1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/Support/ConvertUTF.h"
52 #include "llvm/Support/SaveAndRestore.h"
53 
54 using namespace clang;
55 using namespace sema;
56 using llvm::RoundingMode;
57 
58 /// Determine whether the use of this declaration is valid, without
59 /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
61   // See if this is an auto-typed variable whose initializer we are parsing.
62   if (ParsingInitForAutoVars.count(D))
63     return false;
64 
65   // See if this is a deleted function.
66   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
67     if (FD->isDeleted())
68       return false;
69 
70     // If the function has a deduced return type, and we can't deduce it,
71     // then we can't use it either.
72     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
73         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
74       return false;
75 
76     // See if this is an aligned allocation/deallocation function that is
77     // unavailable.
78     if (TreatUnavailableAsInvalid &&
79         isUnavailableAlignedAllocationFunction(*FD))
80       return false;
81   }
82 
83   // See if this function is unavailable.
84   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
85       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
86     return false;
87 
88   if (isa<UnresolvedUsingIfExistsDecl>(D))
89     return false;
90 
91   return true;
92 }
93 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
95   // Warn if this is used but marked unused.
96   if (const auto *A = D->getAttr<UnusedAttr>()) {
97     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
98     // should diagnose them.
99     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
100         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
101       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
102       if (DC && !DC->hasAttr<UnusedAttr>())
103         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
104     }
105   }
106 }
107 
108 /// Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
110   assert(Decl && Decl->isDeleted());
111 
112   if (Decl->isDefaulted()) {
113     // If the method was explicitly defaulted, point at that declaration.
114     if (!Decl->isImplicit())
115       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
116 
117     // Try to diagnose why this special member function was implicitly
118     // deleted. This might fail, if that reason no longer applies.
119     DiagnoseDeletedDefaultedFunction(Decl);
120     return;
121   }
122 
123   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
124   if (Ctor && Ctor->isInheritingConstructor())
125     return NoteDeletedInheritingConstructor(Ctor);
126 
127   Diag(Decl->getLocation(), diag::note_availability_specified_here)
128     << Decl << 1;
129 }
130 
131 /// Determine whether a FunctionDecl was ever declared with an
132 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
134   for (auto I : D->redecls()) {
135     if (I->getStorageClass() != SC_None)
136       return true;
137   }
138   return false;
139 }
140 
141 /// Check whether we're in an extern inline function and referring to a
142 /// variable or function with internal linkage (C11 6.7.4p3).
143 ///
144 /// This is only a warning because we used to silently accept this code, but
145 /// in many cases it will not behave correctly. This is not enabled in C++ mode
146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
147 /// and so while there may still be user mistakes, most of the time we can't
148 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
150                                                       const NamedDecl *D,
151                                                       SourceLocation Loc) {
152   // This is disabled under C++; there are too many ways for this to fire in
153   // contexts where the warning is a false positive, or where it is technically
154   // correct but benign.
155   if (S.getLangOpts().CPlusPlus)
156     return;
157 
158   // Check if this is an inlined function or method.
159   FunctionDecl *Current = S.getCurFunctionDecl();
160   if (!Current)
161     return;
162   if (!Current->isInlined())
163     return;
164   if (!Current->isExternallyVisible())
165     return;
166 
167   // Check if the decl has internal linkage.
168   if (D->getFormalLinkage() != InternalLinkage)
169     return;
170 
171   // Downgrade from ExtWarn to Extension if
172   //  (1) the supposedly external inline function is in the main file,
173   //      and probably won't be included anywhere else.
174   //  (2) the thing we're referencing is a pure function.
175   //  (3) the thing we're referencing is another inline function.
176   // This last can give us false negatives, but it's better than warning on
177   // wrappers for simple C library functions.
178   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
179   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
180   if (!DowngradeWarning && UsedFn)
181     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
182 
183   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
184                                : diag::ext_internal_in_extern_inline)
185     << /*IsVar=*/!UsedFn << D;
186 
187   S.MaybeSuggestAddingStaticToDecl(Current);
188 
189   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
190       << D;
191 }
192 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
194   const FunctionDecl *First = Cur->getFirstDecl();
195 
196   // Suggest "static" on the function, if possible.
197   if (!hasAnyExplicitStorageClass(First)) {
198     SourceLocation DeclBegin = First->getSourceRange().getBegin();
199     Diag(DeclBegin, diag::note_convert_inline_to_static)
200       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
201   }
202 }
203 
204 /// Determine whether the use of this declaration is valid, and
205 /// emit any corresponding diagnostics.
206 ///
207 /// This routine diagnoses various problems with referencing
208 /// declarations that can occur when using a declaration. For example,
209 /// it might warn if a deprecated or unavailable declaration is being
210 /// used, or produce an error (and return true) if a C++0x deleted
211 /// function is being used.
212 ///
213 /// \returns true if there was an error (this declaration cannot be
214 /// referenced), false otherwise.
215 ///
DiagnoseUseOfDecl(NamedDecl * D,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess,bool AvoidPartialAvailabilityChecks,ObjCInterfaceDecl * ClassReceiver)216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
217                              const ObjCInterfaceDecl *UnknownObjCClass,
218                              bool ObjCPropertyAccess,
219                              bool AvoidPartialAvailabilityChecks,
220                              ObjCInterfaceDecl *ClassReceiver) {
221   SourceLocation Loc = Locs.front();
222   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
223     // If there were any diagnostics suppressed by template argument deduction,
224     // emit them now.
225     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
226     if (Pos != SuppressedDiagnostics.end()) {
227       for (const PartialDiagnosticAt &Suppressed : Pos->second)
228         Diag(Suppressed.first, Suppressed.second);
229 
230       // Clear out the list of suppressed diagnostics, so that we don't emit
231       // them again for this specialization. However, we don't obsolete this
232       // entry from the table, because we want to avoid ever emitting these
233       // diagnostics again.
234       Pos->second.clear();
235     }
236 
237     // C++ [basic.start.main]p3:
238     //   The function 'main' shall not be used within a program.
239     if (cast<FunctionDecl>(D)->isMain())
240       Diag(Loc, diag::ext_main_used);
241 
242     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
243   }
244 
245   // See if this is an auto-typed variable whose initializer we are parsing.
246   if (ParsingInitForAutoVars.count(D)) {
247     if (isa<BindingDecl>(D)) {
248       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
249         << D->getDeclName();
250     } else {
251       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
252         << D->getDeclName() << cast<VarDecl>(D)->getType();
253     }
254     return true;
255   }
256 
257   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
258     // See if this is a deleted function.
259     if (FD->isDeleted()) {
260       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
261       if (Ctor && Ctor->isInheritingConstructor())
262         Diag(Loc, diag::err_deleted_inherited_ctor_use)
263             << Ctor->getParent()
264             << Ctor->getInheritedConstructor().getConstructor()->getParent();
265       else
266         Diag(Loc, diag::err_deleted_function_use);
267       NoteDeletedFunction(FD);
268       return true;
269     }
270 
271     // [expr.prim.id]p4
272     //   A program that refers explicitly or implicitly to a function with a
273     //   trailing requires-clause whose constraint-expression is not satisfied,
274     //   other than to declare it, is ill-formed. [...]
275     //
276     // See if this is a function with constraints that need to be satisfied.
277     // Check this before deducing the return type, as it might instantiate the
278     // definition.
279     if (FD->getTrailingRequiresClause()) {
280       ConstraintSatisfaction Satisfaction;
281       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
282         // A diagnostic will have already been generated (non-constant
283         // constraint expression, for example)
284         return true;
285       if (!Satisfaction.IsSatisfied) {
286         Diag(Loc,
287              diag::err_reference_to_function_with_unsatisfied_constraints)
288             << D;
289         DiagnoseUnsatisfiedConstraint(Satisfaction);
290         return true;
291       }
292     }
293 
294     // If the function has a deduced return type, and we can't deduce it,
295     // then we can't use it either.
296     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
297         DeduceReturnType(FD, Loc))
298       return true;
299 
300     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
301       return true;
302 
303     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
304       return true;
305   }
306 
307   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
308     // Lambdas are only default-constructible or assignable in C++2a onwards.
309     if (MD->getParent()->isLambda() &&
310         ((isa<CXXConstructorDecl>(MD) &&
311           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
312          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
313       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
314         << !isa<CXXConstructorDecl>(MD);
315     }
316   }
317 
318   auto getReferencedObjCProp = [](const NamedDecl *D) ->
319                                       const ObjCPropertyDecl * {
320     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
321       return MD->findPropertyDecl();
322     return nullptr;
323   };
324   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
325     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
326       return true;
327   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
328       return true;
329   }
330 
331   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
332   // Only the variables omp_in and omp_out are allowed in the combiner.
333   // Only the variables omp_priv and omp_orig are allowed in the
334   // initializer-clause.
335   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
336   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
337       isa<VarDecl>(D)) {
338     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
339         << getCurFunction()->HasOMPDeclareReductionCombiner;
340     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
341     return true;
342   }
343 
344   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
345   //  List-items in map clauses on this construct may only refer to the declared
346   //  variable var and entities that could be referenced by a procedure defined
347   //  at the same location
348   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
349       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
350     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
351         << getOpenMPDeclareMapperVarName();
352     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
353     return true;
354   }
355 
356   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
357     Diag(Loc, diag::err_use_of_empty_using_if_exists);
358     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
359     return true;
360   }
361 
362   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
363                              AvoidPartialAvailabilityChecks, ClassReceiver);
364 
365   DiagnoseUnusedOfDecl(*this, D, Loc);
366 
367   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
368 
369   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
370     if (auto *VD = dyn_cast<ValueDecl>(D))
371       checkDeviceDecl(VD, Loc);
372 
373     if (!Context.getTargetInfo().isTLSSupported())
374       if (const auto *VD = dyn_cast<VarDecl>(D))
375         if (VD->getTLSKind() != VarDecl::TLS_None)
376           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
377   }
378 
379   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
380       !isUnevaluatedContext()) {
381     // C++ [expr.prim.req.nested] p3
382     //   A local parameter shall only appear as an unevaluated operand
383     //   (Clause 8) within the constraint-expression.
384     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
385         << D;
386     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
387     return true;
388   }
389 
390   return false;
391 }
392 
393 /// DiagnoseSentinelCalls - This routine checks whether a call or
394 /// message-send is to a declaration with the sentinel attribute, and
395 /// if so, it checks that the requirements of the sentinel are
396 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
398                                  ArrayRef<Expr *> Args) {
399   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
400   if (!attr)
401     return;
402 
403   // The number of formal parameters of the declaration.
404   unsigned numFormalParams;
405 
406   // The kind of declaration.  This is also an index into a %select in
407   // the diagnostic.
408   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
409 
410   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
411     numFormalParams = MD->param_size();
412     calleeType = CT_Method;
413   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
414     numFormalParams = FD->param_size();
415     calleeType = CT_Function;
416   } else if (isa<VarDecl>(D)) {
417     QualType type = cast<ValueDecl>(D)->getType();
418     const FunctionType *fn = nullptr;
419     if (const PointerType *ptr = type->getAs<PointerType>()) {
420       fn = ptr->getPointeeType()->getAs<FunctionType>();
421       if (!fn) return;
422       calleeType = CT_Function;
423     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
424       fn = ptr->getPointeeType()->castAs<FunctionType>();
425       calleeType = CT_Block;
426     } else {
427       return;
428     }
429 
430     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
431       numFormalParams = proto->getNumParams();
432     } else {
433       numFormalParams = 0;
434     }
435   } else {
436     return;
437   }
438 
439   // "nullPos" is the number of formal parameters at the end which
440   // effectively count as part of the variadic arguments.  This is
441   // useful if you would prefer to not have *any* formal parameters,
442   // but the language forces you to have at least one.
443   unsigned nullPos = attr->getNullPos();
444   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
445   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
446 
447   // The number of arguments which should follow the sentinel.
448   unsigned numArgsAfterSentinel = attr->getSentinel();
449 
450   // If there aren't enough arguments for all the formal parameters,
451   // the sentinel, and the args after the sentinel, complain.
452   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
453     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
454     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
455     return;
456   }
457 
458   // Otherwise, find the sentinel expression.
459   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
460   if (!sentinelExpr) return;
461   if (sentinelExpr->isValueDependent()) return;
462   if (Context.isSentinelNullExpr(sentinelExpr)) return;
463 
464   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
465   // or 'NULL' if those are actually defined in the context.  Only use
466   // 'nil' for ObjC methods, where it's much more likely that the
467   // variadic arguments form a list of object pointers.
468   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
469   std::string NullValue;
470   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
471     NullValue = "nil";
472   else if (getLangOpts().CPlusPlus11)
473     NullValue = "nullptr";
474   else if (PP.isMacroDefined("NULL"))
475     NullValue = "NULL";
476   else
477     NullValue = "(void*) 0";
478 
479   if (MissingNilLoc.isInvalid())
480     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
481   else
482     Diag(MissingNilLoc, diag::warn_missing_sentinel)
483       << int(calleeType)
484       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
485   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
486 }
487 
getExprRange(Expr * E) const488 SourceRange Sema::getExprRange(Expr *E) const {
489   return E ? E->getSourceRange() : SourceRange();
490 }
491 
492 //===----------------------------------------------------------------------===//
493 //  Standard Promotions and Conversions
494 //===----------------------------------------------------------------------===//
495 
496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
498   // Handle any placeholder expressions which made it here.
499   if (E->getType()->isPlaceholderType()) {
500     ExprResult result = CheckPlaceholderExpr(E);
501     if (result.isInvalid()) return ExprError();
502     E = result.get();
503   }
504 
505   QualType Ty = E->getType();
506   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
507 
508   if (Ty->isFunctionType()) {
509     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
510       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
511         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
512           return ExprError();
513 
514     E = ImpCastExprToType(E, Context.getPointerType(Ty),
515                           CK_FunctionToPointerDecay).get();
516   } else if (Ty->isArrayType()) {
517     // In C90 mode, arrays only promote to pointers if the array expression is
518     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
519     // type 'array of type' is converted to an expression that has type 'pointer
520     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
521     // that has type 'array of type' ...".  The relevant change is "an lvalue"
522     // (C90) to "an expression" (C99).
523     //
524     // C++ 4.2p1:
525     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
526     // T" can be converted to an rvalue of type "pointer to T".
527     //
528     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
529       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
530                                          CK_ArrayToPointerDecay);
531       if (Res.isInvalid())
532         return ExprError();
533       E = Res.get();
534     }
535   }
536   return E;
537 }
538 
CheckForNullPointerDereference(Sema & S,Expr * E)539 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
540   // Check to see if we are dereferencing a null pointer.  If so,
541   // and if not volatile-qualified, this is undefined behavior that the
542   // optimizer will delete, so warn about it.  People sometimes try to use this
543   // to get a deterministic trap and are surprised by clang's behavior.  This
544   // only handles the pattern "*null", which is a very syntactic check.
545   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
546   if (UO && UO->getOpcode() == UO_Deref &&
547       UO->getSubExpr()->getType()->isPointerType()) {
548     const LangAS AS =
549         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
550     if ((!isTargetAddressSpace(AS) ||
551          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
552         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
553             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
554         !UO->getType().isVolatileQualified()) {
555       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
556                             S.PDiag(diag::warn_indirection_through_null)
557                                 << UO->getSubExpr()->getSourceRange());
558       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
559                             S.PDiag(diag::note_indirection_through_null));
560     }
561   }
562 }
563 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
565                                     SourceLocation AssignLoc,
566                                     const Expr* RHS) {
567   const ObjCIvarDecl *IV = OIRE->getDecl();
568   if (!IV)
569     return;
570 
571   DeclarationName MemberName = IV->getDeclName();
572   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
573   if (!Member || !Member->isStr("isa"))
574     return;
575 
576   const Expr *Base = OIRE->getBase();
577   QualType BaseType = Base->getType();
578   if (OIRE->isArrow())
579     BaseType = BaseType->getPointeeType();
580   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
581     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
582       ObjCInterfaceDecl *ClassDeclared = nullptr;
583       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
584       if (!ClassDeclared->getSuperClass()
585           && (*ClassDeclared->ivar_begin()) == IV) {
586         if (RHS) {
587           NamedDecl *ObjectSetClass =
588             S.LookupSingleName(S.TUScope,
589                                &S.Context.Idents.get("object_setClass"),
590                                SourceLocation(), S.LookupOrdinaryName);
591           if (ObjectSetClass) {
592             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
594                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595                                               "object_setClass(")
596                 << FixItHint::CreateReplacement(
597                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
598                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
599           }
600           else
601             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
602         } else {
603           NamedDecl *ObjectGetClass =
604             S.LookupSingleName(S.TUScope,
605                                &S.Context.Idents.get("object_getClass"),
606                                SourceLocation(), S.LookupOrdinaryName);
607           if (ObjectGetClass)
608             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
609                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
610                                               "object_getClass(")
611                 << FixItHint::CreateReplacement(
612                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
613           else
614             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
615         }
616         S.Diag(IV->getLocation(), diag::note_ivar_decl);
617       }
618     }
619 }
620 
DefaultLvalueConversion(Expr * E)621 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
622   // Handle any placeholder expressions which made it here.
623   if (E->getType()->isPlaceholderType()) {
624     ExprResult result = CheckPlaceholderExpr(E);
625     if (result.isInvalid()) return ExprError();
626     E = result.get();
627   }
628 
629   // C++ [conv.lval]p1:
630   //   A glvalue of a non-function, non-array type T can be
631   //   converted to a prvalue.
632   if (!E->isGLValue()) return E;
633 
634   QualType T = E->getType();
635   assert(!T.isNull() && "r-value conversion on typeless expression?");
636 
637   // lvalue-to-rvalue conversion cannot be applied to function or array types.
638   if (T->isFunctionType() || T->isArrayType())
639     return E;
640 
641   // We don't want to throw lvalue-to-rvalue casts on top of
642   // expressions of certain types in C++.
643   if (getLangOpts().CPlusPlus &&
644       (E->getType() == Context.OverloadTy ||
645        T->isDependentType() ||
646        T->isRecordType()))
647     return E;
648 
649   // The C standard is actually really unclear on this point, and
650   // DR106 tells us what the result should be but not why.  It's
651   // generally best to say that void types just doesn't undergo
652   // lvalue-to-rvalue at all.  Note that expressions of unqualified
653   // 'void' type are never l-values, but qualified void can be.
654   if (T->isVoidType())
655     return E;
656 
657   // OpenCL usually rejects direct accesses to values of 'half' type.
658   if (getLangOpts().OpenCL &&
659       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
660       T->isHalfType()) {
661     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
662       << 0 << T;
663     return ExprError();
664   }
665 
666   CheckForNullPointerDereference(*this, E);
667   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
668     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
669                                      &Context.Idents.get("object_getClass"),
670                                      SourceLocation(), LookupOrdinaryName);
671     if (ObjectGetClass)
672       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
673           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
674           << FixItHint::CreateReplacement(
675                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
676     else
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
678   }
679   else if (const ObjCIvarRefExpr *OIRE =
680             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
681     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
682 
683   // C++ [conv.lval]p1:
684   //   [...] If T is a non-class type, the type of the prvalue is the
685   //   cv-unqualified version of T. Otherwise, the type of the
686   //   rvalue is T.
687   //
688   // C99 6.3.2.1p2:
689   //   If the lvalue has qualified type, the value has the unqualified
690   //   version of the type of the lvalue; otherwise, the value has the
691   //   type of the lvalue.
692   if (T.hasQualifiers())
693     T = T.getUnqualifiedType();
694 
695   // Under the MS ABI, lock down the inheritance model now.
696   if (T->isMemberPointerType() &&
697       Context.getTargetInfo().getCXXABI().isMicrosoft())
698     (void)isCompleteType(E->getExprLoc(), T);
699 
700   ExprResult Res = CheckLValueToRValueConversionOperand(E);
701   if (Res.isInvalid())
702     return Res;
703   E = Res.get();
704 
705   // Loading a __weak object implicitly retains the value, so we need a cleanup to
706   // balance that.
707   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
708     Cleanup.setExprNeedsCleanups(true);
709 
710   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
711     Cleanup.setExprNeedsCleanups(true);
712 
713   // C++ [conv.lval]p3:
714   //   If T is cv std::nullptr_t, the result is a null pointer constant.
715   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
716   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
717                                  CurFPFeatureOverrides());
718 
719   // C11 6.3.2.1p2:
720   //   ... if the lvalue has atomic type, the value has the non-atomic version
721   //   of the type of the lvalue ...
722   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
723     T = Atomic->getValueType().getUnqualifiedType();
724     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
725                                    nullptr, VK_PRValue, FPOptionsOverride());
726   }
727 
728   return Res;
729 }
730 
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)731 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
732   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
733   if (Res.isInvalid())
734     return ExprError();
735   Res = DefaultLvalueConversion(Res.get());
736   if (Res.isInvalid())
737     return ExprError();
738   return Res;
739 }
740 
741 /// CallExprUnaryConversions - a special case of an unary conversion
742 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)743 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
744   QualType Ty = E->getType();
745   ExprResult Res = E;
746   // Only do implicit cast for a function type, but not for a pointer
747   // to function type.
748   if (Ty->isFunctionType()) {
749     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
750                             CK_FunctionToPointerDecay);
751     if (Res.isInvalid())
752       return ExprError();
753   }
754   Res = DefaultLvalueConversion(Res.get());
755   if (Res.isInvalid())
756     return ExprError();
757   return Res.get();
758 }
759 
760 /// UsualUnaryConversions - Performs various conversions that are common to most
761 /// operators (C99 6.3). The conversions of array and function types are
762 /// sometimes suppressed. For example, the array->pointer conversion doesn't
763 /// apply if the array is an argument to the sizeof or address (&) operators.
764 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)765 ExprResult Sema::UsualUnaryConversions(Expr *E) {
766   // First, convert to an r-value.
767   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
768   if (Res.isInvalid())
769     return ExprError();
770   E = Res.get();
771 
772   QualType Ty = E->getType();
773   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
774 
775   // Half FP have to be promoted to float unless it is natively supported
776   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
777     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
778 
779   // Try to perform integral promotions if the object has a theoretically
780   // promotable type.
781   if (Ty->isIntegralOrUnscopedEnumerationType()) {
782     // C99 6.3.1.1p2:
783     //
784     //   The following may be used in an expression wherever an int or
785     //   unsigned int may be used:
786     //     - an object or expression with an integer type whose integer
787     //       conversion rank is less than or equal to the rank of int
788     //       and unsigned int.
789     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
790     //
791     //   If an int can represent all values of the original type, the
792     //   value is converted to an int; otherwise, it is converted to an
793     //   unsigned int. These are called the integer promotions. All
794     //   other types are unchanged by the integer promotions.
795 
796     QualType PTy = Context.isPromotableBitField(E);
797     if (!PTy.isNull()) {
798       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
799       return E;
800     }
801     if (Ty->isPromotableIntegerType()) {
802       QualType PT = Context.getPromotedIntegerType(Ty);
803       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
804       return E;
805     }
806   }
807   return E;
808 }
809 
810 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
811 /// do not have a prototype. Arguments that have type float or __fp16
812 /// are promoted to double. All other argument types are converted by
813 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)814 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
815   QualType Ty = E->getType();
816   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
817 
818   ExprResult Res = UsualUnaryConversions(E);
819   if (Res.isInvalid())
820     return ExprError();
821   E = Res.get();
822 
823   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
824   // promote to double.
825   // Note that default argument promotion applies only to float (and
826   // half/fp16); it does not apply to _Float16.
827   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
828   if (BTy && (BTy->getKind() == BuiltinType::Half ||
829               BTy->getKind() == BuiltinType::Float)) {
830     if (getLangOpts().OpenCL &&
831         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
832       if (BTy->getKind() == BuiltinType::Half) {
833         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
834       }
835     } else {
836       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
837     }
838   }
839   if (BTy &&
840       getLangOpts().getExtendIntArgs() ==
841           LangOptions::ExtendArgsKind::ExtendTo64 &&
842       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
843       Context.getTypeSizeInChars(BTy) <
844           Context.getTypeSizeInChars(Context.LongLongTy)) {
845     E = (Ty->isUnsignedIntegerType())
846             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
847                   .get()
848             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
849     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
850            "Unexpected typesize for LongLongTy");
851   }
852 
853   // C++ performs lvalue-to-rvalue conversion as a default argument
854   // promotion, even on class types, but note:
855   //   C++11 [conv.lval]p2:
856   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
857   //     operand or a subexpression thereof the value contained in the
858   //     referenced object is not accessed. Otherwise, if the glvalue
859   //     has a class type, the conversion copy-initializes a temporary
860   //     of type T from the glvalue and the result of the conversion
861   //     is a prvalue for the temporary.
862   // FIXME: add some way to gate this entire thing for correctness in
863   // potentially potentially evaluated contexts.
864   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
865     ExprResult Temp = PerformCopyInitialization(
866                        InitializedEntity::InitializeTemporary(E->getType()),
867                                                 E->getExprLoc(), E);
868     if (Temp.isInvalid())
869       return ExprError();
870     E = Temp.get();
871   }
872 
873   return E;
874 }
875 
876 /// Determine the degree of POD-ness for an expression.
877 /// Incomplete types are considered POD, since this check can be performed
878 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)879 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
880   if (Ty->isIncompleteType()) {
881     // C++11 [expr.call]p7:
882     //   After these conversions, if the argument does not have arithmetic,
883     //   enumeration, pointer, pointer to member, or class type, the program
884     //   is ill-formed.
885     //
886     // Since we've already performed array-to-pointer and function-to-pointer
887     // decay, the only such type in C++ is cv void. This also handles
888     // initializer lists as variadic arguments.
889     if (Ty->isVoidType())
890       return VAK_Invalid;
891 
892     if (Ty->isObjCObjectType())
893       return VAK_Invalid;
894     return VAK_Valid;
895   }
896 
897   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
898     return VAK_Invalid;
899 
900   if (Ty.isCXX98PODType(Context))
901     return VAK_Valid;
902 
903   // C++11 [expr.call]p7:
904   //   Passing a potentially-evaluated argument of class type (Clause 9)
905   //   having a non-trivial copy constructor, a non-trivial move constructor,
906   //   or a non-trivial destructor, with no corresponding parameter,
907   //   is conditionally-supported with implementation-defined semantics.
908   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
909     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
910       if (!Record->hasNonTrivialCopyConstructor() &&
911           !Record->hasNonTrivialMoveConstructor() &&
912           !Record->hasNonTrivialDestructor())
913         return VAK_ValidInCXX11;
914 
915   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
916     return VAK_Valid;
917 
918   if (Ty->isObjCObjectType())
919     return VAK_Invalid;
920 
921   if (getLangOpts().MSVCCompat)
922     return VAK_MSVCUndefined;
923 
924   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
925   // permitted to reject them. We should consider doing so.
926   return VAK_Undefined;
927 }
928 
checkVariadicArgument(const Expr * E,VariadicCallType CT)929 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
930   // Don't allow one to pass an Objective-C interface to a vararg.
931   const QualType &Ty = E->getType();
932   VarArgKind VAK = isValidVarArgType(Ty);
933 
934   // Complain about passing non-POD types through varargs.
935   switch (VAK) {
936   case VAK_ValidInCXX11:
937     DiagRuntimeBehavior(
938         E->getBeginLoc(), nullptr,
939         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
940     LLVM_FALLTHROUGH;
941   case VAK_Valid:
942     if (Ty->isRecordType()) {
943       // This is unlikely to be what the user intended. If the class has a
944       // 'c_str' member function, the user probably meant to call that.
945       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
946                           PDiag(diag::warn_pass_class_arg_to_vararg)
947                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
948     }
949     break;
950 
951   case VAK_Undefined:
952   case VAK_MSVCUndefined:
953     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
954                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
955                             << getLangOpts().CPlusPlus11 << Ty << CT);
956     break;
957 
958   case VAK_Invalid:
959     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
960       Diag(E->getBeginLoc(),
961            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
962           << Ty << CT;
963     else if (Ty->isObjCObjectType())
964       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
965                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
966                               << Ty << CT);
967     else
968       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
969           << isa<InitListExpr>(E) << Ty << CT;
970     break;
971   }
972 }
973 
974 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
975 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)976 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
977                                                   FunctionDecl *FDecl) {
978   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
979     // Strip the unbridged-cast placeholder expression off, if applicable.
980     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
981         (CT == VariadicMethod ||
982          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
983       E = stripARCUnbridgedCast(E);
984 
985     // Otherwise, do normal placeholder checking.
986     } else {
987       ExprResult ExprRes = CheckPlaceholderExpr(E);
988       if (ExprRes.isInvalid())
989         return ExprError();
990       E = ExprRes.get();
991     }
992   }
993 
994   ExprResult ExprRes = DefaultArgumentPromotion(E);
995   if (ExprRes.isInvalid())
996     return ExprError();
997 
998   // Copy blocks to the heap.
999   if (ExprRes.get()->getType()->isBlockPointerType())
1000     maybeExtendBlockObject(ExprRes);
1001 
1002   E = ExprRes.get();
1003 
1004   // Diagnostics regarding non-POD argument types are
1005   // emitted along with format string checking in Sema::CheckFunctionCall().
1006   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1007     // Turn this into a trap.
1008     CXXScopeSpec SS;
1009     SourceLocation TemplateKWLoc;
1010     UnqualifiedId Name;
1011     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1012                        E->getBeginLoc());
1013     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1014                                           /*HasTrailingLParen=*/true,
1015                                           /*IsAddressOfOperand=*/false);
1016     if (TrapFn.isInvalid())
1017       return ExprError();
1018 
1019     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1020                                     None, E->getEndLoc());
1021     if (Call.isInvalid())
1022       return ExprError();
1023 
1024     ExprResult Comma =
1025         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1026     if (Comma.isInvalid())
1027       return ExprError();
1028     return Comma.get();
1029   }
1030 
1031   if (!getLangOpts().CPlusPlus &&
1032       RequireCompleteType(E->getExprLoc(), E->getType(),
1033                           diag::err_call_incomplete_argument))
1034     return ExprError();
1035 
1036   return E;
1037 }
1038 
1039 /// Converts an integer to complex float type.  Helper function of
1040 /// UsualArithmeticConversions()
1041 ///
1042 /// \return false if the integer expression is an integer type and is
1043 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1044 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1045                                                   ExprResult &ComplexExpr,
1046                                                   QualType IntTy,
1047                                                   QualType ComplexTy,
1048                                                   bool SkipCast) {
1049   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1050   if (SkipCast) return false;
1051   if (IntTy->isIntegerType()) {
1052     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1053     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1054     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1055                                   CK_FloatingRealToComplex);
1056   } else {
1057     assert(IntTy->isComplexIntegerType());
1058     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1059                                   CK_IntegralComplexToFloatingComplex);
1060   }
1061   return false;
1062 }
1063 
1064 /// Handle arithmetic conversion with complex types.  Helper function of
1065 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1066 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1067                                              ExprResult &RHS, QualType LHSType,
1068                                              QualType RHSType,
1069                                              bool IsCompAssign) {
1070   // if we have an integer operand, the result is the complex type.
1071   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1072                                              /*skipCast*/false))
1073     return LHSType;
1074   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1075                                              /*skipCast*/IsCompAssign))
1076     return RHSType;
1077 
1078   // This handles complex/complex, complex/float, or float/complex.
1079   // When both operands are complex, the shorter operand is converted to the
1080   // type of the longer, and that is the type of the result. This corresponds
1081   // to what is done when combining two real floating-point operands.
1082   // The fun begins when size promotion occur across type domains.
1083   // From H&S 6.3.4: When one operand is complex and the other is a real
1084   // floating-point type, the less precise type is converted, within it's
1085   // real or complex domain, to the precision of the other type. For example,
1086   // when combining a "long double" with a "double _Complex", the
1087   // "double _Complex" is promoted to "long double _Complex".
1088 
1089   // Compute the rank of the two types, regardless of whether they are complex.
1090   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1091 
1092   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1093   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1094   QualType LHSElementType =
1095       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1096   QualType RHSElementType =
1097       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1098 
1099   QualType ResultType = S.Context.getComplexType(LHSElementType);
1100   if (Order < 0) {
1101     // Promote the precision of the LHS if not an assignment.
1102     ResultType = S.Context.getComplexType(RHSElementType);
1103     if (!IsCompAssign) {
1104       if (LHSComplexType)
1105         LHS =
1106             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1107       else
1108         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1109     }
1110   } else if (Order > 0) {
1111     // Promote the precision of the RHS.
1112     if (RHSComplexType)
1113       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1114     else
1115       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1116   }
1117   return ResultType;
1118 }
1119 
1120 /// Handle arithmetic conversion from integer to float.  Helper function
1121 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1122 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1123                                            ExprResult &IntExpr,
1124                                            QualType FloatTy, QualType IntTy,
1125                                            bool ConvertFloat, bool ConvertInt) {
1126   if (IntTy->isIntegerType()) {
1127     if (ConvertInt)
1128       // Convert intExpr to the lhs floating point type.
1129       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1130                                     CK_IntegralToFloating);
1131     return FloatTy;
1132   }
1133 
1134   // Convert both sides to the appropriate complex float.
1135   assert(IntTy->isComplexIntegerType());
1136   QualType result = S.Context.getComplexType(FloatTy);
1137 
1138   // _Complex int -> _Complex float
1139   if (ConvertInt)
1140     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1141                                   CK_IntegralComplexToFloatingComplex);
1142 
1143   // float -> _Complex float
1144   if (ConvertFloat)
1145     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1146                                     CK_FloatingRealToComplex);
1147 
1148   return result;
1149 }
1150 
1151 /// Handle arithmethic conversion with floating point types.  Helper
1152 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1153 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1154                                       ExprResult &RHS, QualType LHSType,
1155                                       QualType RHSType, bool IsCompAssign) {
1156   bool LHSFloat = LHSType->isRealFloatingType();
1157   bool RHSFloat = RHSType->isRealFloatingType();
1158 
1159   // N1169 4.1.4: If one of the operands has a floating type and the other
1160   //              operand has a fixed-point type, the fixed-point operand
1161   //              is converted to the floating type [...]
1162   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1163     if (LHSFloat)
1164       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1165     else if (!IsCompAssign)
1166       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1167     return LHSFloat ? LHSType : RHSType;
1168   }
1169 
1170   // If we have two real floating types, convert the smaller operand
1171   // to the bigger result.
1172   if (LHSFloat && RHSFloat) {
1173     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1174     if (order > 0) {
1175       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1176       return LHSType;
1177     }
1178 
1179     assert(order < 0 && "illegal float comparison");
1180     if (!IsCompAssign)
1181       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1182     return RHSType;
1183   }
1184 
1185   if (LHSFloat) {
1186     // Half FP has to be promoted to float unless it is natively supported
1187     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1188       LHSType = S.Context.FloatTy;
1189 
1190     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1191                                       /*ConvertFloat=*/!IsCompAssign,
1192                                       /*ConvertInt=*/ true);
1193   }
1194   assert(RHSFloat);
1195   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1196                                     /*ConvertFloat=*/ true,
1197                                     /*ConvertInt=*/!IsCompAssign);
1198 }
1199 
1200 /// Diagnose attempts to convert between __float128 and long double if
1201 /// there is no support for such conversion. Helper function of
1202 /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1203 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1204                                       QualType RHSType) {
1205   /*  No issue converting if at least one of the types is not a floating point
1206       type or the two types have the same rank.
1207   */
1208   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1209       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1210     return false;
1211 
1212   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1213          "The remaining types must be floating point types.");
1214 
1215   auto *LHSComplex = LHSType->getAs<ComplexType>();
1216   auto *RHSComplex = RHSType->getAs<ComplexType>();
1217 
1218   QualType LHSElemType = LHSComplex ?
1219     LHSComplex->getElementType() : LHSType;
1220   QualType RHSElemType = RHSComplex ?
1221     RHSComplex->getElementType() : RHSType;
1222 
1223   // No issue if the two types have the same representation
1224   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1225       &S.Context.getFloatTypeSemantics(RHSElemType))
1226     return false;
1227 
1228   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1229                                 RHSElemType == S.Context.LongDoubleTy);
1230   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1231                             RHSElemType == S.Context.Float128Ty);
1232 
1233   // We've handled the situation where __float128 and long double have the same
1234   // representation. We allow all conversions for all possible long double types
1235   // except PPC's double double.
1236   return Float128AndLongDouble &&
1237     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1238      &llvm::APFloat::PPCDoubleDouble());
1239 }
1240 
1241 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1242 
1243 namespace {
1244 /// These helper callbacks are placed in an anonymous namespace to
1245 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1246 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1247   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1248 }
1249 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1250 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1251   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1252                              CK_IntegralComplexCast);
1253 }
1254 }
1255 
1256 /// Handle integer arithmetic conversions.  Helper function of
1257 /// UsualArithmeticConversions()
1258 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1259 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1260                                         ExprResult &RHS, QualType LHSType,
1261                                         QualType RHSType, bool IsCompAssign) {
1262   // The rules for this case are in C99 6.3.1.8
1263   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1264   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1265   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1266   if (LHSSigned == RHSSigned) {
1267     // Same signedness; use the higher-ranked type
1268     if (order >= 0) {
1269       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1270       return LHSType;
1271     } else if (!IsCompAssign)
1272       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1273     return RHSType;
1274   } else if (order != (LHSSigned ? 1 : -1)) {
1275     // The unsigned type has greater than or equal rank to the
1276     // signed type, so use the unsigned type
1277     if (RHSSigned) {
1278       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1279       return LHSType;
1280     } else if (!IsCompAssign)
1281       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1282     return RHSType;
1283   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1284     // The two types are different widths; if we are here, that
1285     // means the signed type is larger than the unsigned type, so
1286     // use the signed type.
1287     if (LHSSigned) {
1288       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1289       return LHSType;
1290     } else if (!IsCompAssign)
1291       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1292     return RHSType;
1293   } else {
1294     // The signed type is higher-ranked than the unsigned type,
1295     // but isn't actually any bigger (like unsigned int and long
1296     // on most 32-bit systems).  Use the unsigned type corresponding
1297     // to the signed type.
1298     QualType result =
1299       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1300     RHS = (*doRHSCast)(S, RHS.get(), result);
1301     if (!IsCompAssign)
1302       LHS = (*doLHSCast)(S, LHS.get(), result);
1303     return result;
1304   }
1305 }
1306 
1307 /// Handle conversions with GCC complex int extension.  Helper function
1308 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1309 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1310                                            ExprResult &RHS, QualType LHSType,
1311                                            QualType RHSType,
1312                                            bool IsCompAssign) {
1313   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1314   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1315 
1316   if (LHSComplexInt && RHSComplexInt) {
1317     QualType LHSEltType = LHSComplexInt->getElementType();
1318     QualType RHSEltType = RHSComplexInt->getElementType();
1319     QualType ScalarType =
1320       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1321         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1322 
1323     return S.Context.getComplexType(ScalarType);
1324   }
1325 
1326   if (LHSComplexInt) {
1327     QualType LHSEltType = LHSComplexInt->getElementType();
1328     QualType ScalarType =
1329       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1330         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1331     QualType ComplexType = S.Context.getComplexType(ScalarType);
1332     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1333                               CK_IntegralRealToComplex);
1334 
1335     return ComplexType;
1336   }
1337 
1338   assert(RHSComplexInt);
1339 
1340   QualType RHSEltType = RHSComplexInt->getElementType();
1341   QualType ScalarType =
1342     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1343       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1344   QualType ComplexType = S.Context.getComplexType(ScalarType);
1345 
1346   if (!IsCompAssign)
1347     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1348                               CK_IntegralRealToComplex);
1349   return ComplexType;
1350 }
1351 
1352 /// Return the rank of a given fixed point or integer type. The value itself
1353 /// doesn't matter, but the values must be increasing with proper increasing
1354 /// rank as described in N1169 4.1.1.
GetFixedPointRank(QualType Ty)1355 static unsigned GetFixedPointRank(QualType Ty) {
1356   const auto *BTy = Ty->getAs<BuiltinType>();
1357   assert(BTy && "Expected a builtin type.");
1358 
1359   switch (BTy->getKind()) {
1360   case BuiltinType::ShortFract:
1361   case BuiltinType::UShortFract:
1362   case BuiltinType::SatShortFract:
1363   case BuiltinType::SatUShortFract:
1364     return 1;
1365   case BuiltinType::Fract:
1366   case BuiltinType::UFract:
1367   case BuiltinType::SatFract:
1368   case BuiltinType::SatUFract:
1369     return 2;
1370   case BuiltinType::LongFract:
1371   case BuiltinType::ULongFract:
1372   case BuiltinType::SatLongFract:
1373   case BuiltinType::SatULongFract:
1374     return 3;
1375   case BuiltinType::ShortAccum:
1376   case BuiltinType::UShortAccum:
1377   case BuiltinType::SatShortAccum:
1378   case BuiltinType::SatUShortAccum:
1379     return 4;
1380   case BuiltinType::Accum:
1381   case BuiltinType::UAccum:
1382   case BuiltinType::SatAccum:
1383   case BuiltinType::SatUAccum:
1384     return 5;
1385   case BuiltinType::LongAccum:
1386   case BuiltinType::ULongAccum:
1387   case BuiltinType::SatLongAccum:
1388   case BuiltinType::SatULongAccum:
1389     return 6;
1390   default:
1391     if (BTy->isInteger())
1392       return 0;
1393     llvm_unreachable("Unexpected fixed point or integer type");
1394   }
1395 }
1396 
1397 /// handleFixedPointConversion - Fixed point operations between fixed
1398 /// point types and integers or other fixed point types do not fall under
1399 /// usual arithmetic conversion since these conversions could result in loss
1400 /// of precsision (N1169 4.1.4). These operations should be calculated with
1401 /// the full precision of their result type (N1169 4.1.6.2.1).
handleFixedPointConversion(Sema & S,QualType LHSTy,QualType RHSTy)1402 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1403                                            QualType RHSTy) {
1404   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1405          "Expected at least one of the operands to be a fixed point type");
1406   assert((LHSTy->isFixedPointOrIntegerType() ||
1407           RHSTy->isFixedPointOrIntegerType()) &&
1408          "Special fixed point arithmetic operation conversions are only "
1409          "applied to ints or other fixed point types");
1410 
1411   // If one operand has signed fixed-point type and the other operand has
1412   // unsigned fixed-point type, then the unsigned fixed-point operand is
1413   // converted to its corresponding signed fixed-point type and the resulting
1414   // type is the type of the converted operand.
1415   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1416     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1417   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1418     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1419 
1420   // The result type is the type with the highest rank, whereby a fixed-point
1421   // conversion rank is always greater than an integer conversion rank; if the
1422   // type of either of the operands is a saturating fixedpoint type, the result
1423   // type shall be the saturating fixed-point type corresponding to the type
1424   // with the highest rank; the resulting value is converted (taking into
1425   // account rounding and overflow) to the precision of the resulting type.
1426   // Same ranks between signed and unsigned types are resolved earlier, so both
1427   // types are either signed or both unsigned at this point.
1428   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1429   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1430 
1431   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1432 
1433   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1434     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1435 
1436   return ResultTy;
1437 }
1438 
1439 /// Check that the usual arithmetic conversions can be performed on this pair of
1440 /// expressions that might be of enumeration type.
checkEnumArithmeticConversions(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc,Sema::ArithConvKind ACK)1441 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1442                                            SourceLocation Loc,
1443                                            Sema::ArithConvKind ACK) {
1444   // C++2a [expr.arith.conv]p1:
1445   //   If one operand is of enumeration type and the other operand is of a
1446   //   different enumeration type or a floating-point type, this behavior is
1447   //   deprecated ([depr.arith.conv.enum]).
1448   //
1449   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1450   // Eventually we will presumably reject these cases (in C++23 onwards?).
1451   QualType L = LHS->getType(), R = RHS->getType();
1452   bool LEnum = L->isUnscopedEnumerationType(),
1453        REnum = R->isUnscopedEnumerationType();
1454   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1455   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1456       (REnum && L->isFloatingType())) {
1457     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1458                     ? diag::warn_arith_conv_enum_float_cxx20
1459                     : diag::warn_arith_conv_enum_float)
1460         << LHS->getSourceRange() << RHS->getSourceRange()
1461         << (int)ACK << LEnum << L << R;
1462   } else if (!IsCompAssign && LEnum && REnum &&
1463              !S.Context.hasSameUnqualifiedType(L, R)) {
1464     unsigned DiagID;
1465     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1466         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1467       // If either enumeration type is unnamed, it's less likely that the
1468       // user cares about this, but this situation is still deprecated in
1469       // C++2a. Use a different warning group.
1470       DiagID = S.getLangOpts().CPlusPlus20
1471                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1472                     : diag::warn_arith_conv_mixed_anon_enum_types;
1473     } else if (ACK == Sema::ACK_Conditional) {
1474       // Conditional expressions are separated out because they have
1475       // historically had a different warning flag.
1476       DiagID = S.getLangOpts().CPlusPlus20
1477                    ? diag::warn_conditional_mixed_enum_types_cxx20
1478                    : diag::warn_conditional_mixed_enum_types;
1479     } else if (ACK == Sema::ACK_Comparison) {
1480       // Comparison expressions are separated out because they have
1481       // historically had a different warning flag.
1482       DiagID = S.getLangOpts().CPlusPlus20
1483                    ? diag::warn_comparison_mixed_enum_types_cxx20
1484                    : diag::warn_comparison_mixed_enum_types;
1485     } else {
1486       DiagID = S.getLangOpts().CPlusPlus20
1487                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1488                    : diag::warn_arith_conv_mixed_enum_types;
1489     }
1490     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1491                         << (int)ACK << L << R;
1492   }
1493 }
1494 
1495 /// UsualArithmeticConversions - Performs various conversions that are common to
1496 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1497 /// routine returns the first non-arithmetic type found. The client is
1498 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,ArithConvKind ACK)1499 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1500                                           SourceLocation Loc,
1501                                           ArithConvKind ACK) {
1502   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1503 
1504   if (ACK != ACK_CompAssign) {
1505     LHS = UsualUnaryConversions(LHS.get());
1506     if (LHS.isInvalid())
1507       return QualType();
1508   }
1509 
1510   RHS = UsualUnaryConversions(RHS.get());
1511   if (RHS.isInvalid())
1512     return QualType();
1513 
1514   // For conversion purposes, we ignore any qualifiers.
1515   // For example, "const float" and "float" are equivalent.
1516   QualType LHSType =
1517     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1518   QualType RHSType =
1519     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1520 
1521   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1522   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1523     LHSType = AtomicLHS->getValueType();
1524 
1525   // If both types are identical, no conversion is needed.
1526   if (LHSType == RHSType)
1527     return LHSType;
1528 
1529   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1530   // The caller can deal with this (e.g. pointer + int).
1531   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1532     return QualType();
1533 
1534   // Apply unary and bitfield promotions to the LHS's type.
1535   QualType LHSUnpromotedType = LHSType;
1536   if (LHSType->isPromotableIntegerType())
1537     LHSType = Context.getPromotedIntegerType(LHSType);
1538   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1539   if (!LHSBitfieldPromoteTy.isNull())
1540     LHSType = LHSBitfieldPromoteTy;
1541   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1542     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1543 
1544   // If both types are identical, no conversion is needed.
1545   if (LHSType == RHSType)
1546     return LHSType;
1547 
1548   // At this point, we have two different arithmetic types.
1549 
1550   // Diagnose attempts to convert between __float128 and long double where
1551   // such conversions currently can't be handled.
1552   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1553     return QualType();
1554 
1555   // Handle complex types first (C99 6.3.1.8p1).
1556   if (LHSType->isComplexType() || RHSType->isComplexType())
1557     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1558                                         ACK == ACK_CompAssign);
1559 
1560   // Now handle "real" floating types (i.e. float, double, long double).
1561   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1562     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1563                                  ACK == ACK_CompAssign);
1564 
1565   // Handle GCC complex int extension.
1566   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1567     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1568                                       ACK == ACK_CompAssign);
1569 
1570   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1571     return handleFixedPointConversion(*this, LHSType, RHSType);
1572 
1573   // Finally, we have two differing integer types.
1574   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1575            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1576 }
1577 
1578 //===----------------------------------------------------------------------===//
1579 //  Semantic Analysis for various Expression Types
1580 //===----------------------------------------------------------------------===//
1581 
1582 
1583 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1584 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1585                                 SourceLocation DefaultLoc,
1586                                 SourceLocation RParenLoc,
1587                                 Expr *ControllingExpr,
1588                                 ArrayRef<ParsedType> ArgTypes,
1589                                 ArrayRef<Expr *> ArgExprs) {
1590   unsigned NumAssocs = ArgTypes.size();
1591   assert(NumAssocs == ArgExprs.size());
1592 
1593   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1594   for (unsigned i = 0; i < NumAssocs; ++i) {
1595     if (ArgTypes[i])
1596       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1597     else
1598       Types[i] = nullptr;
1599   }
1600 
1601   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1602                                              ControllingExpr,
1603                                              llvm::makeArrayRef(Types, NumAssocs),
1604                                              ArgExprs);
1605   delete [] Types;
1606   return ER;
1607 }
1608 
1609 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1610 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1611                                  SourceLocation DefaultLoc,
1612                                  SourceLocation RParenLoc,
1613                                  Expr *ControllingExpr,
1614                                  ArrayRef<TypeSourceInfo *> Types,
1615                                  ArrayRef<Expr *> Exprs) {
1616   unsigned NumAssocs = Types.size();
1617   assert(NumAssocs == Exprs.size());
1618 
1619   // Decay and strip qualifiers for the controlling expression type, and handle
1620   // placeholder type replacement. See committee discussion from WG14 DR423.
1621   {
1622     EnterExpressionEvaluationContext Unevaluated(
1623         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1624     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1625     if (R.isInvalid())
1626       return ExprError();
1627     ControllingExpr = R.get();
1628   }
1629 
1630   // The controlling expression is an unevaluated operand, so side effects are
1631   // likely unintended.
1632   if (!inTemplateInstantiation() &&
1633       ControllingExpr->HasSideEffects(Context, false))
1634     Diag(ControllingExpr->getExprLoc(),
1635          diag::warn_side_effects_unevaluated_context);
1636 
1637   bool TypeErrorFound = false,
1638        IsResultDependent = ControllingExpr->isTypeDependent(),
1639        ContainsUnexpandedParameterPack
1640          = ControllingExpr->containsUnexpandedParameterPack();
1641 
1642   for (unsigned i = 0; i < NumAssocs; ++i) {
1643     if (Exprs[i]->containsUnexpandedParameterPack())
1644       ContainsUnexpandedParameterPack = true;
1645 
1646     if (Types[i]) {
1647       if (Types[i]->getType()->containsUnexpandedParameterPack())
1648         ContainsUnexpandedParameterPack = true;
1649 
1650       if (Types[i]->getType()->isDependentType()) {
1651         IsResultDependent = true;
1652       } else {
1653         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1654         // complete object type other than a variably modified type."
1655         unsigned D = 0;
1656         if (Types[i]->getType()->isIncompleteType())
1657           D = diag::err_assoc_type_incomplete;
1658         else if (!Types[i]->getType()->isObjectType())
1659           D = diag::err_assoc_type_nonobject;
1660         else if (Types[i]->getType()->isVariablyModifiedType())
1661           D = diag::err_assoc_type_variably_modified;
1662 
1663         if (D != 0) {
1664           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1665             << Types[i]->getTypeLoc().getSourceRange()
1666             << Types[i]->getType();
1667           TypeErrorFound = true;
1668         }
1669 
1670         // C11 6.5.1.1p2 "No two generic associations in the same generic
1671         // selection shall specify compatible types."
1672         for (unsigned j = i+1; j < NumAssocs; ++j)
1673           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1674               Context.typesAreCompatible(Types[i]->getType(),
1675                                          Types[j]->getType())) {
1676             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1677                  diag::err_assoc_compatible_types)
1678               << Types[j]->getTypeLoc().getSourceRange()
1679               << Types[j]->getType()
1680               << Types[i]->getType();
1681             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1682                  diag::note_compat_assoc)
1683               << Types[i]->getTypeLoc().getSourceRange()
1684               << Types[i]->getType();
1685             TypeErrorFound = true;
1686           }
1687       }
1688     }
1689   }
1690   if (TypeErrorFound)
1691     return ExprError();
1692 
1693   // If we determined that the generic selection is result-dependent, don't
1694   // try to compute the result expression.
1695   if (IsResultDependent)
1696     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1697                                         Exprs, DefaultLoc, RParenLoc,
1698                                         ContainsUnexpandedParameterPack);
1699 
1700   SmallVector<unsigned, 1> CompatIndices;
1701   unsigned DefaultIndex = -1U;
1702   for (unsigned i = 0; i < NumAssocs; ++i) {
1703     if (!Types[i])
1704       DefaultIndex = i;
1705     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1706                                         Types[i]->getType()))
1707       CompatIndices.push_back(i);
1708   }
1709 
1710   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1711   // type compatible with at most one of the types named in its generic
1712   // association list."
1713   if (CompatIndices.size() > 1) {
1714     // We strip parens here because the controlling expression is typically
1715     // parenthesized in macro definitions.
1716     ControllingExpr = ControllingExpr->IgnoreParens();
1717     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1718         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1719         << (unsigned)CompatIndices.size();
1720     for (unsigned I : CompatIndices) {
1721       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1722            diag::note_compat_assoc)
1723         << Types[I]->getTypeLoc().getSourceRange()
1724         << Types[I]->getType();
1725     }
1726     return ExprError();
1727   }
1728 
1729   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1730   // its controlling expression shall have type compatible with exactly one of
1731   // the types named in its generic association list."
1732   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1733     // We strip parens here because the controlling expression is typically
1734     // parenthesized in macro definitions.
1735     ControllingExpr = ControllingExpr->IgnoreParens();
1736     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1737         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1738     return ExprError();
1739   }
1740 
1741   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1742   // type name that is compatible with the type of the controlling expression,
1743   // then the result expression of the generic selection is the expression
1744   // in that generic association. Otherwise, the result expression of the
1745   // generic selection is the expression in the default generic association."
1746   unsigned ResultIndex =
1747     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1748 
1749   return GenericSelectionExpr::Create(
1750       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1751       ContainsUnexpandedParameterPack, ResultIndex);
1752 }
1753 
1754 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1755 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1756 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1757                                      unsigned Offset) {
1758   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1759                                         S.getLangOpts());
1760 }
1761 
1762 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1763 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
BuildCookedLiteralOperatorCall(Sema & S,Scope * Scope,IdentifierInfo * UDSuffix,SourceLocation UDSuffixLoc,ArrayRef<Expr * > Args,SourceLocation LitEndLoc)1764 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1765                                                  IdentifierInfo *UDSuffix,
1766                                                  SourceLocation UDSuffixLoc,
1767                                                  ArrayRef<Expr*> Args,
1768                                                  SourceLocation LitEndLoc) {
1769   assert(Args.size() <= 2 && "too many arguments for literal operator");
1770 
1771   QualType ArgTy[2];
1772   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1773     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1774     if (ArgTy[ArgIdx]->isArrayType())
1775       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1776   }
1777 
1778   DeclarationName OpName =
1779     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1780   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1781   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1782 
1783   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1784   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1785                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1786                               /*AllowStringTemplatePack*/ false,
1787                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1788     return ExprError();
1789 
1790   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1791 }
1792 
1793 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1794 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1795 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1796 /// multiple tokens.  However, the common case is that StringToks points to one
1797 /// string.
1798 ///
1799 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1800 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1801   assert(!StringToks.empty() && "Must have at least one string!");
1802 
1803   StringLiteralParser Literal(StringToks, PP);
1804   if (Literal.hadError)
1805     return ExprError();
1806 
1807   SmallVector<SourceLocation, 4> StringTokLocs;
1808   for (const Token &Tok : StringToks)
1809     StringTokLocs.push_back(Tok.getLocation());
1810 
1811   QualType CharTy = Context.CharTy;
1812   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1813   if (Literal.isWide()) {
1814     CharTy = Context.getWideCharType();
1815     Kind = StringLiteral::Wide;
1816   } else if (Literal.isUTF8()) {
1817     if (getLangOpts().Char8)
1818       CharTy = Context.Char8Ty;
1819     Kind = StringLiteral::UTF8;
1820   } else if (Literal.isUTF16()) {
1821     CharTy = Context.Char16Ty;
1822     Kind = StringLiteral::UTF16;
1823   } else if (Literal.isUTF32()) {
1824     CharTy = Context.Char32Ty;
1825     Kind = StringLiteral::UTF32;
1826   } else if (Literal.isPascal()) {
1827     CharTy = Context.UnsignedCharTy;
1828   }
1829 
1830   // Warn on initializing an array of char from a u8 string literal; this
1831   // becomes ill-formed in C++2a.
1832   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1833       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1834     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1835 
1836     // Create removals for all 'u8' prefixes in the string literal(s). This
1837     // ensures C++2a compatibility (but may change the program behavior when
1838     // built by non-Clang compilers for which the execution character set is
1839     // not always UTF-8).
1840     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1841     SourceLocation RemovalDiagLoc;
1842     for (const Token &Tok : StringToks) {
1843       if (Tok.getKind() == tok::utf8_string_literal) {
1844         if (RemovalDiagLoc.isInvalid())
1845           RemovalDiagLoc = Tok.getLocation();
1846         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1847             Tok.getLocation(),
1848             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1849                                            getSourceManager(), getLangOpts())));
1850       }
1851     }
1852     Diag(RemovalDiagLoc, RemovalDiag);
1853   }
1854 
1855   QualType StrTy =
1856       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1857 
1858   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1859   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1860                                              Kind, Literal.Pascal, StrTy,
1861                                              &StringTokLocs[0],
1862                                              StringTokLocs.size());
1863   if (Literal.getUDSuffix().empty())
1864     return Lit;
1865 
1866   // We're building a user-defined literal.
1867   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1868   SourceLocation UDSuffixLoc =
1869     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1870                    Literal.getUDSuffixOffset());
1871 
1872   // Make sure we're allowed user-defined literals here.
1873   if (!UDLScope)
1874     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1875 
1876   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1877   //   operator "" X (str, len)
1878   QualType SizeType = Context.getSizeType();
1879 
1880   DeclarationName OpName =
1881     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1882   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1883   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1884 
1885   QualType ArgTy[] = {
1886     Context.getArrayDecayedType(StrTy), SizeType
1887   };
1888 
1889   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1890   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1891                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1892                                 /*AllowStringTemplatePack*/ true,
1893                                 /*DiagnoseMissing*/ true, Lit)) {
1894 
1895   case LOLR_Cooked: {
1896     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1897     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1898                                                     StringTokLocs[0]);
1899     Expr *Args[] = { Lit, LenArg };
1900 
1901     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1902   }
1903 
1904   case LOLR_Template: {
1905     TemplateArgumentListInfo ExplicitArgs;
1906     TemplateArgument Arg(Lit);
1907     TemplateArgumentLocInfo ArgInfo(Lit);
1908     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1909     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1910                                     &ExplicitArgs);
1911   }
1912 
1913   case LOLR_StringTemplatePack: {
1914     TemplateArgumentListInfo ExplicitArgs;
1915 
1916     unsigned CharBits = Context.getIntWidth(CharTy);
1917     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1918     llvm::APSInt Value(CharBits, CharIsUnsigned);
1919 
1920     TemplateArgument TypeArg(CharTy);
1921     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1922     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1923 
1924     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1925       Value = Lit->getCodeUnit(I);
1926       TemplateArgument Arg(Context, Value, CharTy);
1927       TemplateArgumentLocInfo ArgInfo;
1928       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1929     }
1930     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1931                                     &ExplicitArgs);
1932   }
1933   case LOLR_Raw:
1934   case LOLR_ErrorNoDiagnostic:
1935     llvm_unreachable("unexpected literal operator lookup result");
1936   case LOLR_Error:
1937     return ExprError();
1938   }
1939   llvm_unreachable("unexpected literal operator lookup result");
1940 }
1941 
1942 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1943 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1944                        SourceLocation Loc,
1945                        const CXXScopeSpec *SS) {
1946   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1947   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1948 }
1949 
1950 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1951 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1952                        const DeclarationNameInfo &NameInfo,
1953                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1954                        SourceLocation TemplateKWLoc,
1955                        const TemplateArgumentListInfo *TemplateArgs) {
1956   NestedNameSpecifierLoc NNS =
1957       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1958   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1959                           TemplateArgs);
1960 }
1961 
1962 // CUDA/HIP: Check whether a captured reference variable is referencing a
1963 // host variable in a device or host device lambda.
isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema & S,VarDecl * VD)1964 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1965                                                             VarDecl *VD) {
1966   if (!S.getLangOpts().CUDA || !VD->hasInit())
1967     return false;
1968   assert(VD->getType()->isReferenceType());
1969 
1970   // Check whether the reference variable is referencing a host variable.
1971   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1972   if (!DRE)
1973     return false;
1974   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1975   if (!Referee || !Referee->hasGlobalStorage() ||
1976       Referee->hasAttr<CUDADeviceAttr>())
1977     return false;
1978 
1979   // Check whether the current function is a device or host device lambda.
1980   // Check whether the reference variable is a capture by getDeclContext()
1981   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1982   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1983   if (MD && MD->getParent()->isLambda() &&
1984       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1985       VD->getDeclContext() != MD)
1986     return true;
1987 
1988   return false;
1989 }
1990 
getNonOdrUseReasonInCurrentContext(ValueDecl * D)1991 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1992   // A declaration named in an unevaluated operand never constitutes an odr-use.
1993   if (isUnevaluatedContext())
1994     return NOUR_Unevaluated;
1995 
1996   // C++2a [basic.def.odr]p4:
1997   //   A variable x whose name appears as a potentially-evaluated expression e
1998   //   is odr-used by e unless [...] x is a reference that is usable in
1999   //   constant expressions.
2000   // CUDA/HIP:
2001   //   If a reference variable referencing a host variable is captured in a
2002   //   device or host device lambda, the value of the referee must be copied
2003   //   to the capture and the reference variable must be treated as odr-use
2004   //   since the value of the referee is not known at compile time and must
2005   //   be loaded from the captured.
2006   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2007     if (VD->getType()->isReferenceType() &&
2008         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2009         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2010         VD->isUsableInConstantExpressions(Context))
2011       return NOUR_Constant;
2012   }
2013 
2014   // All remaining non-variable cases constitute an odr-use. For variables, we
2015   // need to wait and see how the expression is used.
2016   return NOUR_None;
2017 }
2018 
2019 /// BuildDeclRefExpr - Build an expression that references a
2020 /// declaration that does not require a closure capture.
2021 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,NestedNameSpecifierLoc NNS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2022 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2023                        const DeclarationNameInfo &NameInfo,
2024                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2025                        SourceLocation TemplateKWLoc,
2026                        const TemplateArgumentListInfo *TemplateArgs) {
2027   bool RefersToCapturedVariable =
2028       isa<VarDecl>(D) &&
2029       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2030 
2031   DeclRefExpr *E = DeclRefExpr::Create(
2032       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2033       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2034   MarkDeclRefReferenced(E);
2035 
2036   // C++ [except.spec]p17:
2037   //   An exception-specification is considered to be needed when:
2038   //   - in an expression, the function is the unique lookup result or
2039   //     the selected member of a set of overloaded functions.
2040   //
2041   // We delay doing this until after we've built the function reference and
2042   // marked it as used so that:
2043   //  a) if the function is defaulted, we get errors from defining it before /
2044   //     instead of errors from computing its exception specification, and
2045   //  b) if the function is a defaulted comparison, we can use the body we
2046   //     build when defining it as input to the exception specification
2047   //     computation rather than computing a new body.
2048   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2049     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2050       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2051         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2052     }
2053   }
2054 
2055   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2056       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2057       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2058     getCurFunction()->recordUseOfWeak(E);
2059 
2060   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2061   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2062     FD = IFD->getAnonField();
2063   if (FD) {
2064     UnusedPrivateFields.remove(FD);
2065     // Just in case we're building an illegal pointer-to-member.
2066     if (FD->isBitField())
2067       E->setObjectKind(OK_BitField);
2068   }
2069 
2070   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2071   // designates a bit-field.
2072   if (auto *BD = dyn_cast<BindingDecl>(D))
2073     if (auto *BE = BD->getBinding())
2074       E->setObjectKind(BE->getObjectKind());
2075 
2076   return E;
2077 }
2078 
2079 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2080 /// possibly a list of template arguments.
2081 ///
2082 /// If this produces template arguments, it is permitted to call
2083 /// DecomposeTemplateName.
2084 ///
2085 /// This actually loses a lot of source location information for
2086 /// non-standard name kinds; we should consider preserving that in
2087 /// some way.
2088 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)2089 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2090                              TemplateArgumentListInfo &Buffer,
2091                              DeclarationNameInfo &NameInfo,
2092                              const TemplateArgumentListInfo *&TemplateArgs) {
2093   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2094     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2095     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2096 
2097     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2098                                        Id.TemplateId->NumArgs);
2099     translateTemplateArguments(TemplateArgsPtr, Buffer);
2100 
2101     TemplateName TName = Id.TemplateId->Template.get();
2102     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2103     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2104     TemplateArgs = &Buffer;
2105   } else {
2106     NameInfo = GetNameFromUnqualifiedId(Id);
2107     TemplateArgs = nullptr;
2108   }
2109 }
2110 
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)2111 static void emitEmptyLookupTypoDiagnostic(
2112     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2113     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2114     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2115   DeclContext *Ctx =
2116       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2117   if (!TC) {
2118     // Emit a special diagnostic for failed member lookups.
2119     // FIXME: computing the declaration context might fail here (?)
2120     if (Ctx)
2121       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2122                                                  << SS.getRange();
2123     else
2124       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2125     return;
2126   }
2127 
2128   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2129   bool DroppedSpecifier =
2130       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2131   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2132                         ? diag::note_implicit_param_decl
2133                         : diag::note_previous_decl;
2134   if (!Ctx)
2135     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2136                          SemaRef.PDiag(NoteID));
2137   else
2138     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2139                                  << Typo << Ctx << DroppedSpecifier
2140                                  << SS.getRange(),
2141                          SemaRef.PDiag(NoteID));
2142 }
2143 
2144 /// Diagnose a lookup that found results in an enclosing class during error
2145 /// recovery. This usually indicates that the results were found in a dependent
2146 /// base class that could not be searched as part of a template definition.
2147 /// Always issues a diagnostic (though this may be only a warning in MS
2148 /// compatibility mode).
2149 ///
2150 /// Return \c true if the error is unrecoverable, or \c false if the caller
2151 /// should attempt to recover using these lookup results.
DiagnoseDependentMemberLookup(LookupResult & R)2152 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2153   // During a default argument instantiation the CurContext points
2154   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2155   // function parameter list, hence add an explicit check.
2156   bool isDefaultArgument =
2157       !CodeSynthesisContexts.empty() &&
2158       CodeSynthesisContexts.back().Kind ==
2159           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2160   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2161   bool isInstance = CurMethod && CurMethod->isInstance() &&
2162                     R.getNamingClass() == CurMethod->getParent() &&
2163                     !isDefaultArgument;
2164 
2165   // There are two ways we can find a class-scope declaration during template
2166   // instantiation that we did not find in the template definition: if it is a
2167   // member of a dependent base class, or if it is declared after the point of
2168   // use in the same class. Distinguish these by comparing the class in which
2169   // the member was found to the naming class of the lookup.
2170   unsigned DiagID = diag::err_found_in_dependent_base;
2171   unsigned NoteID = diag::note_member_declared_at;
2172   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2173     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2174                                       : diag::err_found_later_in_class;
2175   } else if (getLangOpts().MSVCCompat) {
2176     DiagID = diag::ext_found_in_dependent_base;
2177     NoteID = diag::note_dependent_member_use;
2178   }
2179 
2180   if (isInstance) {
2181     // Give a code modification hint to insert 'this->'.
2182     Diag(R.getNameLoc(), DiagID)
2183         << R.getLookupName()
2184         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2185     CheckCXXThisCapture(R.getNameLoc());
2186   } else {
2187     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2188     // they're not shadowed).
2189     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2190   }
2191 
2192   for (NamedDecl *D : R)
2193     Diag(D->getLocation(), NoteID);
2194 
2195   // Return true if we are inside a default argument instantiation
2196   // and the found name refers to an instance member function, otherwise
2197   // the caller will try to create an implicit member call and this is wrong
2198   // for default arguments.
2199   //
2200   // FIXME: Is this special case necessary? We could allow the caller to
2201   // diagnose this.
2202   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2203     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2204     return true;
2205   }
2206 
2207   // Tell the callee to try to recover.
2208   return false;
2209 }
2210 
2211 /// Diagnose an empty lookup.
2212 ///
2213 /// \return false if new lookup candidates were found
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,CorrectionCandidateCallback & CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)2214 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2215                                CorrectionCandidateCallback &CCC,
2216                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2217                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2218   DeclarationName Name = R.getLookupName();
2219 
2220   unsigned diagnostic = diag::err_undeclared_var_use;
2221   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2222   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2223       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2224       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2225     diagnostic = diag::err_undeclared_use;
2226     diagnostic_suggest = diag::err_undeclared_use_suggest;
2227   }
2228 
2229   // If the original lookup was an unqualified lookup, fake an
2230   // unqualified lookup.  This is useful when (for example) the
2231   // original lookup would not have found something because it was a
2232   // dependent name.
2233   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2234   while (DC) {
2235     if (isa<CXXRecordDecl>(DC)) {
2236       LookupQualifiedName(R, DC);
2237 
2238       if (!R.empty()) {
2239         // Don't give errors about ambiguities in this lookup.
2240         R.suppressDiagnostics();
2241 
2242         // If there's a best viable function among the results, only mention
2243         // that one in the notes.
2244         OverloadCandidateSet Candidates(R.getNameLoc(),
2245                                         OverloadCandidateSet::CSK_Normal);
2246         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2247         OverloadCandidateSet::iterator Best;
2248         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2249             OR_Success) {
2250           R.clear();
2251           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2252           R.resolveKind();
2253         }
2254 
2255         return DiagnoseDependentMemberLookup(R);
2256       }
2257 
2258       R.clear();
2259     }
2260 
2261     DC = DC->getLookupParent();
2262   }
2263 
2264   // We didn't find anything, so try to correct for a typo.
2265   TypoCorrection Corrected;
2266   if (S && Out) {
2267     SourceLocation TypoLoc = R.getNameLoc();
2268     assert(!ExplicitTemplateArgs &&
2269            "Diagnosing an empty lookup with explicit template args!");
2270     *Out = CorrectTypoDelayed(
2271         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2272         [=](const TypoCorrection &TC) {
2273           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2274                                         diagnostic, diagnostic_suggest);
2275         },
2276         nullptr, CTK_ErrorRecovery);
2277     if (*Out)
2278       return true;
2279   } else if (S &&
2280              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2281                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2282     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2283     bool DroppedSpecifier =
2284         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2285     R.setLookupName(Corrected.getCorrection());
2286 
2287     bool AcceptableWithRecovery = false;
2288     bool AcceptableWithoutRecovery = false;
2289     NamedDecl *ND = Corrected.getFoundDecl();
2290     if (ND) {
2291       if (Corrected.isOverloaded()) {
2292         OverloadCandidateSet OCS(R.getNameLoc(),
2293                                  OverloadCandidateSet::CSK_Normal);
2294         OverloadCandidateSet::iterator Best;
2295         for (NamedDecl *CD : Corrected) {
2296           if (FunctionTemplateDecl *FTD =
2297                    dyn_cast<FunctionTemplateDecl>(CD))
2298             AddTemplateOverloadCandidate(
2299                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2300                 Args, OCS);
2301           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2302             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2303               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2304                                    Args, OCS);
2305         }
2306         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2307         case OR_Success:
2308           ND = Best->FoundDecl;
2309           Corrected.setCorrectionDecl(ND);
2310           break;
2311         default:
2312           // FIXME: Arbitrarily pick the first declaration for the note.
2313           Corrected.setCorrectionDecl(ND);
2314           break;
2315         }
2316       }
2317       R.addDecl(ND);
2318       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2319         CXXRecordDecl *Record = nullptr;
2320         if (Corrected.getCorrectionSpecifier()) {
2321           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2322           Record = Ty->getAsCXXRecordDecl();
2323         }
2324         if (!Record)
2325           Record = cast<CXXRecordDecl>(
2326               ND->getDeclContext()->getRedeclContext());
2327         R.setNamingClass(Record);
2328       }
2329 
2330       auto *UnderlyingND = ND->getUnderlyingDecl();
2331       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2332                                isa<FunctionTemplateDecl>(UnderlyingND);
2333       // FIXME: If we ended up with a typo for a type name or
2334       // Objective-C class name, we're in trouble because the parser
2335       // is in the wrong place to recover. Suggest the typo
2336       // correction, but don't make it a fix-it since we're not going
2337       // to recover well anyway.
2338       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2339                                   getAsTypeTemplateDecl(UnderlyingND) ||
2340                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2341     } else {
2342       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2343       // because we aren't able to recover.
2344       AcceptableWithoutRecovery = true;
2345     }
2346 
2347     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2348       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2349                             ? diag::note_implicit_param_decl
2350                             : diag::note_previous_decl;
2351       if (SS.isEmpty())
2352         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2353                      PDiag(NoteID), AcceptableWithRecovery);
2354       else
2355         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2356                                   << Name << computeDeclContext(SS, false)
2357                                   << DroppedSpecifier << SS.getRange(),
2358                      PDiag(NoteID), AcceptableWithRecovery);
2359 
2360       // Tell the callee whether to try to recover.
2361       return !AcceptableWithRecovery;
2362     }
2363   }
2364   R.clear();
2365 
2366   // Emit a special diagnostic for failed member lookups.
2367   // FIXME: computing the declaration context might fail here (?)
2368   if (!SS.isEmpty()) {
2369     Diag(R.getNameLoc(), diag::err_no_member)
2370       << Name << computeDeclContext(SS, false)
2371       << SS.getRange();
2372     return true;
2373   }
2374 
2375   // Give up, we can't recover.
2376   Diag(R.getNameLoc(), diagnostic) << Name;
2377   return true;
2378 }
2379 
2380 /// In Microsoft mode, if we are inside a template class whose parent class has
2381 /// dependent base classes, and we can't resolve an unqualified identifier, then
2382 /// assume the identifier is a member of a dependent base class.  We can only
2383 /// recover successfully in static methods, instance methods, and other contexts
2384 /// where 'this' is available.  This doesn't precisely match MSVC's
2385 /// instantiation model, but it's close enough.
2386 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2387 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2388                                DeclarationNameInfo &NameInfo,
2389                                SourceLocation TemplateKWLoc,
2390                                const TemplateArgumentListInfo *TemplateArgs) {
2391   // Only try to recover from lookup into dependent bases in static methods or
2392   // contexts where 'this' is available.
2393   QualType ThisType = S.getCurrentThisType();
2394   const CXXRecordDecl *RD = nullptr;
2395   if (!ThisType.isNull())
2396     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2397   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2398     RD = MD->getParent();
2399   if (!RD || !RD->hasAnyDependentBases())
2400     return nullptr;
2401 
2402   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2403   // is available, suggest inserting 'this->' as a fixit.
2404   SourceLocation Loc = NameInfo.getLoc();
2405   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2406   DB << NameInfo.getName() << RD;
2407 
2408   if (!ThisType.isNull()) {
2409     DB << FixItHint::CreateInsertion(Loc, "this->");
2410     return CXXDependentScopeMemberExpr::Create(
2411         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2412         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2413         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2414   }
2415 
2416   // Synthesize a fake NNS that points to the derived class.  This will
2417   // perform name lookup during template instantiation.
2418   CXXScopeSpec SS;
2419   auto *NNS =
2420       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2421   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2422   return DependentScopeDeclRefExpr::Create(
2423       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2424       TemplateArgs);
2425 }
2426 
2427 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2428 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2429                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2430                         bool HasTrailingLParen, bool IsAddressOfOperand,
2431                         CorrectionCandidateCallback *CCC,
2432                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2433   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2434          "cannot be direct & operand and have a trailing lparen");
2435   if (SS.isInvalid())
2436     return ExprError();
2437 
2438   TemplateArgumentListInfo TemplateArgsBuffer;
2439 
2440   // Decompose the UnqualifiedId into the following data.
2441   DeclarationNameInfo NameInfo;
2442   const TemplateArgumentListInfo *TemplateArgs;
2443   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2444 
2445   DeclarationName Name = NameInfo.getName();
2446   IdentifierInfo *II = Name.getAsIdentifierInfo();
2447   SourceLocation NameLoc = NameInfo.getLoc();
2448 
2449   if (II && II->isEditorPlaceholder()) {
2450     // FIXME: When typed placeholders are supported we can create a typed
2451     // placeholder expression node.
2452     return ExprError();
2453   }
2454 
2455   // C++ [temp.dep.expr]p3:
2456   //   An id-expression is type-dependent if it contains:
2457   //     -- an identifier that was declared with a dependent type,
2458   //        (note: handled after lookup)
2459   //     -- a template-id that is dependent,
2460   //        (note: handled in BuildTemplateIdExpr)
2461   //     -- a conversion-function-id that specifies a dependent type,
2462   //     -- a nested-name-specifier that contains a class-name that
2463   //        names a dependent type.
2464   // Determine whether this is a member of an unknown specialization;
2465   // we need to handle these differently.
2466   bool DependentID = false;
2467   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2468       Name.getCXXNameType()->isDependentType()) {
2469     DependentID = true;
2470   } else if (SS.isSet()) {
2471     if (DeclContext *DC = computeDeclContext(SS, false)) {
2472       if (RequireCompleteDeclContext(SS, DC))
2473         return ExprError();
2474     } else {
2475       DependentID = true;
2476     }
2477   }
2478 
2479   if (DependentID)
2480     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2481                                       IsAddressOfOperand, TemplateArgs);
2482 
2483   // Perform the required lookup.
2484   LookupResult R(*this, NameInfo,
2485                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2486                      ? LookupObjCImplicitSelfParam
2487                      : LookupOrdinaryName);
2488   if (TemplateKWLoc.isValid() || TemplateArgs) {
2489     // Lookup the template name again to correctly establish the context in
2490     // which it was found. This is really unfortunate as we already did the
2491     // lookup to determine that it was a template name in the first place. If
2492     // this becomes a performance hit, we can work harder to preserve those
2493     // results until we get here but it's likely not worth it.
2494     bool MemberOfUnknownSpecialization;
2495     AssumedTemplateKind AssumedTemplate;
2496     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2497                            MemberOfUnknownSpecialization, TemplateKWLoc,
2498                            &AssumedTemplate))
2499       return ExprError();
2500 
2501     if (MemberOfUnknownSpecialization ||
2502         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2503       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2504                                         IsAddressOfOperand, TemplateArgs);
2505   } else {
2506     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2507     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2508 
2509     // If the result might be in a dependent base class, this is a dependent
2510     // id-expression.
2511     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2512       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2513                                         IsAddressOfOperand, TemplateArgs);
2514 
2515     // If this reference is in an Objective-C method, then we need to do
2516     // some special Objective-C lookup, too.
2517     if (IvarLookupFollowUp) {
2518       ExprResult E(LookupInObjCMethod(R, S, II, true));
2519       if (E.isInvalid())
2520         return ExprError();
2521 
2522       if (Expr *Ex = E.getAs<Expr>())
2523         return Ex;
2524     }
2525   }
2526 
2527   if (R.isAmbiguous())
2528     return ExprError();
2529 
2530   // This could be an implicitly declared function reference (legal in C90,
2531   // extension in C99, forbidden in C++).
2532   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2533     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2534     if (D) R.addDecl(D);
2535   }
2536 
2537   // Determine whether this name might be a candidate for
2538   // argument-dependent lookup.
2539   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2540 
2541   if (R.empty() && !ADL) {
2542     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2543       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2544                                                    TemplateKWLoc, TemplateArgs))
2545         return E;
2546     }
2547 
2548     // Don't diagnose an empty lookup for inline assembly.
2549     if (IsInlineAsmIdentifier)
2550       return ExprError();
2551 
2552     // If this name wasn't predeclared and if this is not a function
2553     // call, diagnose the problem.
2554     TypoExpr *TE = nullptr;
2555     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2556                                                        : nullptr);
2557     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2558     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2559            "Typo correction callback misconfigured");
2560     if (CCC) {
2561       // Make sure the callback knows what the typo being diagnosed is.
2562       CCC->setTypoName(II);
2563       if (SS.isValid())
2564         CCC->setTypoNNS(SS.getScopeRep());
2565     }
2566     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2567     // a template name, but we happen to have always already looked up the name
2568     // before we get here if it must be a template name.
2569     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2570                             None, &TE)) {
2571       if (TE && KeywordReplacement) {
2572         auto &State = getTypoExprState(TE);
2573         auto BestTC = State.Consumer->getNextCorrection();
2574         if (BestTC.isKeyword()) {
2575           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2576           if (State.DiagHandler)
2577             State.DiagHandler(BestTC);
2578           KeywordReplacement->startToken();
2579           KeywordReplacement->setKind(II->getTokenID());
2580           KeywordReplacement->setIdentifierInfo(II);
2581           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2582           // Clean up the state associated with the TypoExpr, since it has
2583           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2584           clearDelayedTypo(TE);
2585           // Signal that a correction to a keyword was performed by returning a
2586           // valid-but-null ExprResult.
2587           return (Expr*)nullptr;
2588         }
2589         State.Consumer->resetCorrectionStream();
2590       }
2591       return TE ? TE : ExprError();
2592     }
2593 
2594     assert(!R.empty() &&
2595            "DiagnoseEmptyLookup returned false but added no results");
2596 
2597     // If we found an Objective-C instance variable, let
2598     // LookupInObjCMethod build the appropriate expression to
2599     // reference the ivar.
2600     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2601       R.clear();
2602       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2603       // In a hopelessly buggy code, Objective-C instance variable
2604       // lookup fails and no expression will be built to reference it.
2605       if (!E.isInvalid() && !E.get())
2606         return ExprError();
2607       return E;
2608     }
2609   }
2610 
2611   // This is guaranteed from this point on.
2612   assert(!R.empty() || ADL);
2613 
2614   // Check whether this might be a C++ implicit instance member access.
2615   // C++ [class.mfct.non-static]p3:
2616   //   When an id-expression that is not part of a class member access
2617   //   syntax and not used to form a pointer to member is used in the
2618   //   body of a non-static member function of class X, if name lookup
2619   //   resolves the name in the id-expression to a non-static non-type
2620   //   member of some class C, the id-expression is transformed into a
2621   //   class member access expression using (*this) as the
2622   //   postfix-expression to the left of the . operator.
2623   //
2624   // But we don't actually need to do this for '&' operands if R
2625   // resolved to a function or overloaded function set, because the
2626   // expression is ill-formed if it actually works out to be a
2627   // non-static member function:
2628   //
2629   // C++ [expr.ref]p4:
2630   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2631   //   [t]he expression can be used only as the left-hand operand of a
2632   //   member function call.
2633   //
2634   // There are other safeguards against such uses, but it's important
2635   // to get this right here so that we don't end up making a
2636   // spuriously dependent expression if we're inside a dependent
2637   // instance method.
2638   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2639     bool MightBeImplicitMember;
2640     if (!IsAddressOfOperand)
2641       MightBeImplicitMember = true;
2642     else if (!SS.isEmpty())
2643       MightBeImplicitMember = false;
2644     else if (R.isOverloadedResult())
2645       MightBeImplicitMember = false;
2646     else if (R.isUnresolvableResult())
2647       MightBeImplicitMember = true;
2648     else
2649       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2650                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2651                               isa<MSPropertyDecl>(R.getFoundDecl());
2652 
2653     if (MightBeImplicitMember)
2654       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2655                                              R, TemplateArgs, S);
2656   }
2657 
2658   if (TemplateArgs || TemplateKWLoc.isValid()) {
2659 
2660     // In C++1y, if this is a variable template id, then check it
2661     // in BuildTemplateIdExpr().
2662     // The single lookup result must be a variable template declaration.
2663     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2664         Id.TemplateId->Kind == TNK_Var_template) {
2665       assert(R.getAsSingle<VarTemplateDecl>() &&
2666              "There should only be one declaration found.");
2667     }
2668 
2669     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2670   }
2671 
2672   return BuildDeclarationNameExpr(SS, R, ADL);
2673 }
2674 
2675 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2676 /// declaration name, generally during template instantiation.
2677 /// There's a large number of things which don't need to be done along
2678 /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2679 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2680     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2681     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2682   DeclContext *DC = computeDeclContext(SS, false);
2683   if (!DC)
2684     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2685                                      NameInfo, /*TemplateArgs=*/nullptr);
2686 
2687   if (RequireCompleteDeclContext(SS, DC))
2688     return ExprError();
2689 
2690   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2691   LookupQualifiedName(R, DC);
2692 
2693   if (R.isAmbiguous())
2694     return ExprError();
2695 
2696   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2697     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2698                                      NameInfo, /*TemplateArgs=*/nullptr);
2699 
2700   if (R.empty()) {
2701     // Don't diagnose problems with invalid record decl, the secondary no_member
2702     // diagnostic during template instantiation is likely bogus, e.g. if a class
2703     // is invalid because it's derived from an invalid base class, then missing
2704     // members were likely supposed to be inherited.
2705     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2706       if (CD->isInvalidDecl())
2707         return ExprError();
2708     Diag(NameInfo.getLoc(), diag::err_no_member)
2709       << NameInfo.getName() << DC << SS.getRange();
2710     return ExprError();
2711   }
2712 
2713   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2714     // Diagnose a missing typename if this resolved unambiguously to a type in
2715     // a dependent context.  If we can recover with a type, downgrade this to
2716     // a warning in Microsoft compatibility mode.
2717     unsigned DiagID = diag::err_typename_missing;
2718     if (RecoveryTSI && getLangOpts().MSVCCompat)
2719       DiagID = diag::ext_typename_missing;
2720     SourceLocation Loc = SS.getBeginLoc();
2721     auto D = Diag(Loc, DiagID);
2722     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2723       << SourceRange(Loc, NameInfo.getEndLoc());
2724 
2725     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2726     // context.
2727     if (!RecoveryTSI)
2728       return ExprError();
2729 
2730     // Only issue the fixit if we're prepared to recover.
2731     D << FixItHint::CreateInsertion(Loc, "typename ");
2732 
2733     // Recover by pretending this was an elaborated type.
2734     QualType Ty = Context.getTypeDeclType(TD);
2735     TypeLocBuilder TLB;
2736     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2737 
2738     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2739     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2740     QTL.setElaboratedKeywordLoc(SourceLocation());
2741     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2742 
2743     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2744 
2745     return ExprEmpty();
2746   }
2747 
2748   // Defend against this resolving to an implicit member access. We usually
2749   // won't get here if this might be a legitimate a class member (we end up in
2750   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2751   // a pointer-to-member or in an unevaluated context in C++11.
2752   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2753     return BuildPossibleImplicitMemberExpr(SS,
2754                                            /*TemplateKWLoc=*/SourceLocation(),
2755                                            R, /*TemplateArgs=*/nullptr, S);
2756 
2757   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2758 }
2759 
2760 /// The parser has read a name in, and Sema has detected that we're currently
2761 /// inside an ObjC method. Perform some additional checks and determine if we
2762 /// should form a reference to an ivar.
2763 ///
2764 /// Ideally, most of this would be done by lookup, but there's
2765 /// actually quite a lot of extra work involved.
LookupIvarInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II)2766 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2767                                         IdentifierInfo *II) {
2768   SourceLocation Loc = Lookup.getNameLoc();
2769   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2770 
2771   // Check for error condition which is already reported.
2772   if (!CurMethod)
2773     return DeclResult(true);
2774 
2775   // There are two cases to handle here.  1) scoped lookup could have failed,
2776   // in which case we should look for an ivar.  2) scoped lookup could have
2777   // found a decl, but that decl is outside the current instance method (i.e.
2778   // a global variable).  In these two cases, we do a lookup for an ivar with
2779   // this name, if the lookup sucedes, we replace it our current decl.
2780 
2781   // If we're in a class method, we don't normally want to look for
2782   // ivars.  But if we don't find anything else, and there's an
2783   // ivar, that's an error.
2784   bool IsClassMethod = CurMethod->isClassMethod();
2785 
2786   bool LookForIvars;
2787   if (Lookup.empty())
2788     LookForIvars = true;
2789   else if (IsClassMethod)
2790     LookForIvars = false;
2791   else
2792     LookForIvars = (Lookup.isSingleResult() &&
2793                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2794   ObjCInterfaceDecl *IFace = nullptr;
2795   if (LookForIvars) {
2796     IFace = CurMethod->getClassInterface();
2797     ObjCInterfaceDecl *ClassDeclared;
2798     ObjCIvarDecl *IV = nullptr;
2799     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2800       // Diagnose using an ivar in a class method.
2801       if (IsClassMethod) {
2802         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2803         return DeclResult(true);
2804       }
2805 
2806       // Diagnose the use of an ivar outside of the declaring class.
2807       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2808           !declaresSameEntity(ClassDeclared, IFace) &&
2809           !getLangOpts().DebuggerSupport)
2810         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2811 
2812       // Success.
2813       return IV;
2814     }
2815   } else if (CurMethod->isInstanceMethod()) {
2816     // We should warn if a local variable hides an ivar.
2817     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2818       ObjCInterfaceDecl *ClassDeclared;
2819       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2820         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2821             declaresSameEntity(IFace, ClassDeclared))
2822           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2823       }
2824     }
2825   } else if (Lookup.isSingleResult() &&
2826              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2827     // If accessing a stand-alone ivar in a class method, this is an error.
2828     if (const ObjCIvarDecl *IV =
2829             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2830       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2831       return DeclResult(true);
2832     }
2833   }
2834 
2835   // Didn't encounter an error, didn't find an ivar.
2836   return DeclResult(false);
2837 }
2838 
BuildIvarRefExpr(Scope * S,SourceLocation Loc,ObjCIvarDecl * IV)2839 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2840                                   ObjCIvarDecl *IV) {
2841   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2842   assert(CurMethod && CurMethod->isInstanceMethod() &&
2843          "should not reference ivar from this context");
2844 
2845   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2846   assert(IFace && "should not reference ivar from this context");
2847 
2848   // If we're referencing an invalid decl, just return this as a silent
2849   // error node.  The error diagnostic was already emitted on the decl.
2850   if (IV->isInvalidDecl())
2851     return ExprError();
2852 
2853   // Check if referencing a field with __attribute__((deprecated)).
2854   if (DiagnoseUseOfDecl(IV, Loc))
2855     return ExprError();
2856 
2857   // FIXME: This should use a new expr for a direct reference, don't
2858   // turn this into Self->ivar, just return a BareIVarExpr or something.
2859   IdentifierInfo &II = Context.Idents.get("self");
2860   UnqualifiedId SelfName;
2861   SelfName.setImplicitSelfParam(&II);
2862   CXXScopeSpec SelfScopeSpec;
2863   SourceLocation TemplateKWLoc;
2864   ExprResult SelfExpr =
2865       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2866                         /*HasTrailingLParen=*/false,
2867                         /*IsAddressOfOperand=*/false);
2868   if (SelfExpr.isInvalid())
2869     return ExprError();
2870 
2871   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2872   if (SelfExpr.isInvalid())
2873     return ExprError();
2874 
2875   MarkAnyDeclReferenced(Loc, IV, true);
2876 
2877   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2878   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2879       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2880     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2881 
2882   ObjCIvarRefExpr *Result = new (Context)
2883       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2884                       IV->getLocation(), SelfExpr.get(), true, true);
2885 
2886   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2887     if (!isUnevaluatedContext() &&
2888         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2889       getCurFunction()->recordUseOfWeak(Result);
2890   }
2891   if (getLangOpts().ObjCAutoRefCount)
2892     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2893       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2894 
2895   return Result;
2896 }
2897 
2898 /// The parser has read a name in, and Sema has detected that we're currently
2899 /// inside an ObjC method. Perform some additional checks and determine if we
2900 /// should form a reference to an ivar. If so, build an expression referencing
2901 /// that ivar.
2902 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2903 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2904                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2905   // FIXME: Integrate this lookup step into LookupParsedName.
2906   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2907   if (Ivar.isInvalid())
2908     return ExprError();
2909   if (Ivar.isUsable())
2910     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2911                             cast<ObjCIvarDecl>(Ivar.get()));
2912 
2913   if (Lookup.empty() && II && AllowBuiltinCreation)
2914     LookupBuiltin(Lookup);
2915 
2916   // Sentinel value saying that we didn't do anything special.
2917   return ExprResult(false);
2918 }
2919 
2920 /// Cast a base object to a member's actual type.
2921 ///
2922 /// There are two relevant checks:
2923 ///
2924 /// C++ [class.access.base]p7:
2925 ///
2926 ///   If a class member access operator [...] is used to access a non-static
2927 ///   data member or non-static member function, the reference is ill-formed if
2928 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2929 ///   naming class of the right operand.
2930 ///
2931 /// C++ [expr.ref]p7:
2932 ///
2933 ///   If E2 is a non-static data member or a non-static member function, the
2934 ///   program is ill-formed if the class of which E2 is directly a member is an
2935 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2936 ///
2937 /// Note that the latter check does not consider access; the access of the
2938 /// "real" base class is checked as appropriate when checking the access of the
2939 /// member name.
2940 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2941 Sema::PerformObjectMemberConversion(Expr *From,
2942                                     NestedNameSpecifier *Qualifier,
2943                                     NamedDecl *FoundDecl,
2944                                     NamedDecl *Member) {
2945   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2946   if (!RD)
2947     return From;
2948 
2949   QualType DestRecordType;
2950   QualType DestType;
2951   QualType FromRecordType;
2952   QualType FromType = From->getType();
2953   bool PointerConversions = false;
2954   if (isa<FieldDecl>(Member)) {
2955     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2956     auto FromPtrType = FromType->getAs<PointerType>();
2957     DestRecordType = Context.getAddrSpaceQualType(
2958         DestRecordType, FromPtrType
2959                             ? FromType->getPointeeType().getAddressSpace()
2960                             : FromType.getAddressSpace());
2961 
2962     if (FromPtrType) {
2963       DestType = Context.getPointerType(DestRecordType);
2964       FromRecordType = FromPtrType->getPointeeType();
2965       PointerConversions = true;
2966     } else {
2967       DestType = DestRecordType;
2968       FromRecordType = FromType;
2969     }
2970   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2971     if (Method->isStatic())
2972       return From;
2973 
2974     DestType = Method->getThisType();
2975     DestRecordType = DestType->getPointeeType();
2976 
2977     if (FromType->getAs<PointerType>()) {
2978       FromRecordType = FromType->getPointeeType();
2979       PointerConversions = true;
2980     } else {
2981       FromRecordType = FromType;
2982       DestType = DestRecordType;
2983     }
2984 
2985     LangAS FromAS = FromRecordType.getAddressSpace();
2986     LangAS DestAS = DestRecordType.getAddressSpace();
2987     if (FromAS != DestAS) {
2988       QualType FromRecordTypeWithoutAS =
2989           Context.removeAddrSpaceQualType(FromRecordType);
2990       QualType FromTypeWithDestAS =
2991           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2992       if (PointerConversions)
2993         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2994       From = ImpCastExprToType(From, FromTypeWithDestAS,
2995                                CK_AddressSpaceConversion, From->getValueKind())
2996                  .get();
2997     }
2998   } else {
2999     // No conversion necessary.
3000     return From;
3001   }
3002 
3003   if (DestType->isDependentType() || FromType->isDependentType())
3004     return From;
3005 
3006   // If the unqualified types are the same, no conversion is necessary.
3007   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3008     return From;
3009 
3010   SourceRange FromRange = From->getSourceRange();
3011   SourceLocation FromLoc = FromRange.getBegin();
3012 
3013   ExprValueKind VK = From->getValueKind();
3014 
3015   // C++ [class.member.lookup]p8:
3016   //   [...] Ambiguities can often be resolved by qualifying a name with its
3017   //   class name.
3018   //
3019   // If the member was a qualified name and the qualified referred to a
3020   // specific base subobject type, we'll cast to that intermediate type
3021   // first and then to the object in which the member is declared. That allows
3022   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3023   //
3024   //   class Base { public: int x; };
3025   //   class Derived1 : public Base { };
3026   //   class Derived2 : public Base { };
3027   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3028   //
3029   //   void VeryDerived::f() {
3030   //     x = 17; // error: ambiguous base subobjects
3031   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3032   //   }
3033   if (Qualifier && Qualifier->getAsType()) {
3034     QualType QType = QualType(Qualifier->getAsType(), 0);
3035     assert(QType->isRecordType() && "lookup done with non-record type");
3036 
3037     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3038 
3039     // In C++98, the qualifier type doesn't actually have to be a base
3040     // type of the object type, in which case we just ignore it.
3041     // Otherwise build the appropriate casts.
3042     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3043       CXXCastPath BasePath;
3044       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3045                                        FromLoc, FromRange, &BasePath))
3046         return ExprError();
3047 
3048       if (PointerConversions)
3049         QType = Context.getPointerType(QType);
3050       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3051                                VK, &BasePath).get();
3052 
3053       FromType = QType;
3054       FromRecordType = QRecordType;
3055 
3056       // If the qualifier type was the same as the destination type,
3057       // we're done.
3058       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3059         return From;
3060     }
3061   }
3062 
3063   CXXCastPath BasePath;
3064   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3065                                    FromLoc, FromRange, &BasePath,
3066                                    /*IgnoreAccess=*/true))
3067     return ExprError();
3068 
3069   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3070                            VK, &BasePath);
3071 }
3072 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)3073 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3074                                       const LookupResult &R,
3075                                       bool HasTrailingLParen) {
3076   // Only when used directly as the postfix-expression of a call.
3077   if (!HasTrailingLParen)
3078     return false;
3079 
3080   // Never if a scope specifier was provided.
3081   if (SS.isSet())
3082     return false;
3083 
3084   // Only in C++ or ObjC++.
3085   if (!getLangOpts().CPlusPlus)
3086     return false;
3087 
3088   // Turn off ADL when we find certain kinds of declarations during
3089   // normal lookup:
3090   for (NamedDecl *D : R) {
3091     // C++0x [basic.lookup.argdep]p3:
3092     //     -- a declaration of a class member
3093     // Since using decls preserve this property, we check this on the
3094     // original decl.
3095     if (D->isCXXClassMember())
3096       return false;
3097 
3098     // C++0x [basic.lookup.argdep]p3:
3099     //     -- a block-scope function declaration that is not a
3100     //        using-declaration
3101     // NOTE: we also trigger this for function templates (in fact, we
3102     // don't check the decl type at all, since all other decl types
3103     // turn off ADL anyway).
3104     if (isa<UsingShadowDecl>(D))
3105       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3107       return false;
3108 
3109     // C++0x [basic.lookup.argdep]p3:
3110     //     -- a declaration that is neither a function or a function
3111     //        template
3112     // And also for builtin functions.
3113     if (isa<FunctionDecl>(D)) {
3114       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3115 
3116       // But also builtin functions.
3117       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3118         return false;
3119     } else if (!isa<FunctionTemplateDecl>(D))
3120       return false;
3121   }
3122 
3123   return true;
3124 }
3125 
3126 
3127 /// Diagnoses obvious problems with the use of the given declaration
3128 /// as an expression.  This is only actually called for lookups that
3129 /// were not overloaded, and it doesn't promise that the declaration
3130 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)3131 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3132   if (D->isInvalidDecl())
3133     return true;
3134 
3135   if (isa<TypedefNameDecl>(D)) {
3136     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3137     return true;
3138   }
3139 
3140   if (isa<ObjCInterfaceDecl>(D)) {
3141     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3142     return true;
3143   }
3144 
3145   if (isa<NamespaceDecl>(D)) {
3146     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3147     return true;
3148   }
3149 
3150   return false;
3151 }
3152 
3153 // Certain multiversion types should be treated as overloaded even when there is
3154 // only one result.
ShouldLookupResultBeMultiVersionOverload(const LookupResult & R)3155 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3156   assert(R.isSingleResult() && "Expected only a single result");
3157   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3158   return FD &&
3159          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3160 }
3161 
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)3162 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3163                                           LookupResult &R, bool NeedsADL,
3164                                           bool AcceptInvalidDecl) {
3165   // If this is a single, fully-resolved result and we don't need ADL,
3166   // just build an ordinary singleton decl ref.
3167   if (!NeedsADL && R.isSingleResult() &&
3168       !R.getAsSingle<FunctionTemplateDecl>() &&
3169       !ShouldLookupResultBeMultiVersionOverload(R))
3170     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3171                                     R.getRepresentativeDecl(), nullptr,
3172                                     AcceptInvalidDecl);
3173 
3174   // We only need to check the declaration if there's exactly one
3175   // result, because in the overloaded case the results can only be
3176   // functions and function templates.
3177   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3178       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3179     return ExprError();
3180 
3181   // Otherwise, just build an unresolved lookup expression.  Suppress
3182   // any lookup-related diagnostics; we'll hash these out later, when
3183   // we've picked a target.
3184   R.suppressDiagnostics();
3185 
3186   UnresolvedLookupExpr *ULE
3187     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3188                                    SS.getWithLocInContext(Context),
3189                                    R.getLookupNameInfo(),
3190                                    NeedsADL, R.isOverloadedResult(),
3191                                    R.begin(), R.end());
3192 
3193   return ULE;
3194 }
3195 
3196 static void
3197 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3198                                    ValueDecl *var, DeclContext *DC);
3199 
3200 /// Complete semantic analysis for a reference to the given declaration.
BuildDeclarationNameExpr(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,NamedDecl * D,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,bool AcceptInvalidDecl)3201 ExprResult Sema::BuildDeclarationNameExpr(
3202     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3203     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3204     bool AcceptInvalidDecl) {
3205   assert(D && "Cannot refer to a NULL declaration");
3206   assert(!isa<FunctionTemplateDecl>(D) &&
3207          "Cannot refer unambiguously to a function template");
3208 
3209   SourceLocation Loc = NameInfo.getLoc();
3210   if (CheckDeclInExpr(*this, Loc, D))
3211     return ExprError();
3212 
3213   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3214     // Specifically diagnose references to class templates that are missing
3215     // a template argument list.
3216     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3217     return ExprError();
3218   }
3219 
3220   // Make sure that we're referring to a value.
3221   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3222     Diag(Loc, diag::err_ref_non_value)
3223       << D << SS.getRange();
3224     Diag(D->getLocation(), diag::note_declared_at);
3225     return ExprError();
3226   }
3227 
3228   // Check whether this declaration can be used. Note that we suppress
3229   // this check when we're going to perform argument-dependent lookup
3230   // on this function name, because this might not be the function
3231   // that overload resolution actually selects.
3232   if (DiagnoseUseOfDecl(D, Loc))
3233     return ExprError();
3234 
3235   auto *VD = cast<ValueDecl>(D);
3236 
3237   // Only create DeclRefExpr's for valid Decl's.
3238   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3239     return ExprError();
3240 
3241   // Handle members of anonymous structs and unions.  If we got here,
3242   // and the reference is to a class member indirect field, then this
3243   // must be the subject of a pointer-to-member expression.
3244   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3245     if (!indirectField->isCXXClassMember())
3246       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3247                                                       indirectField);
3248 
3249   {
3250     QualType type = VD->getType();
3251     if (type.isNull())
3252       return ExprError();
3253     ExprValueKind valueKind = VK_PRValue;
3254 
3255     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3256     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3257     // is expanded by some outer '...' in the context of the use.
3258     type = type.getNonPackExpansionType();
3259 
3260     switch (D->getKind()) {
3261     // Ignore all the non-ValueDecl kinds.
3262 #define ABSTRACT_DECL(kind)
3263 #define VALUE(type, base)
3264 #define DECL(type, base) \
3265     case Decl::type:
3266 #include "clang/AST/DeclNodes.inc"
3267       llvm_unreachable("invalid value decl kind");
3268 
3269     // These shouldn't make it here.
3270     case Decl::ObjCAtDefsField:
3271       llvm_unreachable("forming non-member reference to ivar?");
3272 
3273     // Enum constants are always r-values and never references.
3274     // Unresolved using declarations are dependent.
3275     case Decl::EnumConstant:
3276     case Decl::UnresolvedUsingValue:
3277     case Decl::OMPDeclareReduction:
3278     case Decl::OMPDeclareMapper:
3279       valueKind = VK_PRValue;
3280       break;
3281 
3282     // Fields and indirect fields that got here must be for
3283     // pointer-to-member expressions; we just call them l-values for
3284     // internal consistency, because this subexpression doesn't really
3285     // exist in the high-level semantics.
3286     case Decl::Field:
3287     case Decl::IndirectField:
3288     case Decl::ObjCIvar:
3289       assert(getLangOpts().CPlusPlus &&
3290              "building reference to field in C?");
3291 
3292       // These can't have reference type in well-formed programs, but
3293       // for internal consistency we do this anyway.
3294       type = type.getNonReferenceType();
3295       valueKind = VK_LValue;
3296       break;
3297 
3298     // Non-type template parameters are either l-values or r-values
3299     // depending on the type.
3300     case Decl::NonTypeTemplateParm: {
3301       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3302         type = reftype->getPointeeType();
3303         valueKind = VK_LValue; // even if the parameter is an r-value reference
3304         break;
3305       }
3306 
3307       // [expr.prim.id.unqual]p2:
3308       //   If the entity is a template parameter object for a template
3309       //   parameter of type T, the type of the expression is const T.
3310       //   [...] The expression is an lvalue if the entity is a [...] template
3311       //   parameter object.
3312       if (type->isRecordType()) {
3313         type = type.getUnqualifiedType().withConst();
3314         valueKind = VK_LValue;
3315         break;
3316       }
3317 
3318       // For non-references, we need to strip qualifiers just in case
3319       // the template parameter was declared as 'const int' or whatever.
3320       valueKind = VK_PRValue;
3321       type = type.getUnqualifiedType();
3322       break;
3323     }
3324 
3325     case Decl::Var:
3326     case Decl::VarTemplateSpecialization:
3327     case Decl::VarTemplatePartialSpecialization:
3328     case Decl::Decomposition:
3329     case Decl::OMPCapturedExpr:
3330       // In C, "extern void blah;" is valid and is an r-value.
3331       if (!getLangOpts().CPlusPlus &&
3332           !type.hasQualifiers() &&
3333           type->isVoidType()) {
3334         valueKind = VK_PRValue;
3335         break;
3336       }
3337       LLVM_FALLTHROUGH;
3338 
3339     case Decl::ImplicitParam:
3340     case Decl::ParmVar: {
3341       // These are always l-values.
3342       valueKind = VK_LValue;
3343       type = type.getNonReferenceType();
3344 
3345       // FIXME: Does the addition of const really only apply in
3346       // potentially-evaluated contexts? Since the variable isn't actually
3347       // captured in an unevaluated context, it seems that the answer is no.
3348       if (!isUnevaluatedContext()) {
3349         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3350         if (!CapturedType.isNull())
3351           type = CapturedType;
3352       }
3353 
3354       break;
3355     }
3356 
3357     case Decl::Binding: {
3358       // These are always lvalues.
3359       valueKind = VK_LValue;
3360       type = type.getNonReferenceType();
3361       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3362       // decides how that's supposed to work.
3363       auto *BD = cast<BindingDecl>(VD);
3364       if (BD->getDeclContext() != CurContext) {
3365         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3366         if (DD && DD->hasLocalStorage())
3367           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3368       }
3369       break;
3370     }
3371 
3372     case Decl::Function: {
3373       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3374         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3375           type = Context.BuiltinFnTy;
3376           valueKind = VK_PRValue;
3377           break;
3378         }
3379       }
3380 
3381       const FunctionType *fty = type->castAs<FunctionType>();
3382 
3383       // If we're referring to a function with an __unknown_anytype
3384       // result type, make the entire expression __unknown_anytype.
3385       if (fty->getReturnType() == Context.UnknownAnyTy) {
3386         type = Context.UnknownAnyTy;
3387         valueKind = VK_PRValue;
3388         break;
3389       }
3390 
3391       // Functions are l-values in C++.
3392       if (getLangOpts().CPlusPlus) {
3393         valueKind = VK_LValue;
3394         break;
3395       }
3396 
3397       // C99 DR 316 says that, if a function type comes from a
3398       // function definition (without a prototype), that type is only
3399       // used for checking compatibility. Therefore, when referencing
3400       // the function, we pretend that we don't have the full function
3401       // type.
3402       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3403           isa<FunctionProtoType>(fty))
3404         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3405                                               fty->getExtInfo());
3406 
3407       // Functions are r-values in C.
3408       valueKind = VK_PRValue;
3409       break;
3410     }
3411 
3412     case Decl::CXXDeductionGuide:
3413       llvm_unreachable("building reference to deduction guide");
3414 
3415     case Decl::MSProperty:
3416     case Decl::MSGuid:
3417     case Decl::TemplateParamObject:
3418       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3419       // capture in OpenMP, or duplicated between host and device?
3420       valueKind = VK_LValue;
3421       break;
3422 
3423     case Decl::CXXMethod:
3424       // If we're referring to a method with an __unknown_anytype
3425       // result type, make the entire expression __unknown_anytype.
3426       // This should only be possible with a type written directly.
3427       if (const FunctionProtoType *proto
3428             = dyn_cast<FunctionProtoType>(VD->getType()))
3429         if (proto->getReturnType() == Context.UnknownAnyTy) {
3430           type = Context.UnknownAnyTy;
3431           valueKind = VK_PRValue;
3432           break;
3433         }
3434 
3435       // C++ methods are l-values if static, r-values if non-static.
3436       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3437         valueKind = VK_LValue;
3438         break;
3439       }
3440       LLVM_FALLTHROUGH;
3441 
3442     case Decl::CXXConversion:
3443     case Decl::CXXDestructor:
3444     case Decl::CXXConstructor:
3445       valueKind = VK_PRValue;
3446       break;
3447     }
3448 
3449     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3450                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3451                             TemplateArgs);
3452   }
3453 }
3454 
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3455 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3456                                     SmallString<32> &Target) {
3457   Target.resize(CharByteWidth * (Source.size() + 1));
3458   char *ResultPtr = &Target[0];
3459   const llvm::UTF8 *ErrorPtr;
3460   bool success =
3461       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3462   (void)success;
3463   assert(success);
3464   Target.resize(ResultPtr - &Target[0]);
3465 }
3466 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentKind IK)3467 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3468                                      PredefinedExpr::IdentKind IK) {
3469   // Pick the current block, lambda, captured statement or function.
3470   Decl *currentDecl = nullptr;
3471   if (const BlockScopeInfo *BSI = getCurBlock())
3472     currentDecl = BSI->TheDecl;
3473   else if (const LambdaScopeInfo *LSI = getCurLambda())
3474     currentDecl = LSI->CallOperator;
3475   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3476     currentDecl = CSI->TheCapturedDecl;
3477   else
3478     currentDecl = getCurFunctionOrMethodDecl();
3479 
3480   if (!currentDecl) {
3481     Diag(Loc, diag::ext_predef_outside_function);
3482     currentDecl = Context.getTranslationUnitDecl();
3483   }
3484 
3485   QualType ResTy;
3486   StringLiteral *SL = nullptr;
3487   if (cast<DeclContext>(currentDecl)->isDependentContext())
3488     ResTy = Context.DependentTy;
3489   else {
3490     // Pre-defined identifiers are of type char[x], where x is the length of
3491     // the string.
3492     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3493     unsigned Length = Str.length();
3494 
3495     llvm::APInt LengthI(32, Length + 1);
3496     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3497       ResTy =
3498           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3499       SmallString<32> RawChars;
3500       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3501                               Str, RawChars);
3502       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503                                            ArrayType::Normal,
3504                                            /*IndexTypeQuals*/ 0);
3505       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3506                                  /*Pascal*/ false, ResTy, Loc);
3507     } else {
3508       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3509       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3510                                            ArrayType::Normal,
3511                                            /*IndexTypeQuals*/ 0);
3512       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3513                                  /*Pascal*/ false, ResTy, Loc);
3514     }
3515   }
3516 
3517   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3518 }
3519 
BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,SourceLocation LParen,SourceLocation RParen,TypeSourceInfo * TSI)3520 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3521                                                SourceLocation LParen,
3522                                                SourceLocation RParen,
3523                                                TypeSourceInfo *TSI) {
3524   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3525 }
3526 
ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,SourceLocation LParen,SourceLocation RParen,ParsedType ParsedTy)3527 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3528                                                SourceLocation LParen,
3529                                                SourceLocation RParen,
3530                                                ParsedType ParsedTy) {
3531   TypeSourceInfo *TSI = nullptr;
3532   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3533 
3534   if (Ty.isNull())
3535     return ExprError();
3536   if (!TSI)
3537     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3538 
3539   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3540 }
3541 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3542 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3543   PredefinedExpr::IdentKind IK;
3544 
3545   switch (Kind) {
3546   default: llvm_unreachable("Unknown simple primary expr!");
3547   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3548   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3549   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3550   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3551   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3552   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3553   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3554   }
3555 
3556   return BuildPredefinedExpr(Loc, IK);
3557 }
3558 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3559 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3560   SmallString<16> CharBuffer;
3561   bool Invalid = false;
3562   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3563   if (Invalid)
3564     return ExprError();
3565 
3566   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3567                             PP, Tok.getKind());
3568   if (Literal.hadError())
3569     return ExprError();
3570 
3571   QualType Ty;
3572   if (Literal.isWide())
3573     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3574   else if (Literal.isUTF8() && getLangOpts().Char8)
3575     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3576   else if (Literal.isUTF16())
3577     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3578   else if (Literal.isUTF32())
3579     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3580   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3581     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3582   else
3583     Ty = Context.CharTy;  // 'x' -> char in C++
3584 
3585   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3586   if (Literal.isWide())
3587     Kind = CharacterLiteral::Wide;
3588   else if (Literal.isUTF16())
3589     Kind = CharacterLiteral::UTF16;
3590   else if (Literal.isUTF32())
3591     Kind = CharacterLiteral::UTF32;
3592   else if (Literal.isUTF8())
3593     Kind = CharacterLiteral::UTF8;
3594 
3595   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3596                                              Tok.getLocation());
3597 
3598   if (Literal.getUDSuffix().empty())
3599     return Lit;
3600 
3601   // We're building a user-defined literal.
3602   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3603   SourceLocation UDSuffixLoc =
3604     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3605 
3606   // Make sure we're allowed user-defined literals here.
3607   if (!UDLScope)
3608     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3609 
3610   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3611   //   operator "" X (ch)
3612   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3613                                         Lit, Tok.getLocation());
3614 }
3615 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3616 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3617   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3618   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3619                                 Context.IntTy, Loc);
3620 }
3621 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3622 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3623                                   QualType Ty, SourceLocation Loc) {
3624   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3625 
3626   using llvm::APFloat;
3627   APFloat Val(Format);
3628 
3629   APFloat::opStatus result = Literal.GetFloatValue(Val);
3630 
3631   // Overflow is always an error, but underflow is only an error if
3632   // we underflowed to zero (APFloat reports denormals as underflow).
3633   if ((result & APFloat::opOverflow) ||
3634       ((result & APFloat::opUnderflow) && Val.isZero())) {
3635     unsigned diagnostic;
3636     SmallString<20> buffer;
3637     if (result & APFloat::opOverflow) {
3638       diagnostic = diag::warn_float_overflow;
3639       APFloat::getLargest(Format).toString(buffer);
3640     } else {
3641       diagnostic = diag::warn_float_underflow;
3642       APFloat::getSmallest(Format).toString(buffer);
3643     }
3644 
3645     S.Diag(Loc, diagnostic)
3646       << Ty
3647       << StringRef(buffer.data(), buffer.size());
3648   }
3649 
3650   bool isExact = (result == APFloat::opOK);
3651   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3652 }
3653 
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3654 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3655   assert(E && "Invalid expression");
3656 
3657   if (E->isValueDependent())
3658     return false;
3659 
3660   QualType QT = E->getType();
3661   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3662     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3663     return true;
3664   }
3665 
3666   llvm::APSInt ValueAPS;
3667   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3668 
3669   if (R.isInvalid())
3670     return true;
3671 
3672   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3673   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3674     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3675         << toString(ValueAPS, 10) << ValueIsPositive;
3676     return true;
3677   }
3678 
3679   return false;
3680 }
3681 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3682 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3683   // Fast path for a single digit (which is quite common).  A single digit
3684   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3685   if (Tok.getLength() == 1) {
3686     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3687     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3688   }
3689 
3690   SmallString<128> SpellingBuffer;
3691   // NumericLiteralParser wants to overread by one character.  Add padding to
3692   // the buffer in case the token is copied to the buffer.  If getSpelling()
3693   // returns a StringRef to the memory buffer, it should have a null char at
3694   // the EOF, so it is also safe.
3695   SpellingBuffer.resize(Tok.getLength() + 1);
3696 
3697   // Get the spelling of the token, which eliminates trigraphs, etc.
3698   bool Invalid = false;
3699   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3700   if (Invalid)
3701     return ExprError();
3702 
3703   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3704                                PP.getSourceManager(), PP.getLangOpts(),
3705                                PP.getTargetInfo(), PP.getDiagnostics());
3706   if (Literal.hadError)
3707     return ExprError();
3708 
3709   if (Literal.hasUDSuffix()) {
3710     // We're building a user-defined literal.
3711     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3712     SourceLocation UDSuffixLoc =
3713       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3714 
3715     // Make sure we're allowed user-defined literals here.
3716     if (!UDLScope)
3717       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3718 
3719     QualType CookedTy;
3720     if (Literal.isFloatingLiteral()) {
3721       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3722       // long double, the literal is treated as a call of the form
3723       //   operator "" X (f L)
3724       CookedTy = Context.LongDoubleTy;
3725     } else {
3726       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3727       // unsigned long long, the literal is treated as a call of the form
3728       //   operator "" X (n ULL)
3729       CookedTy = Context.UnsignedLongLongTy;
3730     }
3731 
3732     DeclarationName OpName =
3733       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3734     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3735     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3736 
3737     SourceLocation TokLoc = Tok.getLocation();
3738 
3739     // Perform literal operator lookup to determine if we're building a raw
3740     // literal or a cooked one.
3741     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3742     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3743                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3744                                   /*AllowStringTemplatePack*/ false,
3745                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3746     case LOLR_ErrorNoDiagnostic:
3747       // Lookup failure for imaginary constants isn't fatal, there's still the
3748       // GNU extension producing _Complex types.
3749       break;
3750     case LOLR_Error:
3751       return ExprError();
3752     case LOLR_Cooked: {
3753       Expr *Lit;
3754       if (Literal.isFloatingLiteral()) {
3755         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3756       } else {
3757         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3758         if (Literal.GetIntegerValue(ResultVal))
3759           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3760               << /* Unsigned */ 1;
3761         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3762                                      Tok.getLocation());
3763       }
3764       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3765     }
3766 
3767     case LOLR_Raw: {
3768       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3769       // literal is treated as a call of the form
3770       //   operator "" X ("n")
3771       unsigned Length = Literal.getUDSuffixOffset();
3772       QualType StrTy = Context.getConstantArrayType(
3773           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3774           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3775       Expr *Lit = StringLiteral::Create(
3776           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3777           /*Pascal*/false, StrTy, &TokLoc, 1);
3778       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3779     }
3780 
3781     case LOLR_Template: {
3782       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3783       // template), L is treated as a call fo the form
3784       //   operator "" X <'c1', 'c2', ... 'ck'>()
3785       // where n is the source character sequence c1 c2 ... ck.
3786       TemplateArgumentListInfo ExplicitArgs;
3787       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3788       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3789       llvm::APSInt Value(CharBits, CharIsUnsigned);
3790       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3791         Value = TokSpelling[I];
3792         TemplateArgument Arg(Context, Value, Context.CharTy);
3793         TemplateArgumentLocInfo ArgInfo;
3794         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3795       }
3796       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3797                                       &ExplicitArgs);
3798     }
3799     case LOLR_StringTemplatePack:
3800       llvm_unreachable("unexpected literal operator lookup result");
3801     }
3802   }
3803 
3804   Expr *Res;
3805 
3806   if (Literal.isFixedPointLiteral()) {
3807     QualType Ty;
3808 
3809     if (Literal.isAccum) {
3810       if (Literal.isHalf) {
3811         Ty = Context.ShortAccumTy;
3812       } else if (Literal.isLong) {
3813         Ty = Context.LongAccumTy;
3814       } else {
3815         Ty = Context.AccumTy;
3816       }
3817     } else if (Literal.isFract) {
3818       if (Literal.isHalf) {
3819         Ty = Context.ShortFractTy;
3820       } else if (Literal.isLong) {
3821         Ty = Context.LongFractTy;
3822       } else {
3823         Ty = Context.FractTy;
3824       }
3825     }
3826 
3827     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3828 
3829     bool isSigned = !Literal.isUnsigned;
3830     unsigned scale = Context.getFixedPointScale(Ty);
3831     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3832 
3833     llvm::APInt Val(bit_width, 0, isSigned);
3834     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3835     bool ValIsZero = Val.isNullValue() && !Overflowed;
3836 
3837     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3838     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3839       // Clause 6.4.4 - The value of a constant shall be in the range of
3840       // representable values for its type, with exception for constants of a
3841       // fract type with a value of exactly 1; such a constant shall denote
3842       // the maximal value for the type.
3843       --Val;
3844     else if (Val.ugt(MaxVal) || Overflowed)
3845       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3846 
3847     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3848                                               Tok.getLocation(), scale);
3849   } else if (Literal.isFloatingLiteral()) {
3850     QualType Ty;
3851     if (Literal.isHalf){
3852       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3853         Ty = Context.HalfTy;
3854       else {
3855         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3856         return ExprError();
3857       }
3858     } else if (Literal.isFloat)
3859       Ty = Context.FloatTy;
3860     else if (Literal.isLong)
3861       Ty = Context.LongDoubleTy;
3862     else if (Literal.isFloat16)
3863       Ty = Context.Float16Ty;
3864     else if (Literal.isFloat128)
3865       Ty = Context.Float128Ty;
3866     else
3867       Ty = Context.DoubleTy;
3868 
3869     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3870 
3871     if (Ty == Context.DoubleTy) {
3872       if (getLangOpts().SinglePrecisionConstants) {
3873         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3874           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875         }
3876       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3877                                              "cl_khr_fp64", getLangOpts())) {
3878         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3879         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3880             << (getLangOpts().OpenCLVersion >= 300);
3881         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3882       }
3883     }
3884   } else if (!Literal.isIntegerLiteral()) {
3885     return ExprError();
3886   } else {
3887     QualType Ty;
3888 
3889     // 'long long' is a C99 or C++11 feature.
3890     if (!getLangOpts().C99 && Literal.isLongLong) {
3891       if (getLangOpts().CPlusPlus)
3892         Diag(Tok.getLocation(),
3893              getLangOpts().CPlusPlus11 ?
3894              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3895       else
3896         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3897     }
3898 
3899     // 'z/uz' literals are a C++2b feature.
3900     if (Literal.isSizeT)
3901       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3902                                   ? getLangOpts().CPlusPlus2b
3903                                         ? diag::warn_cxx20_compat_size_t_suffix
3904                                         : diag::ext_cxx2b_size_t_suffix
3905                                   : diag::err_cxx2b_size_t_suffix);
3906 
3907     // Get the value in the widest-possible width.
3908     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3909     llvm::APInt ResultVal(MaxWidth, 0);
3910 
3911     if (Literal.GetIntegerValue(ResultVal)) {
3912       // If this value didn't fit into uintmax_t, error and force to ull.
3913       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3914           << /* Unsigned */ 1;
3915       Ty = Context.UnsignedLongLongTy;
3916       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3917              "long long is not intmax_t?");
3918     } else {
3919       // If this value fits into a ULL, try to figure out what else it fits into
3920       // according to the rules of C99 6.4.4.1p5.
3921 
3922       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3923       // be an unsigned int.
3924       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3925 
3926       // Check from smallest to largest, picking the smallest type we can.
3927       unsigned Width = 0;
3928 
3929       // Microsoft specific integer suffixes are explicitly sized.
3930       if (Literal.MicrosoftInteger) {
3931         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3932           Width = 8;
3933           Ty = Context.CharTy;
3934         } else {
3935           Width = Literal.MicrosoftInteger;
3936           Ty = Context.getIntTypeForBitwidth(Width,
3937                                              /*Signed=*/!Literal.isUnsigned);
3938         }
3939       }
3940 
3941       // Check C++2b size_t literals.
3942       if (Literal.isSizeT) {
3943         assert(!Literal.MicrosoftInteger &&
3944                "size_t literals can't be Microsoft literals");
3945         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3946             Context.getTargetInfo().getSizeType());
3947 
3948         // Does it fit in size_t?
3949         if (ResultVal.isIntN(SizeTSize)) {
3950           // Does it fit in ssize_t?
3951           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3952             Ty = Context.getSignedSizeType();
3953           else if (AllowUnsigned)
3954             Ty = Context.getSizeType();
3955           Width = SizeTSize;
3956         }
3957       }
3958 
3959       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3960           !Literal.isSizeT) {
3961         // Are int/unsigned possibilities?
3962         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3963 
3964         // Does it fit in a unsigned int?
3965         if (ResultVal.isIntN(IntSize)) {
3966           // Does it fit in a signed int?
3967           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3968             Ty = Context.IntTy;
3969           else if (AllowUnsigned)
3970             Ty = Context.UnsignedIntTy;
3971           Width = IntSize;
3972         }
3973       }
3974 
3975       // Are long/unsigned long possibilities?
3976       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3977         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3978 
3979         // Does it fit in a unsigned long?
3980         if (ResultVal.isIntN(LongSize)) {
3981           // Does it fit in a signed long?
3982           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3983             Ty = Context.LongTy;
3984           else if (AllowUnsigned)
3985             Ty = Context.UnsignedLongTy;
3986           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3987           // is compatible.
3988           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3989             const unsigned LongLongSize =
3990                 Context.getTargetInfo().getLongLongWidth();
3991             Diag(Tok.getLocation(),
3992                  getLangOpts().CPlusPlus
3993                      ? Literal.isLong
3994                            ? diag::warn_old_implicitly_unsigned_long_cxx
3995                            : /*C++98 UB*/ diag::
3996                                  ext_old_implicitly_unsigned_long_cxx
3997                      : diag::warn_old_implicitly_unsigned_long)
3998                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3999                                             : /*will be ill-formed*/ 1);
4000             Ty = Context.UnsignedLongTy;
4001           }
4002           Width = LongSize;
4003         }
4004       }
4005 
4006       // Check long long if needed.
4007       if (Ty.isNull() && !Literal.isSizeT) {
4008         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4009 
4010         // Does it fit in a unsigned long long?
4011         if (ResultVal.isIntN(LongLongSize)) {
4012           // Does it fit in a signed long long?
4013           // To be compatible with MSVC, hex integer literals ending with the
4014           // LL or i64 suffix are always signed in Microsoft mode.
4015           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4016               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4017             Ty = Context.LongLongTy;
4018           else if (AllowUnsigned)
4019             Ty = Context.UnsignedLongLongTy;
4020           Width = LongLongSize;
4021         }
4022       }
4023 
4024       // If we still couldn't decide a type, we either have 'size_t' literal
4025       // that is out of range, or a decimal literal that does not fit in a
4026       // signed long long and has no U suffix.
4027       if (Ty.isNull()) {
4028         if (Literal.isSizeT)
4029           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4030               << Literal.isUnsigned;
4031         else
4032           Diag(Tok.getLocation(),
4033                diag::ext_integer_literal_too_large_for_signed);
4034         Ty = Context.UnsignedLongLongTy;
4035         Width = Context.getTargetInfo().getLongLongWidth();
4036       }
4037 
4038       if (ResultVal.getBitWidth() != Width)
4039         ResultVal = ResultVal.trunc(Width);
4040     }
4041     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4042   }
4043 
4044   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4045   if (Literal.isImaginary) {
4046     Res = new (Context) ImaginaryLiteral(Res,
4047                                         Context.getComplexType(Res->getType()));
4048 
4049     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4050   }
4051   return Res;
4052 }
4053 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)4054 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4055   assert(E && "ActOnParenExpr() missing expr");
4056   QualType ExprTy = E->getType();
4057   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4058       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4059     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4060   return new (Context) ParenExpr(L, R, E);
4061 }
4062 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)4063 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4064                                          SourceLocation Loc,
4065                                          SourceRange ArgRange) {
4066   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4067   // scalar or vector data type argument..."
4068   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4069   // type (C99 6.2.5p18) or void.
4070   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4071     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4072       << T << ArgRange;
4073     return true;
4074   }
4075 
4076   assert((T->isVoidType() || !T->isIncompleteType()) &&
4077          "Scalar types should always be complete");
4078   return false;
4079 }
4080 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4081 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4082                                            SourceLocation Loc,
4083                                            SourceRange ArgRange,
4084                                            UnaryExprOrTypeTrait TraitKind) {
4085   // Invalid types must be hard errors for SFINAE in C++.
4086   if (S.LangOpts.CPlusPlus)
4087     return true;
4088 
4089   // C99 6.5.3.4p1:
4090   if (T->isFunctionType() &&
4091       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4092        TraitKind == UETT_PreferredAlignOf)) {
4093     // sizeof(function)/alignof(function) is allowed as an extension.
4094     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4095         << getTraitSpelling(TraitKind) << ArgRange;
4096     return false;
4097   }
4098 
4099   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4100   // this is an error (OpenCL v1.1 s6.3.k)
4101   if (T->isVoidType()) {
4102     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4103                                         : diag::ext_sizeof_alignof_void_type;
4104     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4105     return false;
4106   }
4107 
4108   return true;
4109 }
4110 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4111 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4112                                              SourceLocation Loc,
4113                                              SourceRange ArgRange,
4114                                              UnaryExprOrTypeTrait TraitKind) {
4115   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4116   // runtime doesn't allow it.
4117   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4118     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4119       << T << (TraitKind == UETT_SizeOf)
4120       << ArgRange;
4121     return true;
4122   }
4123 
4124   return false;
4125 }
4126 
4127 /// Check whether E is a pointer from a decayed array type (the decayed
4128 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)4129 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4130                                      Expr *E) {
4131   // Don't warn if the operation changed the type.
4132   if (T != E->getType())
4133     return;
4134 
4135   // Now look for array decays.
4136   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4137   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4138     return;
4139 
4140   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4141                                              << ICE->getType()
4142                                              << ICE->getSubExpr()->getType();
4143 }
4144 
4145 /// Check the constraints on expression operands to unary type expression
4146 /// and type traits.
4147 ///
4148 /// Completes any types necessary and validates the constraints on the operand
4149 /// expression. The logic mostly mirrors the type-based overload, but may modify
4150 /// the expression as it completes the type for that expression through template
4151 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)4152 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4153                                             UnaryExprOrTypeTrait ExprKind) {
4154   QualType ExprTy = E->getType();
4155   assert(!ExprTy->isReferenceType());
4156 
4157   bool IsUnevaluatedOperand =
4158       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4159        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4160   if (IsUnevaluatedOperand) {
4161     ExprResult Result = CheckUnevaluatedOperand(E);
4162     if (Result.isInvalid())
4163       return true;
4164     E = Result.get();
4165   }
4166 
4167   // The operand for sizeof and alignof is in an unevaluated expression context,
4168   // so side effects could result in unintended consequences.
4169   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4170   // used to build SFINAE gadgets.
4171   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4172   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4173       !E->isInstantiationDependent() &&
4174       E->HasSideEffects(Context, false))
4175     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4176 
4177   if (ExprKind == UETT_VecStep)
4178     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4179                                         E->getSourceRange());
4180 
4181   // Explicitly list some types as extensions.
4182   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4183                                       E->getSourceRange(), ExprKind))
4184     return false;
4185 
4186   // 'alignof' applied to an expression only requires the base element type of
4187   // the expression to be complete. 'sizeof' requires the expression's type to
4188   // be complete (and will attempt to complete it if it's an array of unknown
4189   // bound).
4190   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4191     if (RequireCompleteSizedType(
4192             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4193             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4194             getTraitSpelling(ExprKind), E->getSourceRange()))
4195       return true;
4196   } else {
4197     if (RequireCompleteSizedExprType(
4198             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4199             getTraitSpelling(ExprKind), E->getSourceRange()))
4200       return true;
4201   }
4202 
4203   // Completing the expression's type may have changed it.
4204   ExprTy = E->getType();
4205   assert(!ExprTy->isReferenceType());
4206 
4207   if (ExprTy->isFunctionType()) {
4208     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4209         << getTraitSpelling(ExprKind) << E->getSourceRange();
4210     return true;
4211   }
4212 
4213   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4214                                        E->getSourceRange(), ExprKind))
4215     return true;
4216 
4217   if (ExprKind == UETT_SizeOf) {
4218     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4219       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4220         QualType OType = PVD->getOriginalType();
4221         QualType Type = PVD->getType();
4222         if (Type->isPointerType() && OType->isArrayType()) {
4223           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4224             << Type << OType;
4225           Diag(PVD->getLocation(), diag::note_declared_at);
4226         }
4227       }
4228     }
4229 
4230     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4231     // decays into a pointer and returns an unintended result. This is most
4232     // likely a typo for "sizeof(array) op x".
4233     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4234       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4235                                BO->getLHS());
4236       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4237                                BO->getRHS());
4238     }
4239   }
4240 
4241   return false;
4242 }
4243 
4244 /// Check the constraints on operands to unary expression and type
4245 /// traits.
4246 ///
4247 /// This will complete any types necessary, and validate the various constraints
4248 /// on those operands.
4249 ///
4250 /// The UsualUnaryConversions() function is *not* called by this routine.
4251 /// C99 6.3.2.1p[2-4] all state:
4252 ///   Except when it is the operand of the sizeof operator ...
4253 ///
4254 /// C++ [expr.sizeof]p4
4255 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4256 ///   standard conversions are not applied to the operand of sizeof.
4257 ///
4258 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)4259 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4260                                             SourceLocation OpLoc,
4261                                             SourceRange ExprRange,
4262                                             UnaryExprOrTypeTrait ExprKind) {
4263   if (ExprType->isDependentType())
4264     return false;
4265 
4266   // C++ [expr.sizeof]p2:
4267   //     When applied to a reference or a reference type, the result
4268   //     is the size of the referenced type.
4269   // C++11 [expr.alignof]p3:
4270   //     When alignof is applied to a reference type, the result
4271   //     shall be the alignment of the referenced type.
4272   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4273     ExprType = Ref->getPointeeType();
4274 
4275   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4276   //   When alignof or _Alignof is applied to an array type, the result
4277   //   is the alignment of the element type.
4278   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4279       ExprKind == UETT_OpenMPRequiredSimdAlign)
4280     ExprType = Context.getBaseElementType(ExprType);
4281 
4282   if (ExprKind == UETT_VecStep)
4283     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4284 
4285   // Explicitly list some types as extensions.
4286   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4287                                       ExprKind))
4288     return false;
4289 
4290   if (RequireCompleteSizedType(
4291           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4292           getTraitSpelling(ExprKind), ExprRange))
4293     return true;
4294 
4295   if (ExprType->isFunctionType()) {
4296     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4297         << getTraitSpelling(ExprKind) << ExprRange;
4298     return true;
4299   }
4300 
4301   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4302                                        ExprKind))
4303     return true;
4304 
4305   return false;
4306 }
4307 
CheckAlignOfExpr(Sema & S,Expr * E,UnaryExprOrTypeTrait ExprKind)4308 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4309   // Cannot know anything else if the expression is dependent.
4310   if (E->isTypeDependent())
4311     return false;
4312 
4313   if (E->getObjectKind() == OK_BitField) {
4314     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4315        << 1 << E->getSourceRange();
4316     return true;
4317   }
4318 
4319   ValueDecl *D = nullptr;
4320   Expr *Inner = E->IgnoreParens();
4321   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4322     D = DRE->getDecl();
4323   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4324     D = ME->getMemberDecl();
4325   }
4326 
4327   // If it's a field, require the containing struct to have a
4328   // complete definition so that we can compute the layout.
4329   //
4330   // This can happen in C++11 onwards, either by naming the member
4331   // in a way that is not transformed into a member access expression
4332   // (in an unevaluated operand, for instance), or by naming the member
4333   // in a trailing-return-type.
4334   //
4335   // For the record, since __alignof__ on expressions is a GCC
4336   // extension, GCC seems to permit this but always gives the
4337   // nonsensical answer 0.
4338   //
4339   // We don't really need the layout here --- we could instead just
4340   // directly check for all the appropriate alignment-lowing
4341   // attributes --- but that would require duplicating a lot of
4342   // logic that just isn't worth duplicating for such a marginal
4343   // use-case.
4344   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4345     // Fast path this check, since we at least know the record has a
4346     // definition if we can find a member of it.
4347     if (!FD->getParent()->isCompleteDefinition()) {
4348       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4349         << E->getSourceRange();
4350       return true;
4351     }
4352 
4353     // Otherwise, if it's a field, and the field doesn't have
4354     // reference type, then it must have a complete type (or be a
4355     // flexible array member, which we explicitly want to
4356     // white-list anyway), which makes the following checks trivial.
4357     if (!FD->getType()->isReferenceType())
4358       return false;
4359   }
4360 
4361   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4362 }
4363 
CheckVecStepExpr(Expr * E)4364 bool Sema::CheckVecStepExpr(Expr *E) {
4365   E = E->IgnoreParens();
4366 
4367   // Cannot know anything else if the expression is dependent.
4368   if (E->isTypeDependent())
4369     return false;
4370 
4371   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4372 }
4373 
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)4374 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4375                                         CapturingScopeInfo *CSI) {
4376   assert(T->isVariablyModifiedType());
4377   assert(CSI != nullptr);
4378 
4379   // We're going to walk down into the type and look for VLA expressions.
4380   do {
4381     const Type *Ty = T.getTypePtr();
4382     switch (Ty->getTypeClass()) {
4383 #define TYPE(Class, Base)
4384 #define ABSTRACT_TYPE(Class, Base)
4385 #define NON_CANONICAL_TYPE(Class, Base)
4386 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4387 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4388 #include "clang/AST/TypeNodes.inc"
4389       T = QualType();
4390       break;
4391     // These types are never variably-modified.
4392     case Type::Builtin:
4393     case Type::Complex:
4394     case Type::Vector:
4395     case Type::ExtVector:
4396     case Type::ConstantMatrix:
4397     case Type::Record:
4398     case Type::Enum:
4399     case Type::Elaborated:
4400     case Type::TemplateSpecialization:
4401     case Type::ObjCObject:
4402     case Type::ObjCInterface:
4403     case Type::ObjCObjectPointer:
4404     case Type::ObjCTypeParam:
4405     case Type::Pipe:
4406     case Type::ExtInt:
4407       llvm_unreachable("type class is never variably-modified!");
4408     case Type::Adjusted:
4409       T = cast<AdjustedType>(Ty)->getOriginalType();
4410       break;
4411     case Type::Decayed:
4412       T = cast<DecayedType>(Ty)->getPointeeType();
4413       break;
4414     case Type::Pointer:
4415       T = cast<PointerType>(Ty)->getPointeeType();
4416       break;
4417     case Type::BlockPointer:
4418       T = cast<BlockPointerType>(Ty)->getPointeeType();
4419       break;
4420     case Type::LValueReference:
4421     case Type::RValueReference:
4422       T = cast<ReferenceType>(Ty)->getPointeeType();
4423       break;
4424     case Type::MemberPointer:
4425       T = cast<MemberPointerType>(Ty)->getPointeeType();
4426       break;
4427     case Type::ConstantArray:
4428     case Type::IncompleteArray:
4429       // Losing element qualification here is fine.
4430       T = cast<ArrayType>(Ty)->getElementType();
4431       break;
4432     case Type::VariableArray: {
4433       // Losing element qualification here is fine.
4434       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4435 
4436       // Unknown size indication requires no size computation.
4437       // Otherwise, evaluate and record it.
4438       auto Size = VAT->getSizeExpr();
4439       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4440           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4441         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4442 
4443       T = VAT->getElementType();
4444       break;
4445     }
4446     case Type::FunctionProto:
4447     case Type::FunctionNoProto:
4448       T = cast<FunctionType>(Ty)->getReturnType();
4449       break;
4450     case Type::Paren:
4451     case Type::TypeOf:
4452     case Type::UnaryTransform:
4453     case Type::Attributed:
4454     case Type::SubstTemplateTypeParm:
4455     case Type::MacroQualified:
4456       // Keep walking after single level desugaring.
4457       T = T.getSingleStepDesugaredType(Context);
4458       break;
4459     case Type::Typedef:
4460       T = cast<TypedefType>(Ty)->desugar();
4461       break;
4462     case Type::Decltype:
4463       T = cast<DecltypeType>(Ty)->desugar();
4464       break;
4465     case Type::Auto:
4466     case Type::DeducedTemplateSpecialization:
4467       T = cast<DeducedType>(Ty)->getDeducedType();
4468       break;
4469     case Type::TypeOfExpr:
4470       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4471       break;
4472     case Type::Atomic:
4473       T = cast<AtomicType>(Ty)->getValueType();
4474       break;
4475     }
4476   } while (!T.isNull() && T->isVariablyModifiedType());
4477 }
4478 
4479 /// Build a sizeof or alignof expression given a type operand.
4480 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)4481 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4482                                      SourceLocation OpLoc,
4483                                      UnaryExprOrTypeTrait ExprKind,
4484                                      SourceRange R) {
4485   if (!TInfo)
4486     return ExprError();
4487 
4488   QualType T = TInfo->getType();
4489 
4490   if (!T->isDependentType() &&
4491       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4492     return ExprError();
4493 
4494   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4495     if (auto *TT = T->getAs<TypedefType>()) {
4496       for (auto I = FunctionScopes.rbegin(),
4497                 E = std::prev(FunctionScopes.rend());
4498            I != E; ++I) {
4499         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4500         if (CSI == nullptr)
4501           break;
4502         DeclContext *DC = nullptr;
4503         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4504           DC = LSI->CallOperator;
4505         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4506           DC = CRSI->TheCapturedDecl;
4507         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4508           DC = BSI->TheDecl;
4509         if (DC) {
4510           if (DC->containsDecl(TT->getDecl()))
4511             break;
4512           captureVariablyModifiedType(Context, T, CSI);
4513         }
4514       }
4515     }
4516   }
4517 
4518   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4519   return new (Context) UnaryExprOrTypeTraitExpr(
4520       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4521 }
4522 
4523 /// Build a sizeof or alignof expression given an expression
4524 /// operand.
4525 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)4526 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4527                                      UnaryExprOrTypeTrait ExprKind) {
4528   ExprResult PE = CheckPlaceholderExpr(E);
4529   if (PE.isInvalid())
4530     return ExprError();
4531 
4532   E = PE.get();
4533 
4534   // Verify that the operand is valid.
4535   bool isInvalid = false;
4536   if (E->isTypeDependent()) {
4537     // Delay type-checking for type-dependent expressions.
4538   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4539     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4540   } else if (ExprKind == UETT_VecStep) {
4541     isInvalid = CheckVecStepExpr(E);
4542   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4543       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4544       isInvalid = true;
4545   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4546     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4547     isInvalid = true;
4548   } else {
4549     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4550   }
4551 
4552   if (isInvalid)
4553     return ExprError();
4554 
4555   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4556     PE = TransformToPotentiallyEvaluated(E);
4557     if (PE.isInvalid()) return ExprError();
4558     E = PE.get();
4559   }
4560 
4561   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4562   return new (Context) UnaryExprOrTypeTraitExpr(
4563       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4564 }
4565 
4566 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4567 /// expr and the same for @c alignof and @c __alignof
4568 /// Note that the ArgRange is invalid if isType is false.
4569 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4570 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4571                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4572                                     void *TyOrEx, SourceRange ArgRange) {
4573   // If error parsing type, ignore.
4574   if (!TyOrEx) return ExprError();
4575 
4576   if (IsType) {
4577     TypeSourceInfo *TInfo;
4578     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4579     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4580   }
4581 
4582   Expr *ArgEx = (Expr *)TyOrEx;
4583   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4584   return Result;
4585 }
4586 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4587 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4588                                      bool IsReal) {
4589   if (V.get()->isTypeDependent())
4590     return S.Context.DependentTy;
4591 
4592   // _Real and _Imag are only l-values for normal l-values.
4593   if (V.get()->getObjectKind() != OK_Ordinary) {
4594     V = S.DefaultLvalueConversion(V.get());
4595     if (V.isInvalid())
4596       return QualType();
4597   }
4598 
4599   // These operators return the element type of a complex type.
4600   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4601     return CT->getElementType();
4602 
4603   // Otherwise they pass through real integer and floating point types here.
4604   if (V.get()->getType()->isArithmeticType())
4605     return V.get()->getType();
4606 
4607   // Test for placeholders.
4608   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4609   if (PR.isInvalid()) return QualType();
4610   if (PR.get() != V.get()) {
4611     V = PR;
4612     return CheckRealImagOperand(S, V, Loc, IsReal);
4613   }
4614 
4615   // Reject anything else.
4616   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4617     << (IsReal ? "__real" : "__imag");
4618   return QualType();
4619 }
4620 
4621 
4622 
4623 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4624 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4625                           tok::TokenKind Kind, Expr *Input) {
4626   UnaryOperatorKind Opc;
4627   switch (Kind) {
4628   default: llvm_unreachable("Unknown unary op!");
4629   case tok::plusplus:   Opc = UO_PostInc; break;
4630   case tok::minusminus: Opc = UO_PostDec; break;
4631   }
4632 
4633   // Since this might is a postfix expression, get rid of ParenListExprs.
4634   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4635   if (Result.isInvalid()) return ExprError();
4636   Input = Result.get();
4637 
4638   return BuildUnaryOp(S, OpLoc, Opc, Input);
4639 }
4640 
4641 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4642 ///
4643 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4644 static bool checkArithmeticOnObjCPointer(Sema &S,
4645                                          SourceLocation opLoc,
4646                                          Expr *op) {
4647   assert(op->getType()->isObjCObjectPointerType());
4648   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4649       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4650     return false;
4651 
4652   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4653     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4654     << op->getSourceRange();
4655   return true;
4656 }
4657 
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4658 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4659   auto *BaseNoParens = Base->IgnoreParens();
4660   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4661     return MSProp->getPropertyDecl()->getType()->isArrayType();
4662   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4663 }
4664 
4665 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4666 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4667                               Expr *idx, SourceLocation rbLoc) {
4668   if (base && !base->getType().isNull() &&
4669       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4670     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4671                                     SourceLocation(), /*Length*/ nullptr,
4672                                     /*Stride=*/nullptr, rbLoc);
4673 
4674   // Since this might be a postfix expression, get rid of ParenListExprs.
4675   if (isa<ParenListExpr>(base)) {
4676     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4677     if (result.isInvalid()) return ExprError();
4678     base = result.get();
4679   }
4680 
4681   // Check if base and idx form a MatrixSubscriptExpr.
4682   //
4683   // Helper to check for comma expressions, which are not allowed as indices for
4684   // matrix subscript expressions.
4685   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4686     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4687       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4688           << SourceRange(base->getBeginLoc(), rbLoc);
4689       return true;
4690     }
4691     return false;
4692   };
4693   // The matrix subscript operator ([][])is considered a single operator.
4694   // Separating the index expressions by parenthesis is not allowed.
4695   if (base->getType()->isSpecificPlaceholderType(
4696           BuiltinType::IncompleteMatrixIdx) &&
4697       !isa<MatrixSubscriptExpr>(base)) {
4698     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4699         << SourceRange(base->getBeginLoc(), rbLoc);
4700     return ExprError();
4701   }
4702   // If the base is a MatrixSubscriptExpr, try to create a new
4703   // MatrixSubscriptExpr.
4704   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4705   if (matSubscriptE) {
4706     if (CheckAndReportCommaError(idx))
4707       return ExprError();
4708 
4709     assert(matSubscriptE->isIncomplete() &&
4710            "base has to be an incomplete matrix subscript");
4711     return CreateBuiltinMatrixSubscriptExpr(
4712         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4713   }
4714 
4715   // Handle any non-overload placeholder types in the base and index
4716   // expressions.  We can't handle overloads here because the other
4717   // operand might be an overloadable type, in which case the overload
4718   // resolution for the operator overload should get the first crack
4719   // at the overload.
4720   bool IsMSPropertySubscript = false;
4721   if (base->getType()->isNonOverloadPlaceholderType()) {
4722     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4723     if (!IsMSPropertySubscript) {
4724       ExprResult result = CheckPlaceholderExpr(base);
4725       if (result.isInvalid())
4726         return ExprError();
4727       base = result.get();
4728     }
4729   }
4730 
4731   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4732   if (base->getType()->isMatrixType()) {
4733     if (CheckAndReportCommaError(idx))
4734       return ExprError();
4735 
4736     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4737   }
4738 
4739   // A comma-expression as the index is deprecated in C++2a onwards.
4740   if (getLangOpts().CPlusPlus20 &&
4741       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4742        (isa<CXXOperatorCallExpr>(idx) &&
4743         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4744     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4745         << SourceRange(base->getBeginLoc(), rbLoc);
4746   }
4747 
4748   if (idx->getType()->isNonOverloadPlaceholderType()) {
4749     ExprResult result = CheckPlaceholderExpr(idx);
4750     if (result.isInvalid()) return ExprError();
4751     idx = result.get();
4752   }
4753 
4754   // Build an unanalyzed expression if either operand is type-dependent.
4755   if (getLangOpts().CPlusPlus &&
4756       (base->isTypeDependent() || idx->isTypeDependent())) {
4757     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4758                                             VK_LValue, OK_Ordinary, rbLoc);
4759   }
4760 
4761   // MSDN, property (C++)
4762   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4763   // This attribute can also be used in the declaration of an empty array in a
4764   // class or structure definition. For example:
4765   // __declspec(property(get=GetX, put=PutX)) int x[];
4766   // The above statement indicates that x[] can be used with one or more array
4767   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4768   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4769   if (IsMSPropertySubscript) {
4770     // Build MS property subscript expression if base is MS property reference
4771     // or MS property subscript.
4772     return new (Context) MSPropertySubscriptExpr(
4773         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4774   }
4775 
4776   // Use C++ overloaded-operator rules if either operand has record
4777   // type.  The spec says to do this if either type is *overloadable*,
4778   // but enum types can't declare subscript operators or conversion
4779   // operators, so there's nothing interesting for overload resolution
4780   // to do if there aren't any record types involved.
4781   //
4782   // ObjC pointers have their own subscripting logic that is not tied
4783   // to overload resolution and so should not take this path.
4784   if (getLangOpts().CPlusPlus &&
4785       (base->getType()->isRecordType() ||
4786        (!base->getType()->isObjCObjectPointerType() &&
4787         idx->getType()->isRecordType()))) {
4788     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4789   }
4790 
4791   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4792 
4793   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4794     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4795 
4796   return Res;
4797 }
4798 
tryConvertExprToType(Expr * E,QualType Ty)4799 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4800   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4801   InitializationKind Kind =
4802       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4803   InitializationSequence InitSeq(*this, Entity, Kind, E);
4804   return InitSeq.Perform(*this, Entity, Kind, E);
4805 }
4806 
CreateBuiltinMatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,SourceLocation RBLoc)4807 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4808                                                   Expr *ColumnIdx,
4809                                                   SourceLocation RBLoc) {
4810   ExprResult BaseR = CheckPlaceholderExpr(Base);
4811   if (BaseR.isInvalid())
4812     return BaseR;
4813   Base = BaseR.get();
4814 
4815   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4816   if (RowR.isInvalid())
4817     return RowR;
4818   RowIdx = RowR.get();
4819 
4820   if (!ColumnIdx)
4821     return new (Context) MatrixSubscriptExpr(
4822         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4823 
4824   // Build an unanalyzed expression if any of the operands is type-dependent.
4825   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4826       ColumnIdx->isTypeDependent())
4827     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4828                                              Context.DependentTy, RBLoc);
4829 
4830   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4831   if (ColumnR.isInvalid())
4832     return ColumnR;
4833   ColumnIdx = ColumnR.get();
4834 
4835   // Check that IndexExpr is an integer expression. If it is a constant
4836   // expression, check that it is less than Dim (= the number of elements in the
4837   // corresponding dimension).
4838   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4839                           bool IsColumnIdx) -> Expr * {
4840     if (!IndexExpr->getType()->isIntegerType() &&
4841         !IndexExpr->isTypeDependent()) {
4842       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4843           << IsColumnIdx;
4844       return nullptr;
4845     }
4846 
4847     if (Optional<llvm::APSInt> Idx =
4848             IndexExpr->getIntegerConstantExpr(Context)) {
4849       if ((*Idx < 0 || *Idx >= Dim)) {
4850         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4851             << IsColumnIdx << Dim;
4852         return nullptr;
4853       }
4854     }
4855 
4856     ExprResult ConvExpr =
4857         tryConvertExprToType(IndexExpr, Context.getSizeType());
4858     assert(!ConvExpr.isInvalid() &&
4859            "should be able to convert any integer type to size type");
4860     return ConvExpr.get();
4861   };
4862 
4863   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4864   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4865   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4866   if (!RowIdx || !ColumnIdx)
4867     return ExprError();
4868 
4869   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4870                                            MTy->getElementType(), RBLoc);
4871 }
4872 
CheckAddressOfNoDeref(const Expr * E)4873 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4874   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4875   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4876 
4877   // For expressions like `&(*s).b`, the base is recorded and what should be
4878   // checked.
4879   const MemberExpr *Member = nullptr;
4880   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4881     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4882 
4883   LastRecord.PossibleDerefs.erase(StrippedExpr);
4884 }
4885 
CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr * E)4886 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4887   if (isUnevaluatedContext())
4888     return;
4889 
4890   QualType ResultTy = E->getType();
4891   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4892 
4893   // Bail if the element is an array since it is not memory access.
4894   if (isa<ArrayType>(ResultTy))
4895     return;
4896 
4897   if (ResultTy->hasAttr(attr::NoDeref)) {
4898     LastRecord.PossibleDerefs.insert(E);
4899     return;
4900   }
4901 
4902   // Check if the base type is a pointer to a member access of a struct
4903   // marked with noderef.
4904   const Expr *Base = E->getBase();
4905   QualType BaseTy = Base->getType();
4906   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4907     // Not a pointer access
4908     return;
4909 
4910   const MemberExpr *Member = nullptr;
4911   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4912          Member->isArrow())
4913     Base = Member->getBase();
4914 
4915   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4916     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4917       LastRecord.PossibleDerefs.insert(E);
4918   }
4919 }
4920 
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLocFirst,SourceLocation ColonLocSecond,Expr * Length,Expr * Stride,SourceLocation RBLoc)4921 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4922                                           Expr *LowerBound,
4923                                           SourceLocation ColonLocFirst,
4924                                           SourceLocation ColonLocSecond,
4925                                           Expr *Length, Expr *Stride,
4926                                           SourceLocation RBLoc) {
4927   if (Base->getType()->isPlaceholderType() &&
4928       !Base->getType()->isSpecificPlaceholderType(
4929           BuiltinType::OMPArraySection)) {
4930     ExprResult Result = CheckPlaceholderExpr(Base);
4931     if (Result.isInvalid())
4932       return ExprError();
4933     Base = Result.get();
4934   }
4935   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4936     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4937     if (Result.isInvalid())
4938       return ExprError();
4939     Result = DefaultLvalueConversion(Result.get());
4940     if (Result.isInvalid())
4941       return ExprError();
4942     LowerBound = Result.get();
4943   }
4944   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4945     ExprResult Result = CheckPlaceholderExpr(Length);
4946     if (Result.isInvalid())
4947       return ExprError();
4948     Result = DefaultLvalueConversion(Result.get());
4949     if (Result.isInvalid())
4950       return ExprError();
4951     Length = Result.get();
4952   }
4953   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4954     ExprResult Result = CheckPlaceholderExpr(Stride);
4955     if (Result.isInvalid())
4956       return ExprError();
4957     Result = DefaultLvalueConversion(Result.get());
4958     if (Result.isInvalid())
4959       return ExprError();
4960     Stride = Result.get();
4961   }
4962 
4963   // Build an unanalyzed expression if either operand is type-dependent.
4964   if (Base->isTypeDependent() ||
4965       (LowerBound &&
4966        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4967       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4968       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4969     return new (Context) OMPArraySectionExpr(
4970         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4971         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4972   }
4973 
4974   // Perform default conversions.
4975   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4976   QualType ResultTy;
4977   if (OriginalTy->isAnyPointerType()) {
4978     ResultTy = OriginalTy->getPointeeType();
4979   } else if (OriginalTy->isArrayType()) {
4980     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4981   } else {
4982     return ExprError(
4983         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4984         << Base->getSourceRange());
4985   }
4986   // C99 6.5.2.1p1
4987   if (LowerBound) {
4988     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4989                                                       LowerBound);
4990     if (Res.isInvalid())
4991       return ExprError(Diag(LowerBound->getExprLoc(),
4992                             diag::err_omp_typecheck_section_not_integer)
4993                        << 0 << LowerBound->getSourceRange());
4994     LowerBound = Res.get();
4995 
4996     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4997         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4998       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4999           << 0 << LowerBound->getSourceRange();
5000   }
5001   if (Length) {
5002     auto Res =
5003         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5004     if (Res.isInvalid())
5005       return ExprError(Diag(Length->getExprLoc(),
5006                             diag::err_omp_typecheck_section_not_integer)
5007                        << 1 << Length->getSourceRange());
5008     Length = Res.get();
5009 
5010     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5011         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5012       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5013           << 1 << Length->getSourceRange();
5014   }
5015   if (Stride) {
5016     ExprResult Res =
5017         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5018     if (Res.isInvalid())
5019       return ExprError(Diag(Stride->getExprLoc(),
5020                             diag::err_omp_typecheck_section_not_integer)
5021                        << 1 << Stride->getSourceRange());
5022     Stride = Res.get();
5023 
5024     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5025         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5026       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5027           << 1 << Stride->getSourceRange();
5028   }
5029 
5030   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5031   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5032   // type. Note that functions are not objects, and that (in C99 parlance)
5033   // incomplete types are not object types.
5034   if (ResultTy->isFunctionType()) {
5035     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5036         << ResultTy << Base->getSourceRange();
5037     return ExprError();
5038   }
5039 
5040   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5041                           diag::err_omp_section_incomplete_type, Base))
5042     return ExprError();
5043 
5044   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5045     Expr::EvalResult Result;
5046     if (LowerBound->EvaluateAsInt(Result, Context)) {
5047       // OpenMP 5.0, [2.1.5 Array Sections]
5048       // The array section must be a subset of the original array.
5049       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5050       if (LowerBoundValue.isNegative()) {
5051         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5052             << LowerBound->getSourceRange();
5053         return ExprError();
5054       }
5055     }
5056   }
5057 
5058   if (Length) {
5059     Expr::EvalResult Result;
5060     if (Length->EvaluateAsInt(Result, Context)) {
5061       // OpenMP 5.0, [2.1.5 Array Sections]
5062       // The length must evaluate to non-negative integers.
5063       llvm::APSInt LengthValue = Result.Val.getInt();
5064       if (LengthValue.isNegative()) {
5065         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5066             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5067             << Length->getSourceRange();
5068         return ExprError();
5069       }
5070     }
5071   } else if (ColonLocFirst.isValid() &&
5072              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5073                                       !OriginalTy->isVariableArrayType()))) {
5074     // OpenMP 5.0, [2.1.5 Array Sections]
5075     // When the size of the array dimension is not known, the length must be
5076     // specified explicitly.
5077     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5078         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5079     return ExprError();
5080   }
5081 
5082   if (Stride) {
5083     Expr::EvalResult Result;
5084     if (Stride->EvaluateAsInt(Result, Context)) {
5085       // OpenMP 5.0, [2.1.5 Array Sections]
5086       // The stride must evaluate to a positive integer.
5087       llvm::APSInt StrideValue = Result.Val.getInt();
5088       if (!StrideValue.isStrictlyPositive()) {
5089         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5090             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5091             << Stride->getSourceRange();
5092         return ExprError();
5093       }
5094     }
5095   }
5096 
5097   if (!Base->getType()->isSpecificPlaceholderType(
5098           BuiltinType::OMPArraySection)) {
5099     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5100     if (Result.isInvalid())
5101       return ExprError();
5102     Base = Result.get();
5103   }
5104   return new (Context) OMPArraySectionExpr(
5105       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5106       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5107 }
5108 
ActOnOMPArrayShapingExpr(Expr * Base,SourceLocation LParenLoc,SourceLocation RParenLoc,ArrayRef<Expr * > Dims,ArrayRef<SourceRange> Brackets)5109 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5110                                           SourceLocation RParenLoc,
5111                                           ArrayRef<Expr *> Dims,
5112                                           ArrayRef<SourceRange> Brackets) {
5113   if (Base->getType()->isPlaceholderType()) {
5114     ExprResult Result = CheckPlaceholderExpr(Base);
5115     if (Result.isInvalid())
5116       return ExprError();
5117     Result = DefaultLvalueConversion(Result.get());
5118     if (Result.isInvalid())
5119       return ExprError();
5120     Base = Result.get();
5121   }
5122   QualType BaseTy = Base->getType();
5123   // Delay analysis of the types/expressions if instantiation/specialization is
5124   // required.
5125   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5126     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5127                                        LParenLoc, RParenLoc, Dims, Brackets);
5128   if (!BaseTy->isPointerType() ||
5129       (!Base->isTypeDependent() &&
5130        BaseTy->getPointeeType()->isIncompleteType()))
5131     return ExprError(Diag(Base->getExprLoc(),
5132                           diag::err_omp_non_pointer_type_array_shaping_base)
5133                      << Base->getSourceRange());
5134 
5135   SmallVector<Expr *, 4> NewDims;
5136   bool ErrorFound = false;
5137   for (Expr *Dim : Dims) {
5138     if (Dim->getType()->isPlaceholderType()) {
5139       ExprResult Result = CheckPlaceholderExpr(Dim);
5140       if (Result.isInvalid()) {
5141         ErrorFound = true;
5142         continue;
5143       }
5144       Result = DefaultLvalueConversion(Result.get());
5145       if (Result.isInvalid()) {
5146         ErrorFound = true;
5147         continue;
5148       }
5149       Dim = Result.get();
5150     }
5151     if (!Dim->isTypeDependent()) {
5152       ExprResult Result =
5153           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5154       if (Result.isInvalid()) {
5155         ErrorFound = true;
5156         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5157             << Dim->getSourceRange();
5158         continue;
5159       }
5160       Dim = Result.get();
5161       Expr::EvalResult EvResult;
5162       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5163         // OpenMP 5.0, [2.1.4 Array Shaping]
5164         // Each si is an integral type expression that must evaluate to a
5165         // positive integer.
5166         llvm::APSInt Value = EvResult.Val.getInt();
5167         if (!Value.isStrictlyPositive()) {
5168           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5169               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5170               << Dim->getSourceRange();
5171           ErrorFound = true;
5172           continue;
5173         }
5174       }
5175     }
5176     NewDims.push_back(Dim);
5177   }
5178   if (ErrorFound)
5179     return ExprError();
5180   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5181                                      LParenLoc, RParenLoc, NewDims, Brackets);
5182 }
5183 
ActOnOMPIteratorExpr(Scope * S,SourceLocation IteratorKwLoc,SourceLocation LLoc,SourceLocation RLoc,ArrayRef<OMPIteratorData> Data)5184 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5185                                       SourceLocation LLoc, SourceLocation RLoc,
5186                                       ArrayRef<OMPIteratorData> Data) {
5187   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5188   bool IsCorrect = true;
5189   for (const OMPIteratorData &D : Data) {
5190     TypeSourceInfo *TInfo = nullptr;
5191     SourceLocation StartLoc;
5192     QualType DeclTy;
5193     if (!D.Type.getAsOpaquePtr()) {
5194       // OpenMP 5.0, 2.1.6 Iterators
5195       // In an iterator-specifier, if the iterator-type is not specified then
5196       // the type of that iterator is of int type.
5197       DeclTy = Context.IntTy;
5198       StartLoc = D.DeclIdentLoc;
5199     } else {
5200       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5201       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5202     }
5203 
5204     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5205                              DeclTy->containsUnexpandedParameterPack() ||
5206                              DeclTy->isInstantiationDependentType();
5207     if (!IsDeclTyDependent) {
5208       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5209         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5210         // The iterator-type must be an integral or pointer type.
5211         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5212             << DeclTy;
5213         IsCorrect = false;
5214         continue;
5215       }
5216       if (DeclTy.isConstant(Context)) {
5217         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5218         // The iterator-type must not be const qualified.
5219         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5220             << DeclTy;
5221         IsCorrect = false;
5222         continue;
5223       }
5224     }
5225 
5226     // Iterator declaration.
5227     assert(D.DeclIdent && "Identifier expected.");
5228     // Always try to create iterator declarator to avoid extra error messages
5229     // about unknown declarations use.
5230     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5231                                D.DeclIdent, DeclTy, TInfo, SC_None);
5232     VD->setImplicit();
5233     if (S) {
5234       // Check for conflicting previous declaration.
5235       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5236       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5237                             ForVisibleRedeclaration);
5238       Previous.suppressDiagnostics();
5239       LookupName(Previous, S);
5240 
5241       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5242                            /*AllowInlineNamespace=*/false);
5243       if (!Previous.empty()) {
5244         NamedDecl *Old = Previous.getRepresentativeDecl();
5245         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5246         Diag(Old->getLocation(), diag::note_previous_definition);
5247       } else {
5248         PushOnScopeChains(VD, S);
5249       }
5250     } else {
5251       CurContext->addDecl(VD);
5252     }
5253     Expr *Begin = D.Range.Begin;
5254     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5255       ExprResult BeginRes =
5256           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5257       Begin = BeginRes.get();
5258     }
5259     Expr *End = D.Range.End;
5260     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5261       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5262       End = EndRes.get();
5263     }
5264     Expr *Step = D.Range.Step;
5265     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5266       if (!Step->getType()->isIntegralType(Context)) {
5267         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5268             << Step << Step->getSourceRange();
5269         IsCorrect = false;
5270         continue;
5271       }
5272       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5273       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5274       // If the step expression of a range-specification equals zero, the
5275       // behavior is unspecified.
5276       if (Result && Result->isNullValue()) {
5277         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5278             << Step << Step->getSourceRange();
5279         IsCorrect = false;
5280         continue;
5281       }
5282     }
5283     if (!Begin || !End || !IsCorrect) {
5284       IsCorrect = false;
5285       continue;
5286     }
5287     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5288     IDElem.IteratorDecl = VD;
5289     IDElem.AssignmentLoc = D.AssignLoc;
5290     IDElem.Range.Begin = Begin;
5291     IDElem.Range.End = End;
5292     IDElem.Range.Step = Step;
5293     IDElem.ColonLoc = D.ColonLoc;
5294     IDElem.SecondColonLoc = D.SecColonLoc;
5295   }
5296   if (!IsCorrect) {
5297     // Invalidate all created iterator declarations if error is found.
5298     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5299       if (Decl *ID = D.IteratorDecl)
5300         ID->setInvalidDecl();
5301     }
5302     return ExprError();
5303   }
5304   SmallVector<OMPIteratorHelperData, 4> Helpers;
5305   if (!CurContext->isDependentContext()) {
5306     // Build number of ityeration for each iteration range.
5307     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5308     // ((Begini-Stepi-1-Endi) / -Stepi);
5309     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5310       // (Endi - Begini)
5311       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5312                                           D.Range.Begin);
5313       if(!Res.isUsable()) {
5314         IsCorrect = false;
5315         continue;
5316       }
5317       ExprResult St, St1;
5318       if (D.Range.Step) {
5319         St = D.Range.Step;
5320         // (Endi - Begini) + Stepi
5321         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5322         if (!Res.isUsable()) {
5323           IsCorrect = false;
5324           continue;
5325         }
5326         // (Endi - Begini) + Stepi - 1
5327         Res =
5328             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5329                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5330         if (!Res.isUsable()) {
5331           IsCorrect = false;
5332           continue;
5333         }
5334         // ((Endi - Begini) + Stepi - 1) / Stepi
5335         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5336         if (!Res.isUsable()) {
5337           IsCorrect = false;
5338           continue;
5339         }
5340         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5341         // (Begini - Endi)
5342         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5343                                              D.Range.Begin, D.Range.End);
5344         if (!Res1.isUsable()) {
5345           IsCorrect = false;
5346           continue;
5347         }
5348         // (Begini - Endi) - Stepi
5349         Res1 =
5350             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5351         if (!Res1.isUsable()) {
5352           IsCorrect = false;
5353           continue;
5354         }
5355         // (Begini - Endi) - Stepi - 1
5356         Res1 =
5357             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5358                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5359         if (!Res1.isUsable()) {
5360           IsCorrect = false;
5361           continue;
5362         }
5363         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5364         Res1 =
5365             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5366         if (!Res1.isUsable()) {
5367           IsCorrect = false;
5368           continue;
5369         }
5370         // Stepi > 0.
5371         ExprResult CmpRes =
5372             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5373                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5374         if (!CmpRes.isUsable()) {
5375           IsCorrect = false;
5376           continue;
5377         }
5378         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5379                                  Res.get(), Res1.get());
5380         if (!Res.isUsable()) {
5381           IsCorrect = false;
5382           continue;
5383         }
5384       }
5385       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5386       if (!Res.isUsable()) {
5387         IsCorrect = false;
5388         continue;
5389       }
5390 
5391       // Build counter update.
5392       // Build counter.
5393       auto *CounterVD =
5394           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5395                           D.IteratorDecl->getBeginLoc(), nullptr,
5396                           Res.get()->getType(), nullptr, SC_None);
5397       CounterVD->setImplicit();
5398       ExprResult RefRes =
5399           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5400                            D.IteratorDecl->getBeginLoc());
5401       // Build counter update.
5402       // I = Begini + counter * Stepi;
5403       ExprResult UpdateRes;
5404       if (D.Range.Step) {
5405         UpdateRes = CreateBuiltinBinOp(
5406             D.AssignmentLoc, BO_Mul,
5407             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5408       } else {
5409         UpdateRes = DefaultLvalueConversion(RefRes.get());
5410       }
5411       if (!UpdateRes.isUsable()) {
5412         IsCorrect = false;
5413         continue;
5414       }
5415       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5416                                      UpdateRes.get());
5417       if (!UpdateRes.isUsable()) {
5418         IsCorrect = false;
5419         continue;
5420       }
5421       ExprResult VDRes =
5422           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5423                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5424                            D.IteratorDecl->getBeginLoc());
5425       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5426                                      UpdateRes.get());
5427       if (!UpdateRes.isUsable()) {
5428         IsCorrect = false;
5429         continue;
5430       }
5431       UpdateRes =
5432           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5433       if (!UpdateRes.isUsable()) {
5434         IsCorrect = false;
5435         continue;
5436       }
5437       ExprResult CounterUpdateRes =
5438           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5439       if (!CounterUpdateRes.isUsable()) {
5440         IsCorrect = false;
5441         continue;
5442       }
5443       CounterUpdateRes =
5444           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5445       if (!CounterUpdateRes.isUsable()) {
5446         IsCorrect = false;
5447         continue;
5448       }
5449       OMPIteratorHelperData &HD = Helpers.emplace_back();
5450       HD.CounterVD = CounterVD;
5451       HD.Upper = Res.get();
5452       HD.Update = UpdateRes.get();
5453       HD.CounterUpdate = CounterUpdateRes.get();
5454     }
5455   } else {
5456     Helpers.assign(ID.size(), {});
5457   }
5458   if (!IsCorrect) {
5459     // Invalidate all created iterator declarations if error is found.
5460     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5461       if (Decl *ID = D.IteratorDecl)
5462         ID->setInvalidDecl();
5463     }
5464     return ExprError();
5465   }
5466   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5467                                  LLoc, RLoc, ID, Helpers);
5468 }
5469 
5470 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)5471 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5472                                       Expr *Idx, SourceLocation RLoc) {
5473   Expr *LHSExp = Base;
5474   Expr *RHSExp = Idx;
5475 
5476   ExprValueKind VK = VK_LValue;
5477   ExprObjectKind OK = OK_Ordinary;
5478 
5479   // Per C++ core issue 1213, the result is an xvalue if either operand is
5480   // a non-lvalue array, and an lvalue otherwise.
5481   if (getLangOpts().CPlusPlus11) {
5482     for (auto *Op : {LHSExp, RHSExp}) {
5483       Op = Op->IgnoreImplicit();
5484       if (Op->getType()->isArrayType() && !Op->isLValue())
5485         VK = VK_XValue;
5486     }
5487   }
5488 
5489   // Perform default conversions.
5490   if (!LHSExp->getType()->getAs<VectorType>()) {
5491     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5492     if (Result.isInvalid())
5493       return ExprError();
5494     LHSExp = Result.get();
5495   }
5496   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5497   if (Result.isInvalid())
5498     return ExprError();
5499   RHSExp = Result.get();
5500 
5501   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5502 
5503   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5504   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5505   // in the subscript position. As a result, we need to derive the array base
5506   // and index from the expression types.
5507   Expr *BaseExpr, *IndexExpr;
5508   QualType ResultType;
5509   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5510     BaseExpr = LHSExp;
5511     IndexExpr = RHSExp;
5512     ResultType = Context.DependentTy;
5513   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5514     BaseExpr = LHSExp;
5515     IndexExpr = RHSExp;
5516     ResultType = PTy->getPointeeType();
5517   } else if (const ObjCObjectPointerType *PTy =
5518                LHSTy->getAs<ObjCObjectPointerType>()) {
5519     BaseExpr = LHSExp;
5520     IndexExpr = RHSExp;
5521 
5522     // Use custom logic if this should be the pseudo-object subscript
5523     // expression.
5524     if (!LangOpts.isSubscriptPointerArithmetic())
5525       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5526                                           nullptr);
5527 
5528     ResultType = PTy->getPointeeType();
5529   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5530      // Handle the uncommon case of "123[Ptr]".
5531     BaseExpr = RHSExp;
5532     IndexExpr = LHSExp;
5533     ResultType = PTy->getPointeeType();
5534   } else if (const ObjCObjectPointerType *PTy =
5535                RHSTy->getAs<ObjCObjectPointerType>()) {
5536      // Handle the uncommon case of "123[Ptr]".
5537     BaseExpr = RHSExp;
5538     IndexExpr = LHSExp;
5539     ResultType = PTy->getPointeeType();
5540     if (!LangOpts.isSubscriptPointerArithmetic()) {
5541       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5542         << ResultType << BaseExpr->getSourceRange();
5543       return ExprError();
5544     }
5545   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5546     BaseExpr = LHSExp;    // vectors: V[123]
5547     IndexExpr = RHSExp;
5548     // We apply C++ DR1213 to vector subscripting too.
5549     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5550       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5551       if (Materialized.isInvalid())
5552         return ExprError();
5553       LHSExp = Materialized.get();
5554     }
5555     VK = LHSExp->getValueKind();
5556     if (VK != VK_PRValue)
5557       OK = OK_VectorComponent;
5558 
5559     ResultType = VTy->getElementType();
5560     QualType BaseType = BaseExpr->getType();
5561     Qualifiers BaseQuals = BaseType.getQualifiers();
5562     Qualifiers MemberQuals = ResultType.getQualifiers();
5563     Qualifiers Combined = BaseQuals + MemberQuals;
5564     if (Combined != MemberQuals)
5565       ResultType = Context.getQualifiedType(ResultType, Combined);
5566   } else if (LHSTy->isArrayType()) {
5567     // If we see an array that wasn't promoted by
5568     // DefaultFunctionArrayLvalueConversion, it must be an array that
5569     // wasn't promoted because of the C90 rule that doesn't
5570     // allow promoting non-lvalue arrays.  Warn, then
5571     // force the promotion here.
5572     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5573         << LHSExp->getSourceRange();
5574     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5575                                CK_ArrayToPointerDecay).get();
5576     LHSTy = LHSExp->getType();
5577 
5578     BaseExpr = LHSExp;
5579     IndexExpr = RHSExp;
5580     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5581   } else if (RHSTy->isArrayType()) {
5582     // Same as previous, except for 123[f().a] case
5583     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5584         << RHSExp->getSourceRange();
5585     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5586                                CK_ArrayToPointerDecay).get();
5587     RHSTy = RHSExp->getType();
5588 
5589     BaseExpr = RHSExp;
5590     IndexExpr = LHSExp;
5591     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5592   } else {
5593     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5594        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5595   }
5596   // C99 6.5.2.1p1
5597   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5598     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5599                      << IndexExpr->getSourceRange());
5600 
5601   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5602        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5603          && !IndexExpr->isTypeDependent())
5604     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5605 
5606   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5607   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5608   // type. Note that Functions are not objects, and that (in C99 parlance)
5609   // incomplete types are not object types.
5610   if (ResultType->isFunctionType()) {
5611     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5612         << ResultType << BaseExpr->getSourceRange();
5613     return ExprError();
5614   }
5615 
5616   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5617     // GNU extension: subscripting on pointer to void
5618     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5619       << BaseExpr->getSourceRange();
5620 
5621     // C forbids expressions of unqualified void type from being l-values.
5622     // See IsCForbiddenLValueType.
5623     if (!ResultType.hasQualifiers())
5624       VK = VK_PRValue;
5625   } else if (!ResultType->isDependentType() &&
5626              RequireCompleteSizedType(
5627                  LLoc, ResultType,
5628                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5629     return ExprError();
5630 
5631   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5632          !ResultType.isCForbiddenLValueType());
5633 
5634   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5635       FunctionScopes.size() > 1) {
5636     if (auto *TT =
5637             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5638       for (auto I = FunctionScopes.rbegin(),
5639                 E = std::prev(FunctionScopes.rend());
5640            I != E; ++I) {
5641         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5642         if (CSI == nullptr)
5643           break;
5644         DeclContext *DC = nullptr;
5645         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5646           DC = LSI->CallOperator;
5647         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5648           DC = CRSI->TheCapturedDecl;
5649         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5650           DC = BSI->TheDecl;
5651         if (DC) {
5652           if (DC->containsDecl(TT->getDecl()))
5653             break;
5654           captureVariablyModifiedType(
5655               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5656         }
5657       }
5658     }
5659   }
5660 
5661   return new (Context)
5662       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5663 }
5664 
CheckCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5665 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5666                                   ParmVarDecl *Param) {
5667   if (Param->hasUnparsedDefaultArg()) {
5668     // If we've already cleared out the location for the default argument,
5669     // that means we're parsing it right now.
5670     if (!UnparsedDefaultArgLocs.count(Param)) {
5671       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5672       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5673       Param->setInvalidDecl();
5674       return true;
5675     }
5676 
5677     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5678         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5679     Diag(UnparsedDefaultArgLocs[Param],
5680          diag::note_default_argument_declared_here);
5681     return true;
5682   }
5683 
5684   if (Param->hasUninstantiatedDefaultArg() &&
5685       InstantiateDefaultArgument(CallLoc, FD, Param))
5686     return true;
5687 
5688   assert(Param->hasInit() && "default argument but no initializer?");
5689 
5690   // If the default expression creates temporaries, we need to
5691   // push them to the current stack of expression temporaries so they'll
5692   // be properly destroyed.
5693   // FIXME: We should really be rebuilding the default argument with new
5694   // bound temporaries; see the comment in PR5810.
5695   // We don't need to do that with block decls, though, because
5696   // blocks in default argument expression can never capture anything.
5697   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5698     // Set the "needs cleanups" bit regardless of whether there are
5699     // any explicit objects.
5700     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5701 
5702     // Append all the objects to the cleanup list.  Right now, this
5703     // should always be a no-op, because blocks in default argument
5704     // expressions should never be able to capture anything.
5705     assert(!Init->getNumObjects() &&
5706            "default argument expression has capturing blocks?");
5707   }
5708 
5709   // We already type-checked the argument, so we know it works.
5710   // Just mark all of the declarations in this potentially-evaluated expression
5711   // as being "referenced".
5712   EnterExpressionEvaluationContext EvalContext(
5713       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5714   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5715                                    /*SkipLocalVariables=*/true);
5716   return false;
5717 }
5718 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5719 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5720                                         FunctionDecl *FD, ParmVarDecl *Param) {
5721   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5722   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5723     return ExprError();
5724   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5725 }
5726 
5727 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)5728 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5729                           Expr *Fn) {
5730   if (Proto && Proto->isVariadic()) {
5731     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5732       return VariadicConstructor;
5733     else if (Fn && Fn->getType()->isBlockPointerType())
5734       return VariadicBlock;
5735     else if (FDecl) {
5736       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5737         if (Method->isInstance())
5738           return VariadicMethod;
5739     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5740       return VariadicMethod;
5741     return VariadicFunction;
5742   }
5743   return VariadicDoesNotApply;
5744 }
5745 
5746 namespace {
5747 class FunctionCallCCC final : public FunctionCallFilterCCC {
5748 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)5749   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5750                   unsigned NumArgs, MemberExpr *ME)
5751       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5752         FunctionName(FuncName) {}
5753 
ValidateCandidate(const TypoCorrection & candidate)5754   bool ValidateCandidate(const TypoCorrection &candidate) override {
5755     if (!candidate.getCorrectionSpecifier() ||
5756         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5757       return false;
5758     }
5759 
5760     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5761   }
5762 
clone()5763   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5764     return std::make_unique<FunctionCallCCC>(*this);
5765   }
5766 
5767 private:
5768   const IdentifierInfo *const FunctionName;
5769 };
5770 }
5771 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)5772 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5773                                                FunctionDecl *FDecl,
5774                                                ArrayRef<Expr *> Args) {
5775   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5776   DeclarationName FuncName = FDecl->getDeclName();
5777   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5778 
5779   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5780   if (TypoCorrection Corrected = S.CorrectTypo(
5781           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5782           S.getScopeForContext(S.CurContext), nullptr, CCC,
5783           Sema::CTK_ErrorRecovery)) {
5784     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5785       if (Corrected.isOverloaded()) {
5786         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5787         OverloadCandidateSet::iterator Best;
5788         for (NamedDecl *CD : Corrected) {
5789           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5790             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5791                                    OCS);
5792         }
5793         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5794         case OR_Success:
5795           ND = Best->FoundDecl;
5796           Corrected.setCorrectionDecl(ND);
5797           break;
5798         default:
5799           break;
5800         }
5801       }
5802       ND = ND->getUnderlyingDecl();
5803       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5804         return Corrected;
5805     }
5806   }
5807   return TypoCorrection();
5808 }
5809 
5810 /// ConvertArgumentsForCall - Converts the arguments specified in
5811 /// Args/NumArgs to the parameter types of the function FDecl with
5812 /// function prototype Proto. Call is the call expression itself, and
5813 /// Fn is the function expression. For a C++ member function, this
5814 /// routine does not attempt to convert the object argument. Returns
5815 /// true if the call is ill-formed.
5816 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)5817 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5818                               FunctionDecl *FDecl,
5819                               const FunctionProtoType *Proto,
5820                               ArrayRef<Expr *> Args,
5821                               SourceLocation RParenLoc,
5822                               bool IsExecConfig) {
5823   // Bail out early if calling a builtin with custom typechecking.
5824   if (FDecl)
5825     if (unsigned ID = FDecl->getBuiltinID())
5826       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5827         return false;
5828 
5829   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5830   // assignment, to the types of the corresponding parameter, ...
5831   unsigned NumParams = Proto->getNumParams();
5832   bool Invalid = false;
5833   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5834   unsigned FnKind = Fn->getType()->isBlockPointerType()
5835                        ? 1 /* block */
5836                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5837                                        : 0 /* function */);
5838 
5839   // If too few arguments are available (and we don't have default
5840   // arguments for the remaining parameters), don't make the call.
5841   if (Args.size() < NumParams) {
5842     if (Args.size() < MinArgs) {
5843       TypoCorrection TC;
5844       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5845         unsigned diag_id =
5846             MinArgs == NumParams && !Proto->isVariadic()
5847                 ? diag::err_typecheck_call_too_few_args_suggest
5848                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5849         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5850                                         << static_cast<unsigned>(Args.size())
5851                                         << TC.getCorrectionRange());
5852       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5853         Diag(RParenLoc,
5854              MinArgs == NumParams && !Proto->isVariadic()
5855                  ? diag::err_typecheck_call_too_few_args_one
5856                  : diag::err_typecheck_call_too_few_args_at_least_one)
5857             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5858       else
5859         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5860                             ? diag::err_typecheck_call_too_few_args
5861                             : diag::err_typecheck_call_too_few_args_at_least)
5862             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5863             << Fn->getSourceRange();
5864 
5865       // Emit the location of the prototype.
5866       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5867         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5868 
5869       return true;
5870     }
5871     // We reserve space for the default arguments when we create
5872     // the call expression, before calling ConvertArgumentsForCall.
5873     assert((Call->getNumArgs() == NumParams) &&
5874            "We should have reserved space for the default arguments before!");
5875   }
5876 
5877   // If too many are passed and not variadic, error on the extras and drop
5878   // them.
5879   if (Args.size() > NumParams) {
5880     if (!Proto->isVariadic()) {
5881       TypoCorrection TC;
5882       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5883         unsigned diag_id =
5884             MinArgs == NumParams && !Proto->isVariadic()
5885                 ? diag::err_typecheck_call_too_many_args_suggest
5886                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5887         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5888                                         << static_cast<unsigned>(Args.size())
5889                                         << TC.getCorrectionRange());
5890       } else if (NumParams == 1 && FDecl &&
5891                  FDecl->getParamDecl(0)->getDeclName())
5892         Diag(Args[NumParams]->getBeginLoc(),
5893              MinArgs == NumParams
5894                  ? diag::err_typecheck_call_too_many_args_one
5895                  : diag::err_typecheck_call_too_many_args_at_most_one)
5896             << FnKind << FDecl->getParamDecl(0)
5897             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5898             << SourceRange(Args[NumParams]->getBeginLoc(),
5899                            Args.back()->getEndLoc());
5900       else
5901         Diag(Args[NumParams]->getBeginLoc(),
5902              MinArgs == NumParams
5903                  ? diag::err_typecheck_call_too_many_args
5904                  : diag::err_typecheck_call_too_many_args_at_most)
5905             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5906             << Fn->getSourceRange()
5907             << SourceRange(Args[NumParams]->getBeginLoc(),
5908                            Args.back()->getEndLoc());
5909 
5910       // Emit the location of the prototype.
5911       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5912         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5913 
5914       // This deletes the extra arguments.
5915       Call->shrinkNumArgs(NumParams);
5916       return true;
5917     }
5918   }
5919   SmallVector<Expr *, 8> AllArgs;
5920   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5921 
5922   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5923                                    AllArgs, CallType);
5924   if (Invalid)
5925     return true;
5926   unsigned TotalNumArgs = AllArgs.size();
5927   for (unsigned i = 0; i < TotalNumArgs; ++i)
5928     Call->setArg(i, AllArgs[i]);
5929 
5930   Call->computeDependence();
5931   return false;
5932 }
5933 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)5934 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5935                                   const FunctionProtoType *Proto,
5936                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5937                                   SmallVectorImpl<Expr *> &AllArgs,
5938                                   VariadicCallType CallType, bool AllowExplicit,
5939                                   bool IsListInitialization) {
5940   unsigned NumParams = Proto->getNumParams();
5941   bool Invalid = false;
5942   size_t ArgIx = 0;
5943   // Continue to check argument types (even if we have too few/many args).
5944   for (unsigned i = FirstParam; i < NumParams; i++) {
5945     QualType ProtoArgType = Proto->getParamType(i);
5946 
5947     Expr *Arg;
5948     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5949     if (ArgIx < Args.size()) {
5950       Arg = Args[ArgIx++];
5951 
5952       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5953                               diag::err_call_incomplete_argument, Arg))
5954         return true;
5955 
5956       // Strip the unbridged-cast placeholder expression off, if applicable.
5957       bool CFAudited = false;
5958       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5959           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5960           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5961         Arg = stripARCUnbridgedCast(Arg);
5962       else if (getLangOpts().ObjCAutoRefCount &&
5963                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5964                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5965         CFAudited = true;
5966 
5967       if (Proto->getExtParameterInfo(i).isNoEscape() &&
5968           ProtoArgType->isBlockPointerType())
5969         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5970           BE->getBlockDecl()->setDoesNotEscape();
5971 
5972       InitializedEntity Entity =
5973           Param ? InitializedEntity::InitializeParameter(Context, Param,
5974                                                          ProtoArgType)
5975                 : InitializedEntity::InitializeParameter(
5976                       Context, ProtoArgType, Proto->isParamConsumed(i));
5977 
5978       // Remember that parameter belongs to a CF audited API.
5979       if (CFAudited)
5980         Entity.setParameterCFAudited();
5981 
5982       ExprResult ArgE = PerformCopyInitialization(
5983           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5984       if (ArgE.isInvalid())
5985         return true;
5986 
5987       Arg = ArgE.getAs<Expr>();
5988     } else {
5989       assert(Param && "can't use default arguments without a known callee");
5990 
5991       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5992       if (ArgExpr.isInvalid())
5993         return true;
5994 
5995       Arg = ArgExpr.getAs<Expr>();
5996     }
5997 
5998     // Check for array bounds violations for each argument to the call. This
5999     // check only triggers warnings when the argument isn't a more complex Expr
6000     // with its own checking, such as a BinaryOperator.
6001     CheckArrayAccess(Arg);
6002 
6003     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6004     CheckStaticArrayArgument(CallLoc, Param, Arg);
6005 
6006     AllArgs.push_back(Arg);
6007   }
6008 
6009   // If this is a variadic call, handle args passed through "...".
6010   if (CallType != VariadicDoesNotApply) {
6011     // Assume that extern "C" functions with variadic arguments that
6012     // return __unknown_anytype aren't *really* variadic.
6013     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6014         FDecl->isExternC()) {
6015       for (Expr *A : Args.slice(ArgIx)) {
6016         QualType paramType; // ignored
6017         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6018         Invalid |= arg.isInvalid();
6019         AllArgs.push_back(arg.get());
6020       }
6021 
6022     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6023     } else {
6024       for (Expr *A : Args.slice(ArgIx)) {
6025         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6026         Invalid |= Arg.isInvalid();
6027         AllArgs.push_back(Arg.get());
6028       }
6029     }
6030 
6031     // Check for array bounds violations.
6032     for (Expr *A : Args.slice(ArgIx))
6033       CheckArrayAccess(A);
6034   }
6035   return Invalid;
6036 }
6037 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)6038 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6039   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6040   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6041     TL = DTL.getOriginalLoc();
6042   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6043     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6044       << ATL.getLocalSourceRange();
6045 }
6046 
6047 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6048 /// array parameter, check that it is non-null, and that if it is formed by
6049 /// array-to-pointer decay, the underlying array is sufficiently large.
6050 ///
6051 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6052 /// array type derivation, then for each call to the function, the value of the
6053 /// corresponding actual argument shall provide access to the first element of
6054 /// an array with at least as many elements as specified by the size expression.
6055 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)6056 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6057                                ParmVarDecl *Param,
6058                                const Expr *ArgExpr) {
6059   // Static array parameters are not supported in C++.
6060   if (!Param || getLangOpts().CPlusPlus)
6061     return;
6062 
6063   QualType OrigTy = Param->getOriginalType();
6064 
6065   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6066   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6067     return;
6068 
6069   if (ArgExpr->isNullPointerConstant(Context,
6070                                      Expr::NPC_NeverValueDependent)) {
6071     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6072     DiagnoseCalleeStaticArrayParam(*this, Param);
6073     return;
6074   }
6075 
6076   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6077   if (!CAT)
6078     return;
6079 
6080   const ConstantArrayType *ArgCAT =
6081     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6082   if (!ArgCAT)
6083     return;
6084 
6085   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6086                                              ArgCAT->getElementType())) {
6087     if (ArgCAT->getSize().ult(CAT->getSize())) {
6088       Diag(CallLoc, diag::warn_static_array_too_small)
6089           << ArgExpr->getSourceRange()
6090           << (unsigned)ArgCAT->getSize().getZExtValue()
6091           << (unsigned)CAT->getSize().getZExtValue() << 0;
6092       DiagnoseCalleeStaticArrayParam(*this, Param);
6093     }
6094     return;
6095   }
6096 
6097   Optional<CharUnits> ArgSize =
6098       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6099   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6100   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6101     Diag(CallLoc, diag::warn_static_array_too_small)
6102         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6103         << (unsigned)ParmSize->getQuantity() << 1;
6104     DiagnoseCalleeStaticArrayParam(*this, Param);
6105   }
6106 }
6107 
6108 /// Given a function expression of unknown-any type, try to rebuild it
6109 /// to have a function type.
6110 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6111 
6112 /// Is the given type a placeholder that we need to lower out
6113 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)6114 static bool isPlaceholderToRemoveAsArg(QualType type) {
6115   // Placeholders are never sugared.
6116   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6117   if (!placeholder) return false;
6118 
6119   switch (placeholder->getKind()) {
6120   // Ignore all the non-placeholder types.
6121 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6122   case BuiltinType::Id:
6123 #include "clang/Basic/OpenCLImageTypes.def"
6124 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6125   case BuiltinType::Id:
6126 #include "clang/Basic/OpenCLExtensionTypes.def"
6127   // In practice we'll never use this, since all SVE types are sugared
6128   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6129 #define SVE_TYPE(Name, Id, SingletonId) \
6130   case BuiltinType::Id:
6131 #include "clang/Basic/AArch64SVEACLETypes.def"
6132 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6133   case BuiltinType::Id:
6134 #include "clang/Basic/PPCTypes.def"
6135 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6136 #include "clang/Basic/RISCVVTypes.def"
6137 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6138 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6139 #include "clang/AST/BuiltinTypes.def"
6140     return false;
6141 
6142   // We cannot lower out overload sets; they might validly be resolved
6143   // by the call machinery.
6144   case BuiltinType::Overload:
6145     return false;
6146 
6147   // Unbridged casts in ARC can be handled in some call positions and
6148   // should be left in place.
6149   case BuiltinType::ARCUnbridgedCast:
6150     return false;
6151 
6152   // Pseudo-objects should be converted as soon as possible.
6153   case BuiltinType::PseudoObject:
6154     return true;
6155 
6156   // The debugger mode could theoretically but currently does not try
6157   // to resolve unknown-typed arguments based on known parameter types.
6158   case BuiltinType::UnknownAny:
6159     return true;
6160 
6161   // These are always invalid as call arguments and should be reported.
6162   case BuiltinType::BoundMember:
6163   case BuiltinType::BuiltinFn:
6164   case BuiltinType::IncompleteMatrixIdx:
6165   case BuiltinType::OMPArraySection:
6166   case BuiltinType::OMPArrayShaping:
6167   case BuiltinType::OMPIterator:
6168     return true;
6169 
6170   }
6171   llvm_unreachable("bad builtin type kind");
6172 }
6173 
6174 /// Check an argument list for placeholders that we won't try to
6175 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)6176 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6177   // Apply this processing to all the arguments at once instead of
6178   // dying at the first failure.
6179   bool hasInvalid = false;
6180   for (size_t i = 0, e = args.size(); i != e; i++) {
6181     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6182       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6183       if (result.isInvalid()) hasInvalid = true;
6184       else args[i] = result.get();
6185     }
6186   }
6187   return hasInvalid;
6188 }
6189 
6190 /// If a builtin function has a pointer argument with no explicit address
6191 /// space, then it should be able to accept a pointer to any address
6192 /// space as input.  In order to do this, we need to replace the
6193 /// standard builtin declaration with one that uses the same address space
6194 /// as the call.
6195 ///
6196 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6197 ///                  it does not contain any pointer arguments without
6198 ///                  an address space qualifer.  Otherwise the rewritten
6199 ///                  FunctionDecl is returned.
6200 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,FunctionDecl * FDecl,MultiExprArg ArgExprs)6201 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6202                                                 FunctionDecl *FDecl,
6203                                                 MultiExprArg ArgExprs) {
6204 
6205   QualType DeclType = FDecl->getType();
6206   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6207 
6208   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6209       ArgExprs.size() < FT->getNumParams())
6210     return nullptr;
6211 
6212   bool NeedsNewDecl = false;
6213   unsigned i = 0;
6214   SmallVector<QualType, 8> OverloadParams;
6215 
6216   for (QualType ParamType : FT->param_types()) {
6217 
6218     // Convert array arguments to pointer to simplify type lookup.
6219     ExprResult ArgRes =
6220         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6221     if (ArgRes.isInvalid())
6222       return nullptr;
6223     Expr *Arg = ArgRes.get();
6224     QualType ArgType = Arg->getType();
6225     if (!ParamType->isPointerType() ||
6226         ParamType.hasAddressSpace() ||
6227         !ArgType->isPointerType() ||
6228         !ArgType->getPointeeType().hasAddressSpace()) {
6229       OverloadParams.push_back(ParamType);
6230       continue;
6231     }
6232 
6233     QualType PointeeType = ParamType->getPointeeType();
6234     if (PointeeType.hasAddressSpace())
6235       continue;
6236 
6237     NeedsNewDecl = true;
6238     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6239 
6240     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6241     OverloadParams.push_back(Context.getPointerType(PointeeType));
6242   }
6243 
6244   if (!NeedsNewDecl)
6245     return nullptr;
6246 
6247   FunctionProtoType::ExtProtoInfo EPI;
6248   EPI.Variadic = FT->isVariadic();
6249   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6250                                                 OverloadParams, EPI);
6251   DeclContext *Parent = FDecl->getParent();
6252   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6253                                                     FDecl->getLocation(),
6254                                                     FDecl->getLocation(),
6255                                                     FDecl->getIdentifier(),
6256                                                     OverloadTy,
6257                                                     /*TInfo=*/nullptr,
6258                                                     SC_Extern, false,
6259                                                     /*hasPrototype=*/true);
6260   SmallVector<ParmVarDecl*, 16> Params;
6261   FT = cast<FunctionProtoType>(OverloadTy);
6262   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6263     QualType ParamType = FT->getParamType(i);
6264     ParmVarDecl *Parm =
6265         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6266                                 SourceLocation(), nullptr, ParamType,
6267                                 /*TInfo=*/nullptr, SC_None, nullptr);
6268     Parm->setScopeInfo(0, i);
6269     Params.push_back(Parm);
6270   }
6271   OverloadDecl->setParams(Params);
6272   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6273   return OverloadDecl;
6274 }
6275 
checkDirectCallValidity(Sema & S,const Expr * Fn,FunctionDecl * Callee,MultiExprArg ArgExprs)6276 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6277                                     FunctionDecl *Callee,
6278                                     MultiExprArg ArgExprs) {
6279   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6280   // similar attributes) really don't like it when functions are called with an
6281   // invalid number of args.
6282   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6283                          /*PartialOverloading=*/false) &&
6284       !Callee->isVariadic())
6285     return;
6286   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6287     return;
6288 
6289   if (const EnableIfAttr *Attr =
6290           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6291     S.Diag(Fn->getBeginLoc(),
6292            isa<CXXMethodDecl>(Callee)
6293                ? diag::err_ovl_no_viable_member_function_in_call
6294                : diag::err_ovl_no_viable_function_in_call)
6295         << Callee << Callee->getSourceRange();
6296     S.Diag(Callee->getLocation(),
6297            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6298         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6299     return;
6300   }
6301 }
6302 
enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr * const UME,Sema & S)6303 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6304     const UnresolvedMemberExpr *const UME, Sema &S) {
6305 
6306   const auto GetFunctionLevelDCIfCXXClass =
6307       [](Sema &S) -> const CXXRecordDecl * {
6308     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6309     if (!DC || !DC->getParent())
6310       return nullptr;
6311 
6312     // If the call to some member function was made from within a member
6313     // function body 'M' return return 'M's parent.
6314     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6315       return MD->getParent()->getCanonicalDecl();
6316     // else the call was made from within a default member initializer of a
6317     // class, so return the class.
6318     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6319       return RD->getCanonicalDecl();
6320     return nullptr;
6321   };
6322   // If our DeclContext is neither a member function nor a class (in the
6323   // case of a lambda in a default member initializer), we can't have an
6324   // enclosing 'this'.
6325 
6326   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6327   if (!CurParentClass)
6328     return false;
6329 
6330   // The naming class for implicit member functions call is the class in which
6331   // name lookup starts.
6332   const CXXRecordDecl *const NamingClass =
6333       UME->getNamingClass()->getCanonicalDecl();
6334   assert(NamingClass && "Must have naming class even for implicit access");
6335 
6336   // If the unresolved member functions were found in a 'naming class' that is
6337   // related (either the same or derived from) to the class that contains the
6338   // member function that itself contained the implicit member access.
6339 
6340   return CurParentClass == NamingClass ||
6341          CurParentClass->isDerivedFrom(NamingClass);
6342 }
6343 
6344 static void
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema & S,const UnresolvedMemberExpr * const UME,SourceLocation CallLoc)6345 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6346     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6347 
6348   if (!UME)
6349     return;
6350 
6351   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6352   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6353   // already been captured, or if this is an implicit member function call (if
6354   // it isn't, an attempt to capture 'this' should already have been made).
6355   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6356       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6357     return;
6358 
6359   // Check if the naming class in which the unresolved members were found is
6360   // related (same as or is a base of) to the enclosing class.
6361 
6362   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6363     return;
6364 
6365 
6366   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6367   // If the enclosing function is not dependent, then this lambda is
6368   // capture ready, so if we can capture this, do so.
6369   if (!EnclosingFunctionCtx->isDependentContext()) {
6370     // If the current lambda and all enclosing lambdas can capture 'this' -
6371     // then go ahead and capture 'this' (since our unresolved overload set
6372     // contains at least one non-static member function).
6373     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6374       S.CheckCXXThisCapture(CallLoc);
6375   } else if (S.CurContext->isDependentContext()) {
6376     // ... since this is an implicit member reference, that might potentially
6377     // involve a 'this' capture, mark 'this' for potential capture in
6378     // enclosing lambdas.
6379     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6380       CurLSI->addPotentialThisCapture(CallLoc);
6381   }
6382 }
6383 
ActOnCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig)6384 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6385                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6386                                Expr *ExecConfig) {
6387   ExprResult Call =
6388       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6389                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6390   if (Call.isInvalid())
6391     return Call;
6392 
6393   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6394   // language modes.
6395   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6396     if (ULE->hasExplicitTemplateArgs() &&
6397         ULE->decls_begin() == ULE->decls_end()) {
6398       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6399                                  ? diag::warn_cxx17_compat_adl_only_template_id
6400                                  : diag::ext_adl_only_template_id)
6401           << ULE->getName();
6402     }
6403   }
6404 
6405   if (LangOpts.OpenMP)
6406     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6407                            ExecConfig);
6408 
6409   return Call;
6410 }
6411 
6412 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6413 /// This provides the location of the left/right parens and a list of comma
6414 /// locations.
BuildCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig,bool AllowRecovery)6415 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6416                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6417                                Expr *ExecConfig, bool IsExecConfig,
6418                                bool AllowRecovery) {
6419   // Since this might be a postfix expression, get rid of ParenListExprs.
6420   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6421   if (Result.isInvalid()) return ExprError();
6422   Fn = Result.get();
6423 
6424   if (checkArgsForPlaceholders(*this, ArgExprs))
6425     return ExprError();
6426 
6427   if (getLangOpts().CPlusPlus) {
6428     // If this is a pseudo-destructor expression, build the call immediately.
6429     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6430       if (!ArgExprs.empty()) {
6431         // Pseudo-destructor calls should not have any arguments.
6432         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6433             << FixItHint::CreateRemoval(
6434                    SourceRange(ArgExprs.front()->getBeginLoc(),
6435                                ArgExprs.back()->getEndLoc()));
6436       }
6437 
6438       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6439                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6440     }
6441     if (Fn->getType() == Context.PseudoObjectTy) {
6442       ExprResult result = CheckPlaceholderExpr(Fn);
6443       if (result.isInvalid()) return ExprError();
6444       Fn = result.get();
6445     }
6446 
6447     // Determine whether this is a dependent call inside a C++ template,
6448     // in which case we won't do any semantic analysis now.
6449     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6450       if (ExecConfig) {
6451         return CUDAKernelCallExpr::Create(Context, Fn,
6452                                           cast<CallExpr>(ExecConfig), ArgExprs,
6453                                           Context.DependentTy, VK_PRValue,
6454                                           RParenLoc, CurFPFeatureOverrides());
6455       } else {
6456 
6457         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6458             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6459             Fn->getBeginLoc());
6460 
6461         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6462                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6463       }
6464     }
6465 
6466     // Determine whether this is a call to an object (C++ [over.call.object]).
6467     if (Fn->getType()->isRecordType())
6468       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6469                                           RParenLoc);
6470 
6471     if (Fn->getType() == Context.UnknownAnyTy) {
6472       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6473       if (result.isInvalid()) return ExprError();
6474       Fn = result.get();
6475     }
6476 
6477     if (Fn->getType() == Context.BoundMemberTy) {
6478       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6479                                        RParenLoc, AllowRecovery);
6480     }
6481   }
6482 
6483   // Check for overloaded calls.  This can happen even in C due to extensions.
6484   if (Fn->getType() == Context.OverloadTy) {
6485     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6486 
6487     // We aren't supposed to apply this logic if there's an '&' involved.
6488     if (!find.HasFormOfMemberPointer) {
6489       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6490         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6491                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6492       OverloadExpr *ovl = find.Expression;
6493       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6494         return BuildOverloadedCallExpr(
6495             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6496             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6497       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6498                                        RParenLoc, AllowRecovery);
6499     }
6500   }
6501 
6502   // If we're directly calling a function, get the appropriate declaration.
6503   if (Fn->getType() == Context.UnknownAnyTy) {
6504     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6505     if (result.isInvalid()) return ExprError();
6506     Fn = result.get();
6507   }
6508 
6509   Expr *NakedFn = Fn->IgnoreParens();
6510 
6511   bool CallingNDeclIndirectly = false;
6512   NamedDecl *NDecl = nullptr;
6513   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6514     if (UnOp->getOpcode() == UO_AddrOf) {
6515       CallingNDeclIndirectly = true;
6516       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6517     }
6518   }
6519 
6520   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6521     NDecl = DRE->getDecl();
6522 
6523     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6524     if (FDecl && FDecl->getBuiltinID()) {
6525       // Rewrite the function decl for this builtin by replacing parameters
6526       // with no explicit address space with the address space of the arguments
6527       // in ArgExprs.
6528       if ((FDecl =
6529                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6530         NDecl = FDecl;
6531         Fn = DeclRefExpr::Create(
6532             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6533             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6534             nullptr, DRE->isNonOdrUse());
6535       }
6536     }
6537   } else if (isa<MemberExpr>(NakedFn))
6538     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6539 
6540   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6541     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6542                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6543       return ExprError();
6544 
6545     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6546   }
6547 
6548   if (Context.isDependenceAllowed() &&
6549       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6550     assert(!getLangOpts().CPlusPlus);
6551     assert((Fn->containsErrors() ||
6552             llvm::any_of(ArgExprs,
6553                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6554            "should only occur in error-recovery path.");
6555     QualType ReturnType =
6556         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6557             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6558             : Context.DependentTy;
6559     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6560                             Expr::getValueKindForType(ReturnType), RParenLoc,
6561                             CurFPFeatureOverrides());
6562   }
6563   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6564                                ExecConfig, IsExecConfig);
6565 }
6566 
6567 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6568 //  with the specified CallArgs
BuildBuiltinCallExpr(SourceLocation Loc,Builtin::ID Id,MultiExprArg CallArgs)6569 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6570                                  MultiExprArg CallArgs) {
6571   StringRef Name = Context.BuiltinInfo.getName(Id);
6572   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6573                  Sema::LookupOrdinaryName);
6574   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6575 
6576   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6577   assert(BuiltInDecl && "failed to find builtin declaration");
6578 
6579   ExprResult DeclRef =
6580       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6581   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6582 
6583   ExprResult Call =
6584       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6585 
6586   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6587   return Call.get();
6588 }
6589 
6590 /// Parse a __builtin_astype expression.
6591 ///
6592 /// __builtin_astype( value, dst type )
6593 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6594 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6595                                  SourceLocation BuiltinLoc,
6596                                  SourceLocation RParenLoc) {
6597   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6598   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6599 }
6600 
6601 /// Create a new AsTypeExpr node (bitcast) from the arguments.
BuildAsTypeExpr(Expr * E,QualType DestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6602 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6603                                  SourceLocation BuiltinLoc,
6604                                  SourceLocation RParenLoc) {
6605   ExprValueKind VK = VK_PRValue;
6606   ExprObjectKind OK = OK_Ordinary;
6607   QualType SrcTy = E->getType();
6608   if (!SrcTy->isDependentType() &&
6609       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6610     return ExprError(
6611         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6612         << DestTy << SrcTy << E->getSourceRange());
6613   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6614 }
6615 
6616 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6617 /// provided arguments.
6618 ///
6619 /// __builtin_convertvector( value, dst type )
6620 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6621 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6622                                         SourceLocation BuiltinLoc,
6623                                         SourceLocation RParenLoc) {
6624   TypeSourceInfo *TInfo;
6625   GetTypeFromParser(ParsedDestTy, &TInfo);
6626   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6627 }
6628 
6629 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6630 /// i.e. an expression not of \p OverloadTy.  The expression should
6631 /// unary-convert to an expression of function-pointer or
6632 /// block-pointer type.
6633 ///
6634 /// \param NDecl the declaration being called, if available
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig,ADLCallKind UsesADL)6635 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6636                                        SourceLocation LParenLoc,
6637                                        ArrayRef<Expr *> Args,
6638                                        SourceLocation RParenLoc, Expr *Config,
6639                                        bool IsExecConfig, ADLCallKind UsesADL) {
6640   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6641   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6642 
6643   // Functions with 'interrupt' attribute cannot be called directly.
6644   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6645     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6646     return ExprError();
6647   }
6648 
6649   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6650   // so there's some risk when calling out to non-interrupt handler functions
6651   // that the callee might not preserve them. This is easy to diagnose here,
6652   // but can be very challenging to debug.
6653   // Likewise, X86 interrupt handlers may only call routines with attribute
6654   // no_caller_saved_registers since there is no efficient way to
6655   // save and restore the non-GPR state.
6656   if (auto *Caller = getCurFunctionDecl()) {
6657     if (Caller->hasAttr<ARMInterruptAttr>()) {
6658       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6659       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6660         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6661         if (FDecl)
6662           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6663       }
6664     }
6665     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6666         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6667       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6668       if (FDecl)
6669         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6670     }
6671   }
6672 
6673   // Promote the function operand.
6674   // We special-case function promotion here because we only allow promoting
6675   // builtin functions to function pointers in the callee of a call.
6676   ExprResult Result;
6677   QualType ResultTy;
6678   if (BuiltinID &&
6679       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6680     // Extract the return type from the (builtin) function pointer type.
6681     // FIXME Several builtins still have setType in
6682     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6683     // Builtins.def to ensure they are correct before removing setType calls.
6684     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6685     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6686     ResultTy = FDecl->getCallResultType();
6687   } else {
6688     Result = CallExprUnaryConversions(Fn);
6689     ResultTy = Context.BoolTy;
6690   }
6691   if (Result.isInvalid())
6692     return ExprError();
6693   Fn = Result.get();
6694 
6695   // Check for a valid function type, but only if it is not a builtin which
6696   // requires custom type checking. These will be handled by
6697   // CheckBuiltinFunctionCall below just after creation of the call expression.
6698   const FunctionType *FuncT = nullptr;
6699   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6700   retry:
6701     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6702       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6703       // have type pointer to function".
6704       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6705       if (!FuncT)
6706         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6707                          << Fn->getType() << Fn->getSourceRange());
6708     } else if (const BlockPointerType *BPT =
6709                    Fn->getType()->getAs<BlockPointerType>()) {
6710       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6711     } else {
6712       // Handle calls to expressions of unknown-any type.
6713       if (Fn->getType() == Context.UnknownAnyTy) {
6714         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6715         if (rewrite.isInvalid())
6716           return ExprError();
6717         Fn = rewrite.get();
6718         goto retry;
6719       }
6720 
6721       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6722                        << Fn->getType() << Fn->getSourceRange());
6723     }
6724   }
6725 
6726   // Get the number of parameters in the function prototype, if any.
6727   // We will allocate space for max(Args.size(), NumParams) arguments
6728   // in the call expression.
6729   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6730   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6731 
6732   CallExpr *TheCall;
6733   if (Config) {
6734     assert(UsesADL == ADLCallKind::NotADL &&
6735            "CUDAKernelCallExpr should not use ADL");
6736     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6737                                          Args, ResultTy, VK_PRValue, RParenLoc,
6738                                          CurFPFeatureOverrides(), NumParams);
6739   } else {
6740     TheCall =
6741         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6742                          CurFPFeatureOverrides(), NumParams, UsesADL);
6743   }
6744 
6745   if (!Context.isDependenceAllowed()) {
6746     // Forget about the nulled arguments since typo correction
6747     // do not handle them well.
6748     TheCall->shrinkNumArgs(Args.size());
6749     // C cannot always handle TypoExpr nodes in builtin calls and direct
6750     // function calls as their argument checking don't necessarily handle
6751     // dependent types properly, so make sure any TypoExprs have been
6752     // dealt with.
6753     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6754     if (!Result.isUsable()) return ExprError();
6755     CallExpr *TheOldCall = TheCall;
6756     TheCall = dyn_cast<CallExpr>(Result.get());
6757     bool CorrectedTypos = TheCall != TheOldCall;
6758     if (!TheCall) return Result;
6759     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6760 
6761     // A new call expression node was created if some typos were corrected.
6762     // However it may not have been constructed with enough storage. In this
6763     // case, rebuild the node with enough storage. The waste of space is
6764     // immaterial since this only happens when some typos were corrected.
6765     if (CorrectedTypos && Args.size() < NumParams) {
6766       if (Config)
6767         TheCall = CUDAKernelCallExpr::Create(
6768             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6769             RParenLoc, CurFPFeatureOverrides(), NumParams);
6770       else
6771         TheCall =
6772             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6773                              CurFPFeatureOverrides(), NumParams, UsesADL);
6774     }
6775     // We can now handle the nulled arguments for the default arguments.
6776     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6777   }
6778 
6779   // Bail out early if calling a builtin with custom type checking.
6780   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6781     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6782 
6783   if (getLangOpts().CUDA) {
6784     if (Config) {
6785       // CUDA: Kernel calls must be to global functions
6786       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6787         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6788             << FDecl << Fn->getSourceRange());
6789 
6790       // CUDA: Kernel function must have 'void' return type
6791       if (!FuncT->getReturnType()->isVoidType() &&
6792           !FuncT->getReturnType()->getAs<AutoType>() &&
6793           !FuncT->getReturnType()->isInstantiationDependentType())
6794         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6795             << Fn->getType() << Fn->getSourceRange());
6796     } else {
6797       // CUDA: Calls to global functions must be configured
6798       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6799         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6800             << FDecl << Fn->getSourceRange());
6801     }
6802   }
6803 
6804   // Check for a valid return type
6805   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6806                           FDecl))
6807     return ExprError();
6808 
6809   // We know the result type of the call, set it.
6810   TheCall->setType(FuncT->getCallResultType(Context));
6811   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6812 
6813   if (Proto) {
6814     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6815                                 IsExecConfig))
6816       return ExprError();
6817   } else {
6818     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6819 
6820     if (FDecl) {
6821       // Check if we have too few/too many template arguments, based
6822       // on our knowledge of the function definition.
6823       const FunctionDecl *Def = nullptr;
6824       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6825         Proto = Def->getType()->getAs<FunctionProtoType>();
6826        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6827           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6828           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6829       }
6830 
6831       // If the function we're calling isn't a function prototype, but we have
6832       // a function prototype from a prior declaratiom, use that prototype.
6833       if (!FDecl->hasPrototype())
6834         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6835     }
6836 
6837     // Promote the arguments (C99 6.5.2.2p6).
6838     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6839       Expr *Arg = Args[i];
6840 
6841       if (Proto && i < Proto->getNumParams()) {
6842         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6843             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6844         ExprResult ArgE =
6845             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6846         if (ArgE.isInvalid())
6847           return true;
6848 
6849         Arg = ArgE.getAs<Expr>();
6850 
6851       } else {
6852         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6853 
6854         if (ArgE.isInvalid())
6855           return true;
6856 
6857         Arg = ArgE.getAs<Expr>();
6858       }
6859 
6860       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6861                               diag::err_call_incomplete_argument, Arg))
6862         return ExprError();
6863 
6864       TheCall->setArg(i, Arg);
6865     }
6866     TheCall->computeDependence();
6867   }
6868 
6869   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6870     if (!Method->isStatic())
6871       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6872         << Fn->getSourceRange());
6873 
6874   // Check for sentinels
6875   if (NDecl)
6876     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6877 
6878   // Warn for unions passing across security boundary (CMSE).
6879   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6880     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6881       if (const auto *RT =
6882               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6883         if (RT->getDecl()->isOrContainsUnion())
6884           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6885               << 0 << i;
6886       }
6887     }
6888   }
6889 
6890   // Do special checking on direct calls to functions.
6891   if (FDecl) {
6892     if (CheckFunctionCall(FDecl, TheCall, Proto))
6893       return ExprError();
6894 
6895     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6896 
6897     if (BuiltinID)
6898       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6899   } else if (NDecl) {
6900     if (CheckPointerCall(NDecl, TheCall, Proto))
6901       return ExprError();
6902   } else {
6903     if (CheckOtherCall(TheCall, Proto))
6904       return ExprError();
6905   }
6906 
6907   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6908 }
6909 
6910 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)6911 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6912                            SourceLocation RParenLoc, Expr *InitExpr) {
6913   assert(Ty && "ActOnCompoundLiteral(): missing type");
6914   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6915 
6916   TypeSourceInfo *TInfo;
6917   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6918   if (!TInfo)
6919     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6920 
6921   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6922 }
6923 
6924 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)6925 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6926                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6927   QualType literalType = TInfo->getType();
6928 
6929   if (literalType->isArrayType()) {
6930     if (RequireCompleteSizedType(
6931             LParenLoc, Context.getBaseElementType(literalType),
6932             diag::err_array_incomplete_or_sizeless_type,
6933             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6934       return ExprError();
6935     if (literalType->isVariableArrayType()) {
6936       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6937                                            diag::err_variable_object_no_init)) {
6938         return ExprError();
6939       }
6940     }
6941   } else if (!literalType->isDependentType() &&
6942              RequireCompleteType(LParenLoc, literalType,
6943                diag::err_typecheck_decl_incomplete_type,
6944                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6945     return ExprError();
6946 
6947   InitializedEntity Entity
6948     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6949   InitializationKind Kind
6950     = InitializationKind::CreateCStyleCast(LParenLoc,
6951                                            SourceRange(LParenLoc, RParenLoc),
6952                                            /*InitList=*/true);
6953   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6954   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6955                                       &literalType);
6956   if (Result.isInvalid())
6957     return ExprError();
6958   LiteralExpr = Result.get();
6959 
6960   bool isFileScope = !CurContext->isFunctionOrMethod();
6961 
6962   // In C, compound literals are l-values for some reason.
6963   // For GCC compatibility, in C++, file-scope array compound literals with
6964   // constant initializers are also l-values, and compound literals are
6965   // otherwise prvalues.
6966   //
6967   // (GCC also treats C++ list-initialized file-scope array prvalues with
6968   // constant initializers as l-values, but that's non-conforming, so we don't
6969   // follow it there.)
6970   //
6971   // FIXME: It would be better to handle the lvalue cases as materializing and
6972   // lifetime-extending a temporary object, but our materialized temporaries
6973   // representation only supports lifetime extension from a variable, not "out
6974   // of thin air".
6975   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6976   // is bound to the result of applying array-to-pointer decay to the compound
6977   // literal.
6978   // FIXME: GCC supports compound literals of reference type, which should
6979   // obviously have a value kind derived from the kind of reference involved.
6980   ExprValueKind VK =
6981       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6982           ? VK_PRValue
6983           : VK_LValue;
6984 
6985   if (isFileScope)
6986     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6987       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6988         Expr *Init = ILE->getInit(i);
6989         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6990       }
6991 
6992   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6993                                               VK, LiteralExpr, isFileScope);
6994   if (isFileScope) {
6995     if (!LiteralExpr->isTypeDependent() &&
6996         !LiteralExpr->isValueDependent() &&
6997         !literalType->isDependentType()) // C99 6.5.2.5p3
6998       if (CheckForConstantInitializer(LiteralExpr, literalType))
6999         return ExprError();
7000   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7001              literalType.getAddressSpace() != LangAS::Default) {
7002     // Embedded-C extensions to C99 6.5.2.5:
7003     //   "If the compound literal occurs inside the body of a function, the
7004     //   type name shall not be qualified by an address-space qualifier."
7005     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7006       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7007     return ExprError();
7008   }
7009 
7010   if (!isFileScope && !getLangOpts().CPlusPlus) {
7011     // Compound literals that have automatic storage duration are destroyed at
7012     // the end of the scope in C; in C++, they're just temporaries.
7013 
7014     // Emit diagnostics if it is or contains a C union type that is non-trivial
7015     // to destruct.
7016     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7017       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7018                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7019 
7020     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7021     if (literalType.isDestructedType()) {
7022       Cleanup.setExprNeedsCleanups(true);
7023       ExprCleanupObjects.push_back(E);
7024       getCurFunction()->setHasBranchProtectedScope();
7025     }
7026   }
7027 
7028   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7029       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7030     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7031                                        E->getInitializer()->getExprLoc());
7032 
7033   return MaybeBindToTemporary(E);
7034 }
7035 
7036 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)7037 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7038                     SourceLocation RBraceLoc) {
7039   // Only produce each kind of designated initialization diagnostic once.
7040   SourceLocation FirstDesignator;
7041   bool DiagnosedArrayDesignator = false;
7042   bool DiagnosedNestedDesignator = false;
7043   bool DiagnosedMixedDesignator = false;
7044 
7045   // Check that any designated initializers are syntactically valid in the
7046   // current language mode.
7047   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7048     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7049       if (FirstDesignator.isInvalid())
7050         FirstDesignator = DIE->getBeginLoc();
7051 
7052       if (!getLangOpts().CPlusPlus)
7053         break;
7054 
7055       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7056         DiagnosedNestedDesignator = true;
7057         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7058           << DIE->getDesignatorsSourceRange();
7059       }
7060 
7061       for (auto &Desig : DIE->designators()) {
7062         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7063           DiagnosedArrayDesignator = true;
7064           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7065             << Desig.getSourceRange();
7066         }
7067       }
7068 
7069       if (!DiagnosedMixedDesignator &&
7070           !isa<DesignatedInitExpr>(InitArgList[0])) {
7071         DiagnosedMixedDesignator = true;
7072         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7073           << DIE->getSourceRange();
7074         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7075           << InitArgList[0]->getSourceRange();
7076       }
7077     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7078                isa<DesignatedInitExpr>(InitArgList[0])) {
7079       DiagnosedMixedDesignator = true;
7080       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7081       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7082         << DIE->getSourceRange();
7083       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7084         << InitArgList[I]->getSourceRange();
7085     }
7086   }
7087 
7088   if (FirstDesignator.isValid()) {
7089     // Only diagnose designated initiaization as a C++20 extension if we didn't
7090     // already diagnose use of (non-C++20) C99 designator syntax.
7091     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7092         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7093       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7094                                 ? diag::warn_cxx17_compat_designated_init
7095                                 : diag::ext_cxx_designated_init);
7096     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7097       Diag(FirstDesignator, diag::ext_designated_init);
7098     }
7099   }
7100 
7101   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7102 }
7103 
7104 ExprResult
BuildInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)7105 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7106                     SourceLocation RBraceLoc) {
7107   // Semantic analysis for initializers is done by ActOnDeclarator() and
7108   // CheckInitializer() - it requires knowledge of the object being initialized.
7109 
7110   // Immediately handle non-overload placeholders.  Overloads can be
7111   // resolved contextually, but everything else here can't.
7112   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7113     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7114       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7115 
7116       // Ignore failures; dropping the entire initializer list because
7117       // of one failure would be terrible for indexing/etc.
7118       if (result.isInvalid()) continue;
7119 
7120       InitArgList[I] = result.get();
7121     }
7122   }
7123 
7124   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7125                                                RBraceLoc);
7126   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7127   return E;
7128 }
7129 
7130 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)7131 void Sema::maybeExtendBlockObject(ExprResult &E) {
7132   assert(E.get()->getType()->isBlockPointerType());
7133   assert(E.get()->isPRValue());
7134 
7135   // Only do this in an r-value context.
7136   if (!getLangOpts().ObjCAutoRefCount) return;
7137 
7138   E = ImplicitCastExpr::Create(
7139       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7140       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7141   Cleanup.setExprNeedsCleanups(true);
7142 }
7143 
7144 /// Prepare a conversion of the given expression to an ObjC object
7145 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)7146 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7147   QualType type = E.get()->getType();
7148   if (type->isObjCObjectPointerType()) {
7149     return CK_BitCast;
7150   } else if (type->isBlockPointerType()) {
7151     maybeExtendBlockObject(E);
7152     return CK_BlockPointerToObjCPointerCast;
7153   } else {
7154     assert(type->isPointerType());
7155     return CK_CPointerToObjCPointerCast;
7156   }
7157 }
7158 
7159 /// Prepares for a scalar cast, performing all the necessary stages
7160 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)7161 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7162   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7163   // Also, callers should have filtered out the invalid cases with
7164   // pointers.  Everything else should be possible.
7165 
7166   QualType SrcTy = Src.get()->getType();
7167   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7168     return CK_NoOp;
7169 
7170   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7171   case Type::STK_MemberPointer:
7172     llvm_unreachable("member pointer type in C");
7173 
7174   case Type::STK_CPointer:
7175   case Type::STK_BlockPointer:
7176   case Type::STK_ObjCObjectPointer:
7177     switch (DestTy->getScalarTypeKind()) {
7178     case Type::STK_CPointer: {
7179       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7180       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7181       if (SrcAS != DestAS)
7182         return CK_AddressSpaceConversion;
7183       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7184         return CK_NoOp;
7185       return CK_BitCast;
7186     }
7187     case Type::STK_BlockPointer:
7188       return (SrcKind == Type::STK_BlockPointer
7189                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7190     case Type::STK_ObjCObjectPointer:
7191       if (SrcKind == Type::STK_ObjCObjectPointer)
7192         return CK_BitCast;
7193       if (SrcKind == Type::STK_CPointer)
7194         return CK_CPointerToObjCPointerCast;
7195       maybeExtendBlockObject(Src);
7196       return CK_BlockPointerToObjCPointerCast;
7197     case Type::STK_Bool:
7198       return CK_PointerToBoolean;
7199     case Type::STK_Integral:
7200       return CK_PointerToIntegral;
7201     case Type::STK_Floating:
7202     case Type::STK_FloatingComplex:
7203     case Type::STK_IntegralComplex:
7204     case Type::STK_MemberPointer:
7205     case Type::STK_FixedPoint:
7206       llvm_unreachable("illegal cast from pointer");
7207     }
7208     llvm_unreachable("Should have returned before this");
7209 
7210   case Type::STK_FixedPoint:
7211     switch (DestTy->getScalarTypeKind()) {
7212     case Type::STK_FixedPoint:
7213       return CK_FixedPointCast;
7214     case Type::STK_Bool:
7215       return CK_FixedPointToBoolean;
7216     case Type::STK_Integral:
7217       return CK_FixedPointToIntegral;
7218     case Type::STK_Floating:
7219       return CK_FixedPointToFloating;
7220     case Type::STK_IntegralComplex:
7221     case Type::STK_FloatingComplex:
7222       Diag(Src.get()->getExprLoc(),
7223            diag::err_unimplemented_conversion_with_fixed_point_type)
7224           << DestTy;
7225       return CK_IntegralCast;
7226     case Type::STK_CPointer:
7227     case Type::STK_ObjCObjectPointer:
7228     case Type::STK_BlockPointer:
7229     case Type::STK_MemberPointer:
7230       llvm_unreachable("illegal cast to pointer type");
7231     }
7232     llvm_unreachable("Should have returned before this");
7233 
7234   case Type::STK_Bool: // casting from bool is like casting from an integer
7235   case Type::STK_Integral:
7236     switch (DestTy->getScalarTypeKind()) {
7237     case Type::STK_CPointer:
7238     case Type::STK_ObjCObjectPointer:
7239     case Type::STK_BlockPointer:
7240       if (Src.get()->isNullPointerConstant(Context,
7241                                            Expr::NPC_ValueDependentIsNull))
7242         return CK_NullToPointer;
7243       return CK_IntegralToPointer;
7244     case Type::STK_Bool:
7245       return CK_IntegralToBoolean;
7246     case Type::STK_Integral:
7247       return CK_IntegralCast;
7248     case Type::STK_Floating:
7249       return CK_IntegralToFloating;
7250     case Type::STK_IntegralComplex:
7251       Src = ImpCastExprToType(Src.get(),
7252                       DestTy->castAs<ComplexType>()->getElementType(),
7253                       CK_IntegralCast);
7254       return CK_IntegralRealToComplex;
7255     case Type::STK_FloatingComplex:
7256       Src = ImpCastExprToType(Src.get(),
7257                       DestTy->castAs<ComplexType>()->getElementType(),
7258                       CK_IntegralToFloating);
7259       return CK_FloatingRealToComplex;
7260     case Type::STK_MemberPointer:
7261       llvm_unreachable("member pointer type in C");
7262     case Type::STK_FixedPoint:
7263       return CK_IntegralToFixedPoint;
7264     }
7265     llvm_unreachable("Should have returned before this");
7266 
7267   case Type::STK_Floating:
7268     switch (DestTy->getScalarTypeKind()) {
7269     case Type::STK_Floating:
7270       return CK_FloatingCast;
7271     case Type::STK_Bool:
7272       return CK_FloatingToBoolean;
7273     case Type::STK_Integral:
7274       return CK_FloatingToIntegral;
7275     case Type::STK_FloatingComplex:
7276       Src = ImpCastExprToType(Src.get(),
7277                               DestTy->castAs<ComplexType>()->getElementType(),
7278                               CK_FloatingCast);
7279       return CK_FloatingRealToComplex;
7280     case Type::STK_IntegralComplex:
7281       Src = ImpCastExprToType(Src.get(),
7282                               DestTy->castAs<ComplexType>()->getElementType(),
7283                               CK_FloatingToIntegral);
7284       return CK_IntegralRealToComplex;
7285     case Type::STK_CPointer:
7286     case Type::STK_ObjCObjectPointer:
7287     case Type::STK_BlockPointer:
7288       llvm_unreachable("valid float->pointer cast?");
7289     case Type::STK_MemberPointer:
7290       llvm_unreachable("member pointer type in C");
7291     case Type::STK_FixedPoint:
7292       return CK_FloatingToFixedPoint;
7293     }
7294     llvm_unreachable("Should have returned before this");
7295 
7296   case Type::STK_FloatingComplex:
7297     switch (DestTy->getScalarTypeKind()) {
7298     case Type::STK_FloatingComplex:
7299       return CK_FloatingComplexCast;
7300     case Type::STK_IntegralComplex:
7301       return CK_FloatingComplexToIntegralComplex;
7302     case Type::STK_Floating: {
7303       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7304       if (Context.hasSameType(ET, DestTy))
7305         return CK_FloatingComplexToReal;
7306       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7307       return CK_FloatingCast;
7308     }
7309     case Type::STK_Bool:
7310       return CK_FloatingComplexToBoolean;
7311     case Type::STK_Integral:
7312       Src = ImpCastExprToType(Src.get(),
7313                               SrcTy->castAs<ComplexType>()->getElementType(),
7314                               CK_FloatingComplexToReal);
7315       return CK_FloatingToIntegral;
7316     case Type::STK_CPointer:
7317     case Type::STK_ObjCObjectPointer:
7318     case Type::STK_BlockPointer:
7319       llvm_unreachable("valid complex float->pointer cast?");
7320     case Type::STK_MemberPointer:
7321       llvm_unreachable("member pointer type in C");
7322     case Type::STK_FixedPoint:
7323       Diag(Src.get()->getExprLoc(),
7324            diag::err_unimplemented_conversion_with_fixed_point_type)
7325           << SrcTy;
7326       return CK_IntegralCast;
7327     }
7328     llvm_unreachable("Should have returned before this");
7329 
7330   case Type::STK_IntegralComplex:
7331     switch (DestTy->getScalarTypeKind()) {
7332     case Type::STK_FloatingComplex:
7333       return CK_IntegralComplexToFloatingComplex;
7334     case Type::STK_IntegralComplex:
7335       return CK_IntegralComplexCast;
7336     case Type::STK_Integral: {
7337       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7338       if (Context.hasSameType(ET, DestTy))
7339         return CK_IntegralComplexToReal;
7340       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7341       return CK_IntegralCast;
7342     }
7343     case Type::STK_Bool:
7344       return CK_IntegralComplexToBoolean;
7345     case Type::STK_Floating:
7346       Src = ImpCastExprToType(Src.get(),
7347                               SrcTy->castAs<ComplexType>()->getElementType(),
7348                               CK_IntegralComplexToReal);
7349       return CK_IntegralToFloating;
7350     case Type::STK_CPointer:
7351     case Type::STK_ObjCObjectPointer:
7352     case Type::STK_BlockPointer:
7353       llvm_unreachable("valid complex int->pointer cast?");
7354     case Type::STK_MemberPointer:
7355       llvm_unreachable("member pointer type in C");
7356     case Type::STK_FixedPoint:
7357       Diag(Src.get()->getExprLoc(),
7358            diag::err_unimplemented_conversion_with_fixed_point_type)
7359           << SrcTy;
7360       return CK_IntegralCast;
7361     }
7362     llvm_unreachable("Should have returned before this");
7363   }
7364 
7365   llvm_unreachable("Unhandled scalar cast");
7366 }
7367 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)7368 static bool breakDownVectorType(QualType type, uint64_t &len,
7369                                 QualType &eltType) {
7370   // Vectors are simple.
7371   if (const VectorType *vecType = type->getAs<VectorType>()) {
7372     len = vecType->getNumElements();
7373     eltType = vecType->getElementType();
7374     assert(eltType->isScalarType());
7375     return true;
7376   }
7377 
7378   // We allow lax conversion to and from non-vector types, but only if
7379   // they're real types (i.e. non-complex, non-pointer scalar types).
7380   if (!type->isRealType()) return false;
7381 
7382   len = 1;
7383   eltType = type;
7384   return true;
7385 }
7386 
7387 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7388 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7389 /// allowed?
7390 ///
7391 /// This will also return false if the two given types do not make sense from
7392 /// the perspective of SVE bitcasts.
isValidSveBitcast(QualType srcTy,QualType destTy)7393 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7394   assert(srcTy->isVectorType() || destTy->isVectorType());
7395 
7396   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7397     if (!FirstType->isSizelessBuiltinType())
7398       return false;
7399 
7400     const auto *VecTy = SecondType->getAs<VectorType>();
7401     return VecTy &&
7402            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7403   };
7404 
7405   return ValidScalableConversion(srcTy, destTy) ||
7406          ValidScalableConversion(destTy, srcTy);
7407 }
7408 
7409 /// Are the two types matrix types and do they have the same dimensions i.e.
7410 /// do they have the same number of rows and the same number of columns?
areMatrixTypesOfTheSameDimension(QualType srcTy,QualType destTy)7411 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7412   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7413     return false;
7414 
7415   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7416   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7417 
7418   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7419          matSrcType->getNumColumns() == matDestType->getNumColumns();
7420 }
7421 
areVectorTypesSameSize(QualType SrcTy,QualType DestTy)7422 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7423   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7424 
7425   uint64_t SrcLen, DestLen;
7426   QualType SrcEltTy, DestEltTy;
7427   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7428     return false;
7429   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7430     return false;
7431 
7432   // ASTContext::getTypeSize will return the size rounded up to a
7433   // power of 2, so instead of using that, we need to use the raw
7434   // element size multiplied by the element count.
7435   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7436   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7437 
7438   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7439 }
7440 
7441 /// Are the two types lax-compatible vector types?  That is, given
7442 /// that one of them is a vector, do they have equal storage sizes,
7443 /// where the storage size is the number of elements times the element
7444 /// size?
7445 ///
7446 /// This will also return false if either of the types is neither a
7447 /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)7448 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7449   assert(destTy->isVectorType() || srcTy->isVectorType());
7450 
7451   // Disallow lax conversions between scalars and ExtVectors (these
7452   // conversions are allowed for other vector types because common headers
7453   // depend on them).  Most scalar OP ExtVector cases are handled by the
7454   // splat path anyway, which does what we want (convert, not bitcast).
7455   // What this rules out for ExtVectors is crazy things like char4*float.
7456   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7457   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7458 
7459   return areVectorTypesSameSize(srcTy, destTy);
7460 }
7461 
7462 /// Is this a legal conversion between two types, one of which is
7463 /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)7464 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7465   assert(destTy->isVectorType() || srcTy->isVectorType());
7466 
7467   switch (Context.getLangOpts().getLaxVectorConversions()) {
7468   case LangOptions::LaxVectorConversionKind::None:
7469     return false;
7470 
7471   case LangOptions::LaxVectorConversionKind::Integer:
7472     if (!srcTy->isIntegralOrEnumerationType()) {
7473       auto *Vec = srcTy->getAs<VectorType>();
7474       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7475         return false;
7476     }
7477     if (!destTy->isIntegralOrEnumerationType()) {
7478       auto *Vec = destTy->getAs<VectorType>();
7479       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7480         return false;
7481     }
7482     // OK, integer (vector) -> integer (vector) bitcast.
7483     break;
7484 
7485     case LangOptions::LaxVectorConversionKind::All:
7486     break;
7487   }
7488 
7489   return areLaxCompatibleVectorTypes(srcTy, destTy);
7490 }
7491 
CheckMatrixCast(SourceRange R,QualType DestTy,QualType SrcTy,CastKind & Kind)7492 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7493                            CastKind &Kind) {
7494   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7495     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7496       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7497              << DestTy << SrcTy << R;
7498     }
7499   } else if (SrcTy->isMatrixType()) {
7500     return Diag(R.getBegin(),
7501                 diag::err_invalid_conversion_between_matrix_and_type)
7502            << SrcTy << DestTy << R;
7503   } else if (DestTy->isMatrixType()) {
7504     return Diag(R.getBegin(),
7505                 diag::err_invalid_conversion_between_matrix_and_type)
7506            << DestTy << SrcTy << R;
7507   }
7508 
7509   Kind = CK_MatrixCast;
7510   return false;
7511 }
7512 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)7513 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7514                            CastKind &Kind) {
7515   assert(VectorTy->isVectorType() && "Not a vector type!");
7516 
7517   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7518     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7519       return Diag(R.getBegin(),
7520                   Ty->isVectorType() ?
7521                   diag::err_invalid_conversion_between_vectors :
7522                   diag::err_invalid_conversion_between_vector_and_integer)
7523         << VectorTy << Ty << R;
7524   } else
7525     return Diag(R.getBegin(),
7526                 diag::err_invalid_conversion_between_vector_and_scalar)
7527       << VectorTy << Ty << R;
7528 
7529   Kind = CK_BitCast;
7530   return false;
7531 }
7532 
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)7533 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7534   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7535 
7536   if (DestElemTy == SplattedExpr->getType())
7537     return SplattedExpr;
7538 
7539   assert(DestElemTy->isFloatingType() ||
7540          DestElemTy->isIntegralOrEnumerationType());
7541 
7542   CastKind CK;
7543   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7544     // OpenCL requires that we convert `true` boolean expressions to -1, but
7545     // only when splatting vectors.
7546     if (DestElemTy->isFloatingType()) {
7547       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7548       // in two steps: boolean to signed integral, then to floating.
7549       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7550                                                  CK_BooleanToSignedIntegral);
7551       SplattedExpr = CastExprRes.get();
7552       CK = CK_IntegralToFloating;
7553     } else {
7554       CK = CK_BooleanToSignedIntegral;
7555     }
7556   } else {
7557     ExprResult CastExprRes = SplattedExpr;
7558     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7559     if (CastExprRes.isInvalid())
7560       return ExprError();
7561     SplattedExpr = CastExprRes.get();
7562   }
7563   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7564 }
7565 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)7566 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7567                                     Expr *CastExpr, CastKind &Kind) {
7568   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7569 
7570   QualType SrcTy = CastExpr->getType();
7571 
7572   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7573   // an ExtVectorType.
7574   // In OpenCL, casts between vectors of different types are not allowed.
7575   // (See OpenCL 6.2).
7576   if (SrcTy->isVectorType()) {
7577     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7578         (getLangOpts().OpenCL &&
7579          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7580       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7581         << DestTy << SrcTy << R;
7582       return ExprError();
7583     }
7584     Kind = CK_BitCast;
7585     return CastExpr;
7586   }
7587 
7588   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7589   // conversion will take place first from scalar to elt type, and then
7590   // splat from elt type to vector.
7591   if (SrcTy->isPointerType())
7592     return Diag(R.getBegin(),
7593                 diag::err_invalid_conversion_between_vector_and_scalar)
7594       << DestTy << SrcTy << R;
7595 
7596   Kind = CK_VectorSplat;
7597   return prepareVectorSplat(DestTy, CastExpr);
7598 }
7599 
7600 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)7601 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7602                     Declarator &D, ParsedType &Ty,
7603                     SourceLocation RParenLoc, Expr *CastExpr) {
7604   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7605          "ActOnCastExpr(): missing type or expr");
7606 
7607   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7608   if (D.isInvalidType())
7609     return ExprError();
7610 
7611   if (getLangOpts().CPlusPlus) {
7612     // Check that there are no default arguments (C++ only).
7613     CheckExtraCXXDefaultArguments(D);
7614   } else {
7615     // Make sure any TypoExprs have been dealt with.
7616     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7617     if (!Res.isUsable())
7618       return ExprError();
7619     CastExpr = Res.get();
7620   }
7621 
7622   checkUnusedDeclAttributes(D);
7623 
7624   QualType castType = castTInfo->getType();
7625   Ty = CreateParsedType(castType, castTInfo);
7626 
7627   bool isVectorLiteral = false;
7628 
7629   // Check for an altivec or OpenCL literal,
7630   // i.e. all the elements are integer constants.
7631   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7632   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7633   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7634        && castType->isVectorType() && (PE || PLE)) {
7635     if (PLE && PLE->getNumExprs() == 0) {
7636       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7637       return ExprError();
7638     }
7639     if (PE || PLE->getNumExprs() == 1) {
7640       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7641       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7642         isVectorLiteral = true;
7643     }
7644     else
7645       isVectorLiteral = true;
7646   }
7647 
7648   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7649   // then handle it as such.
7650   if (isVectorLiteral)
7651     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7652 
7653   // If the Expr being casted is a ParenListExpr, handle it specially.
7654   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7655   // sequence of BinOp comma operators.
7656   if (isa<ParenListExpr>(CastExpr)) {
7657     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7658     if (Result.isInvalid()) return ExprError();
7659     CastExpr = Result.get();
7660   }
7661 
7662   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7663       !getSourceManager().isInSystemMacro(LParenLoc))
7664     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7665 
7666   CheckTollFreeBridgeCast(castType, CastExpr);
7667 
7668   CheckObjCBridgeRelatedCast(castType, CastExpr);
7669 
7670   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7671 
7672   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7673 }
7674 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)7675 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7676                                     SourceLocation RParenLoc, Expr *E,
7677                                     TypeSourceInfo *TInfo) {
7678   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7679          "Expected paren or paren list expression");
7680 
7681   Expr **exprs;
7682   unsigned numExprs;
7683   Expr *subExpr;
7684   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7685   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7686     LiteralLParenLoc = PE->getLParenLoc();
7687     LiteralRParenLoc = PE->getRParenLoc();
7688     exprs = PE->getExprs();
7689     numExprs = PE->getNumExprs();
7690   } else { // isa<ParenExpr> by assertion at function entrance
7691     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7692     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7693     subExpr = cast<ParenExpr>(E)->getSubExpr();
7694     exprs = &subExpr;
7695     numExprs = 1;
7696   }
7697 
7698   QualType Ty = TInfo->getType();
7699   assert(Ty->isVectorType() && "Expected vector type");
7700 
7701   SmallVector<Expr *, 8> initExprs;
7702   const VectorType *VTy = Ty->castAs<VectorType>();
7703   unsigned numElems = VTy->getNumElements();
7704 
7705   // '(...)' form of vector initialization in AltiVec: the number of
7706   // initializers must be one or must match the size of the vector.
7707   // If a single value is specified in the initializer then it will be
7708   // replicated to all the components of the vector
7709   if (ShouldSplatAltivecScalarInCast(VTy)) {
7710     // The number of initializers must be one or must match the size of the
7711     // vector. If a single value is specified in the initializer then it will
7712     // be replicated to all the components of the vector
7713     if (numExprs == 1) {
7714       QualType ElemTy = VTy->getElementType();
7715       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7716       if (Literal.isInvalid())
7717         return ExprError();
7718       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7719                                   PrepareScalarCast(Literal, ElemTy));
7720       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7721     }
7722     else if (numExprs < numElems) {
7723       Diag(E->getExprLoc(),
7724            diag::err_incorrect_number_of_vector_initializers);
7725       return ExprError();
7726     }
7727     else
7728       initExprs.append(exprs, exprs + numExprs);
7729   }
7730   else {
7731     // For OpenCL, when the number of initializers is a single value,
7732     // it will be replicated to all components of the vector.
7733     if (getLangOpts().OpenCL &&
7734         VTy->getVectorKind() == VectorType::GenericVector &&
7735         numExprs == 1) {
7736         QualType ElemTy = VTy->getElementType();
7737         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7738         if (Literal.isInvalid())
7739           return ExprError();
7740         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7741                                     PrepareScalarCast(Literal, ElemTy));
7742         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7743     }
7744 
7745     initExprs.append(exprs, exprs + numExprs);
7746   }
7747   // FIXME: This means that pretty-printing the final AST will produce curly
7748   // braces instead of the original commas.
7749   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7750                                                    initExprs, LiteralRParenLoc);
7751   initE->setType(Ty);
7752   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7753 }
7754 
7755 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7756 /// the ParenListExpr into a sequence of comma binary operators.
7757 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)7758 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7759   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7760   if (!E)
7761     return OrigExpr;
7762 
7763   ExprResult Result(E->getExpr(0));
7764 
7765   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7766     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7767                         E->getExpr(i));
7768 
7769   if (Result.isInvalid()) return ExprError();
7770 
7771   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7772 }
7773 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)7774 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7775                                     SourceLocation R,
7776                                     MultiExprArg Val) {
7777   return ParenListExpr::Create(Context, L, Val, R);
7778 }
7779 
7780 /// Emit a specialized diagnostic when one expression is a null pointer
7781 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7782 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)7783 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7784                                       SourceLocation QuestionLoc) {
7785   Expr *NullExpr = LHSExpr;
7786   Expr *NonPointerExpr = RHSExpr;
7787   Expr::NullPointerConstantKind NullKind =
7788       NullExpr->isNullPointerConstant(Context,
7789                                       Expr::NPC_ValueDependentIsNotNull);
7790 
7791   if (NullKind == Expr::NPCK_NotNull) {
7792     NullExpr = RHSExpr;
7793     NonPointerExpr = LHSExpr;
7794     NullKind =
7795         NullExpr->isNullPointerConstant(Context,
7796                                         Expr::NPC_ValueDependentIsNotNull);
7797   }
7798 
7799   if (NullKind == Expr::NPCK_NotNull)
7800     return false;
7801 
7802   if (NullKind == Expr::NPCK_ZeroExpression)
7803     return false;
7804 
7805   if (NullKind == Expr::NPCK_ZeroLiteral) {
7806     // In this case, check to make sure that we got here from a "NULL"
7807     // string in the source code.
7808     NullExpr = NullExpr->IgnoreParenImpCasts();
7809     SourceLocation loc = NullExpr->getExprLoc();
7810     if (!findMacroSpelling(loc, "NULL"))
7811       return false;
7812   }
7813 
7814   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7815   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7816       << NonPointerExpr->getType() << DiagType
7817       << NonPointerExpr->getSourceRange();
7818   return true;
7819 }
7820 
7821 /// Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)7822 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7823   QualType CondTy = Cond->getType();
7824 
7825   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7826   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7827     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7828       << CondTy << Cond->getSourceRange();
7829     return true;
7830   }
7831 
7832   // C99 6.5.15p2
7833   if (CondTy->isScalarType()) return false;
7834 
7835   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7836     << CondTy << Cond->getSourceRange();
7837   return true;
7838 }
7839 
7840 /// Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)7841 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7842                                          ExprResult &RHS) {
7843     Expr *LHSExpr = LHS.get();
7844     Expr *RHSExpr = RHS.get();
7845 
7846     if (!LHSExpr->getType()->isVoidType())
7847       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7848           << RHSExpr->getSourceRange();
7849     if (!RHSExpr->getType()->isVoidType())
7850       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7851           << LHSExpr->getSourceRange();
7852     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7853     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7854     return S.Context.VoidTy;
7855 }
7856 
7857 /// Return false if the NullExpr can be promoted to PointerTy,
7858 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)7859 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7860                                         QualType PointerTy) {
7861   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7862       !NullExpr.get()->isNullPointerConstant(S.Context,
7863                                             Expr::NPC_ValueDependentIsNull))
7864     return true;
7865 
7866   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7867   return false;
7868 }
7869 
7870 /// Checks compatibility between two pointers and return the resulting
7871 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7872 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7873                                                      ExprResult &RHS,
7874                                                      SourceLocation Loc) {
7875   QualType LHSTy = LHS.get()->getType();
7876   QualType RHSTy = RHS.get()->getType();
7877 
7878   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7879     // Two identical pointers types are always compatible.
7880     return LHSTy;
7881   }
7882 
7883   QualType lhptee, rhptee;
7884 
7885   // Get the pointee types.
7886   bool IsBlockPointer = false;
7887   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7888     lhptee = LHSBTy->getPointeeType();
7889     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7890     IsBlockPointer = true;
7891   } else {
7892     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7893     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7894   }
7895 
7896   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7897   // differently qualified versions of compatible types, the result type is
7898   // a pointer to an appropriately qualified version of the composite
7899   // type.
7900 
7901   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7902   // clause doesn't make sense for our extensions. E.g. address space 2 should
7903   // be incompatible with address space 3: they may live on different devices or
7904   // anything.
7905   Qualifiers lhQual = lhptee.getQualifiers();
7906   Qualifiers rhQual = rhptee.getQualifiers();
7907 
7908   LangAS ResultAddrSpace = LangAS::Default;
7909   LangAS LAddrSpace = lhQual.getAddressSpace();
7910   LangAS RAddrSpace = rhQual.getAddressSpace();
7911 
7912   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7913   // spaces is disallowed.
7914   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7915     ResultAddrSpace = LAddrSpace;
7916   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7917     ResultAddrSpace = RAddrSpace;
7918   else {
7919     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7920         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7921         << RHS.get()->getSourceRange();
7922     return QualType();
7923   }
7924 
7925   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7926   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7927   lhQual.removeCVRQualifiers();
7928   rhQual.removeCVRQualifiers();
7929 
7930   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7931   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7932   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7933   // qual types are compatible iff
7934   //  * corresponded types are compatible
7935   //  * CVR qualifiers are equal
7936   //  * address spaces are equal
7937   // Thus for conditional operator we merge CVR and address space unqualified
7938   // pointees and if there is a composite type we return a pointer to it with
7939   // merged qualifiers.
7940   LHSCastKind =
7941       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7942   RHSCastKind =
7943       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7944   lhQual.removeAddressSpace();
7945   rhQual.removeAddressSpace();
7946 
7947   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7948   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7949 
7950   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7951 
7952   if (CompositeTy.isNull()) {
7953     // In this situation, we assume void* type. No especially good
7954     // reason, but this is what gcc does, and we do have to pick
7955     // to get a consistent AST.
7956     QualType incompatTy;
7957     incompatTy = S.Context.getPointerType(
7958         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7959     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7960     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7961 
7962     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7963     // for casts between types with incompatible address space qualifiers.
7964     // For the following code the compiler produces casts between global and
7965     // local address spaces of the corresponded innermost pointees:
7966     // local int *global *a;
7967     // global int *global *b;
7968     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7969     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7970         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7971         << RHS.get()->getSourceRange();
7972 
7973     return incompatTy;
7974   }
7975 
7976   // The pointer types are compatible.
7977   // In case of OpenCL ResultTy should have the address space qualifier
7978   // which is a superset of address spaces of both the 2nd and the 3rd
7979   // operands of the conditional operator.
7980   QualType ResultTy = [&, ResultAddrSpace]() {
7981     if (S.getLangOpts().OpenCL) {
7982       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7983       CompositeQuals.setAddressSpace(ResultAddrSpace);
7984       return S.Context
7985           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7986           .withCVRQualifiers(MergedCVRQual);
7987     }
7988     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7989   }();
7990   if (IsBlockPointer)
7991     ResultTy = S.Context.getBlockPointerType(ResultTy);
7992   else
7993     ResultTy = S.Context.getPointerType(ResultTy);
7994 
7995   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7996   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7997   return ResultTy;
7998 }
7999 
8000 /// Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)8001 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8002                                                           ExprResult &LHS,
8003                                                           ExprResult &RHS,
8004                                                           SourceLocation Loc) {
8005   QualType LHSTy = LHS.get()->getType();
8006   QualType RHSTy = RHS.get()->getType();
8007 
8008   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8009     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8010       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8011       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8012       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8013       return destType;
8014     }
8015     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8016       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8017       << RHS.get()->getSourceRange();
8018     return QualType();
8019   }
8020 
8021   // We have 2 block pointer types.
8022   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8023 }
8024 
8025 /// Return the resulting type when the operands are both pointers.
8026 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)8027 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8028                                             ExprResult &RHS,
8029                                             SourceLocation Loc) {
8030   // get the pointer types
8031   QualType LHSTy = LHS.get()->getType();
8032   QualType RHSTy = RHS.get()->getType();
8033 
8034   // get the "pointed to" types
8035   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8036   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8037 
8038   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8039   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8040     // Figure out necessary qualifiers (C99 6.5.15p6)
8041     QualType destPointee
8042       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8043     QualType destType = S.Context.getPointerType(destPointee);
8044     // Add qualifiers if necessary.
8045     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8046     // Promote to void*.
8047     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8048     return destType;
8049   }
8050   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8051     QualType destPointee
8052       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8053     QualType destType = S.Context.getPointerType(destPointee);
8054     // Add qualifiers if necessary.
8055     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8056     // Promote to void*.
8057     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8058     return destType;
8059   }
8060 
8061   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8062 }
8063 
8064 /// Return false if the first expression is not an integer and the second
8065 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)8066 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8067                                         Expr* PointerExpr, SourceLocation Loc,
8068                                         bool IsIntFirstExpr) {
8069   if (!PointerExpr->getType()->isPointerType() ||
8070       !Int.get()->getType()->isIntegerType())
8071     return false;
8072 
8073   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8074   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8075 
8076   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8077     << Expr1->getType() << Expr2->getType()
8078     << Expr1->getSourceRange() << Expr2->getSourceRange();
8079   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8080                             CK_IntegralToPointer);
8081   return true;
8082 }
8083 
8084 /// Simple conversion between integer and floating point types.
8085 ///
8086 /// Used when handling the OpenCL conditional operator where the
8087 /// condition is a vector while the other operands are scalar.
8088 ///
8089 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8090 /// types are either integer or floating type. Between the two
8091 /// operands, the type with the higher rank is defined as the "result
8092 /// type". The other operand needs to be promoted to the same type. No
8093 /// other type promotion is allowed. We cannot use
8094 /// UsualArithmeticConversions() for this purpose, since it always
8095 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8096 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8097                                             ExprResult &RHS,
8098                                             SourceLocation QuestionLoc) {
8099   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8100   if (LHS.isInvalid())
8101     return QualType();
8102   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8103   if (RHS.isInvalid())
8104     return QualType();
8105 
8106   // For conversion purposes, we ignore any qualifiers.
8107   // For example, "const float" and "float" are equivalent.
8108   QualType LHSType =
8109     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8110   QualType RHSType =
8111     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8112 
8113   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8114     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8115       << LHSType << LHS.get()->getSourceRange();
8116     return QualType();
8117   }
8118 
8119   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8120     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8121       << RHSType << RHS.get()->getSourceRange();
8122     return QualType();
8123   }
8124 
8125   // If both types are identical, no conversion is needed.
8126   if (LHSType == RHSType)
8127     return LHSType;
8128 
8129   // Now handle "real" floating types (i.e. float, double, long double).
8130   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8131     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8132                                  /*IsCompAssign = */ false);
8133 
8134   // Finally, we have two differing integer types.
8135   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8136   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8137 }
8138 
8139 /// Convert scalar operands to a vector that matches the
8140 ///        condition in length.
8141 ///
8142 /// Used when handling the OpenCL conditional operator where the
8143 /// condition is a vector while the other operands are scalar.
8144 ///
8145 /// We first compute the "result type" for the scalar operands
8146 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8147 /// into a vector of that type where the length matches the condition
8148 /// vector type. s6.11.6 requires that the element types of the result
8149 /// and the condition must have the same number of bits.
8150 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)8151 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8152                               QualType CondTy, SourceLocation QuestionLoc) {
8153   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8154   if (ResTy.isNull()) return QualType();
8155 
8156   const VectorType *CV = CondTy->getAs<VectorType>();
8157   assert(CV);
8158 
8159   // Determine the vector result type
8160   unsigned NumElements = CV->getNumElements();
8161   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8162 
8163   // Ensure that all types have the same number of bits
8164   if (S.Context.getTypeSize(CV->getElementType())
8165       != S.Context.getTypeSize(ResTy)) {
8166     // Since VectorTy is created internally, it does not pretty print
8167     // with an OpenCL name. Instead, we just print a description.
8168     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8169     SmallString<64> Str;
8170     llvm::raw_svector_ostream OS(Str);
8171     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8172     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8173       << CondTy << OS.str();
8174     return QualType();
8175   }
8176 
8177   // Convert operands to the vector result type
8178   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8179   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8180 
8181   return VectorTy;
8182 }
8183 
8184 /// Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)8185 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8186                                        SourceLocation QuestionLoc) {
8187   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8188   // integral type.
8189   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8190   assert(CondTy);
8191   QualType EleTy = CondTy->getElementType();
8192   if (EleTy->isIntegerType()) return false;
8193 
8194   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8195     << Cond->getType() << Cond->getSourceRange();
8196   return true;
8197 }
8198 
8199 /// Return false if the vector condition type and the vector
8200 ///        result type are compatible.
8201 ///
8202 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8203 /// number of elements, and their element types have the same number
8204 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)8205 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8206                               SourceLocation QuestionLoc) {
8207   const VectorType *CV = CondTy->getAs<VectorType>();
8208   const VectorType *RV = VecResTy->getAs<VectorType>();
8209   assert(CV && RV);
8210 
8211   if (CV->getNumElements() != RV->getNumElements()) {
8212     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8213       << CondTy << VecResTy;
8214     return true;
8215   }
8216 
8217   QualType CVE = CV->getElementType();
8218   QualType RVE = RV->getElementType();
8219 
8220   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8221     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8222       << CondTy << VecResTy;
8223     return true;
8224   }
8225 
8226   return false;
8227 }
8228 
8229 /// Return the resulting type for the conditional operator in
8230 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8231 ///        s6.3.i) when the condition is a vector type.
8232 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8233 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8234                              ExprResult &LHS, ExprResult &RHS,
8235                              SourceLocation QuestionLoc) {
8236   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8237   if (Cond.isInvalid())
8238     return QualType();
8239   QualType CondTy = Cond.get()->getType();
8240 
8241   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8242     return QualType();
8243 
8244   // If either operand is a vector then find the vector type of the
8245   // result as specified in OpenCL v1.1 s6.3.i.
8246   if (LHS.get()->getType()->isVectorType() ||
8247       RHS.get()->getType()->isVectorType()) {
8248     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8249                                               /*isCompAssign*/false,
8250                                               /*AllowBothBool*/true,
8251                                               /*AllowBoolConversions*/false);
8252     if (VecResTy.isNull()) return QualType();
8253     // The result type must match the condition type as specified in
8254     // OpenCL v1.1 s6.11.6.
8255     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8256       return QualType();
8257     return VecResTy;
8258   }
8259 
8260   // Both operands are scalar.
8261   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8262 }
8263 
8264 /// Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)8265 static bool checkBlockType(Sema &S, const Expr *E) {
8266   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8267     QualType Ty = CE->getCallee()->getType();
8268     if (Ty->isBlockPointerType()) {
8269       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8270       return true;
8271     }
8272   }
8273   return false;
8274 }
8275 
8276 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8277 /// In that case, LHS = cond.
8278 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)8279 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8280                                         ExprResult &RHS, ExprValueKind &VK,
8281                                         ExprObjectKind &OK,
8282                                         SourceLocation QuestionLoc) {
8283 
8284   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8285   if (!LHSResult.isUsable()) return QualType();
8286   LHS = LHSResult;
8287 
8288   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8289   if (!RHSResult.isUsable()) return QualType();
8290   RHS = RHSResult;
8291 
8292   // C++ is sufficiently different to merit its own checker.
8293   if (getLangOpts().CPlusPlus)
8294     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8295 
8296   VK = VK_PRValue;
8297   OK = OK_Ordinary;
8298 
8299   if (Context.isDependenceAllowed() &&
8300       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8301        RHS.get()->isTypeDependent())) {
8302     assert(!getLangOpts().CPlusPlus);
8303     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8304             RHS.get()->containsErrors()) &&
8305            "should only occur in error-recovery path.");
8306     return Context.DependentTy;
8307   }
8308 
8309   // The OpenCL operator with a vector condition is sufficiently
8310   // different to merit its own checker.
8311   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8312       Cond.get()->getType()->isExtVectorType())
8313     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8314 
8315   // First, check the condition.
8316   Cond = UsualUnaryConversions(Cond.get());
8317   if (Cond.isInvalid())
8318     return QualType();
8319   if (checkCondition(*this, Cond.get(), QuestionLoc))
8320     return QualType();
8321 
8322   // Now check the two expressions.
8323   if (LHS.get()->getType()->isVectorType() ||
8324       RHS.get()->getType()->isVectorType())
8325     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8326                                /*AllowBothBool*/true,
8327                                /*AllowBoolConversions*/false);
8328 
8329   QualType ResTy =
8330       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8331   if (LHS.isInvalid() || RHS.isInvalid())
8332     return QualType();
8333 
8334   QualType LHSTy = LHS.get()->getType();
8335   QualType RHSTy = RHS.get()->getType();
8336 
8337   // Diagnose attempts to convert between __float128 and long double where
8338   // such conversions currently can't be handled.
8339   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8340     Diag(QuestionLoc,
8341          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8342       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8343     return QualType();
8344   }
8345 
8346   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8347   // selection operator (?:).
8348   if (getLangOpts().OpenCL &&
8349       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8350     return QualType();
8351   }
8352 
8353   // If both operands have arithmetic type, do the usual arithmetic conversions
8354   // to find a common type: C99 6.5.15p3,5.
8355   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8356     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8357     // different sizes, or between ExtInts and other types.
8358     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8359       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8360           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8361           << RHS.get()->getSourceRange();
8362       return QualType();
8363     }
8364 
8365     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8366     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8367 
8368     return ResTy;
8369   }
8370 
8371   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8372   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8373     return LHSTy;
8374   }
8375 
8376   // If both operands are the same structure or union type, the result is that
8377   // type.
8378   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8379     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8380       if (LHSRT->getDecl() == RHSRT->getDecl())
8381         // "If both the operands have structure or union type, the result has
8382         // that type."  This implies that CV qualifiers are dropped.
8383         return LHSTy.getUnqualifiedType();
8384     // FIXME: Type of conditional expression must be complete in C mode.
8385   }
8386 
8387   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8388   // The following || allows only one side to be void (a GCC-ism).
8389   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8390     return checkConditionalVoidType(*this, LHS, RHS);
8391   }
8392 
8393   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8394   // the type of the other operand."
8395   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8396   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8397 
8398   // All objective-c pointer type analysis is done here.
8399   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8400                                                         QuestionLoc);
8401   if (LHS.isInvalid() || RHS.isInvalid())
8402     return QualType();
8403   if (!compositeType.isNull())
8404     return compositeType;
8405 
8406 
8407   // Handle block pointer types.
8408   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8409     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8410                                                      QuestionLoc);
8411 
8412   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8413   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8414     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8415                                                        QuestionLoc);
8416 
8417   // GCC compatibility: soften pointer/integer mismatch.  Note that
8418   // null pointers have been filtered out by this point.
8419   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8420       /*IsIntFirstExpr=*/true))
8421     return RHSTy;
8422   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8423       /*IsIntFirstExpr=*/false))
8424     return LHSTy;
8425 
8426   // Allow ?: operations in which both operands have the same
8427   // built-in sizeless type.
8428   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8429     return LHSTy;
8430 
8431   // Emit a better diagnostic if one of the expressions is a null pointer
8432   // constant and the other is not a pointer type. In this case, the user most
8433   // likely forgot to take the address of the other expression.
8434   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8435     return QualType();
8436 
8437   // Otherwise, the operands are not compatible.
8438   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8439     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8440     << RHS.get()->getSourceRange();
8441   return QualType();
8442 }
8443 
8444 /// FindCompositeObjCPointerType - Helper method to find composite type of
8445 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8446 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8447                                             SourceLocation QuestionLoc) {
8448   QualType LHSTy = LHS.get()->getType();
8449   QualType RHSTy = RHS.get()->getType();
8450 
8451   // Handle things like Class and struct objc_class*.  Here we case the result
8452   // to the pseudo-builtin, because that will be implicitly cast back to the
8453   // redefinition type if an attempt is made to access its fields.
8454   if (LHSTy->isObjCClassType() &&
8455       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8456     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8457     return LHSTy;
8458   }
8459   if (RHSTy->isObjCClassType() &&
8460       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8461     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8462     return RHSTy;
8463   }
8464   // And the same for struct objc_object* / id
8465   if (LHSTy->isObjCIdType() &&
8466       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8467     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8468     return LHSTy;
8469   }
8470   if (RHSTy->isObjCIdType() &&
8471       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8472     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8473     return RHSTy;
8474   }
8475   // And the same for struct objc_selector* / SEL
8476   if (Context.isObjCSelType(LHSTy) &&
8477       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8478     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8479     return LHSTy;
8480   }
8481   if (Context.isObjCSelType(RHSTy) &&
8482       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8483     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8484     return RHSTy;
8485   }
8486   // Check constraints for Objective-C object pointers types.
8487   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8488 
8489     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8490       // Two identical object pointer types are always compatible.
8491       return LHSTy;
8492     }
8493     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8494     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8495     QualType compositeType = LHSTy;
8496 
8497     // If both operands are interfaces and either operand can be
8498     // assigned to the other, use that type as the composite
8499     // type. This allows
8500     //   xxx ? (A*) a : (B*) b
8501     // where B is a subclass of A.
8502     //
8503     // Additionally, as for assignment, if either type is 'id'
8504     // allow silent coercion. Finally, if the types are
8505     // incompatible then make sure to use 'id' as the composite
8506     // type so the result is acceptable for sending messages to.
8507 
8508     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8509     // It could return the composite type.
8510     if (!(compositeType =
8511           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8512       // Nothing more to do.
8513     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8514       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8515     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8516       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8517     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8518                 RHSOPT->isObjCQualifiedIdType()) &&
8519                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8520                                                          true)) {
8521       // Need to handle "id<xx>" explicitly.
8522       // GCC allows qualified id and any Objective-C type to devolve to
8523       // id. Currently localizing to here until clear this should be
8524       // part of ObjCQualifiedIdTypesAreCompatible.
8525       compositeType = Context.getObjCIdType();
8526     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8527       compositeType = Context.getObjCIdType();
8528     } else {
8529       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8530       << LHSTy << RHSTy
8531       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8532       QualType incompatTy = Context.getObjCIdType();
8533       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8534       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8535       return incompatTy;
8536     }
8537     // The object pointer types are compatible.
8538     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8539     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8540     return compositeType;
8541   }
8542   // Check Objective-C object pointer types and 'void *'
8543   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8544     if (getLangOpts().ObjCAutoRefCount) {
8545       // ARC forbids the implicit conversion of object pointers to 'void *',
8546       // so these types are not compatible.
8547       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8548           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8549       LHS = RHS = true;
8550       return QualType();
8551     }
8552     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8553     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8554     QualType destPointee
8555     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8556     QualType destType = Context.getPointerType(destPointee);
8557     // Add qualifiers if necessary.
8558     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8559     // Promote to void*.
8560     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8561     return destType;
8562   }
8563   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8564     if (getLangOpts().ObjCAutoRefCount) {
8565       // ARC forbids the implicit conversion of object pointers to 'void *',
8566       // so these types are not compatible.
8567       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8568           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8569       LHS = RHS = true;
8570       return QualType();
8571     }
8572     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8573     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8574     QualType destPointee
8575     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8576     QualType destType = Context.getPointerType(destPointee);
8577     // Add qualifiers if necessary.
8578     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8579     // Promote to void*.
8580     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8581     return destType;
8582   }
8583   return QualType();
8584 }
8585 
8586 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8587 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)8588 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8589                                const PartialDiagnostic &Note,
8590                                SourceRange ParenRange) {
8591   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8592   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8593       EndLoc.isValid()) {
8594     Self.Diag(Loc, Note)
8595       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8596       << FixItHint::CreateInsertion(EndLoc, ")");
8597   } else {
8598     // We can't display the parentheses, so just show the bare note.
8599     Self.Diag(Loc, Note) << ParenRange;
8600   }
8601 }
8602 
IsArithmeticOp(BinaryOperatorKind Opc)8603 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8604   return BinaryOperator::isAdditiveOp(Opc) ||
8605          BinaryOperator::isMultiplicativeOp(Opc) ||
8606          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8607   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8608   // not any of the logical operators.  Bitwise-xor is commonly used as a
8609   // logical-xor because there is no logical-xor operator.  The logical
8610   // operators, including uses of xor, have a high false positive rate for
8611   // precedence warnings.
8612 }
8613 
8614 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8615 /// expression, either using a built-in or overloaded operator,
8616 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8617 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)8618 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8619                                    Expr **RHSExprs) {
8620   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8621   E = E->IgnoreImpCasts();
8622   E = E->IgnoreConversionOperatorSingleStep();
8623   E = E->IgnoreImpCasts();
8624   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8625     E = MTE->getSubExpr();
8626     E = E->IgnoreImpCasts();
8627   }
8628 
8629   // Built-in binary operator.
8630   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8631     if (IsArithmeticOp(OP->getOpcode())) {
8632       *Opcode = OP->getOpcode();
8633       *RHSExprs = OP->getRHS();
8634       return true;
8635     }
8636   }
8637 
8638   // Overloaded operator.
8639   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8640     if (Call->getNumArgs() != 2)
8641       return false;
8642 
8643     // Make sure this is really a binary operator that is safe to pass into
8644     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8645     OverloadedOperatorKind OO = Call->getOperator();
8646     if (OO < OO_Plus || OO > OO_Arrow ||
8647         OO == OO_PlusPlus || OO == OO_MinusMinus)
8648       return false;
8649 
8650     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8651     if (IsArithmeticOp(OpKind)) {
8652       *Opcode = OpKind;
8653       *RHSExprs = Call->getArg(1);
8654       return true;
8655     }
8656   }
8657 
8658   return false;
8659 }
8660 
8661 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8662 /// or is a logical expression such as (x==y) which has int type, but is
8663 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)8664 static bool ExprLooksBoolean(Expr *E) {
8665   E = E->IgnoreParenImpCasts();
8666 
8667   if (E->getType()->isBooleanType())
8668     return true;
8669   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8670     return OP->isComparisonOp() || OP->isLogicalOp();
8671   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8672     return OP->getOpcode() == UO_LNot;
8673   if (E->getType()->isPointerType())
8674     return true;
8675   // FIXME: What about overloaded operator calls returning "unspecified boolean
8676   // type"s (commonly pointer-to-members)?
8677 
8678   return false;
8679 }
8680 
8681 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8682 /// and binary operator are mixed in a way that suggests the programmer assumed
8683 /// the conditional operator has higher precedence, for example:
8684 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)8685 static void DiagnoseConditionalPrecedence(Sema &Self,
8686                                           SourceLocation OpLoc,
8687                                           Expr *Condition,
8688                                           Expr *LHSExpr,
8689                                           Expr *RHSExpr) {
8690   BinaryOperatorKind CondOpcode;
8691   Expr *CondRHS;
8692 
8693   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8694     return;
8695   if (!ExprLooksBoolean(CondRHS))
8696     return;
8697 
8698   // The condition is an arithmetic binary expression, with a right-
8699   // hand side that looks boolean, so warn.
8700 
8701   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8702                         ? diag::warn_precedence_bitwise_conditional
8703                         : diag::warn_precedence_conditional;
8704 
8705   Self.Diag(OpLoc, DiagID)
8706       << Condition->getSourceRange()
8707       << BinaryOperator::getOpcodeStr(CondOpcode);
8708 
8709   SuggestParentheses(
8710       Self, OpLoc,
8711       Self.PDiag(diag::note_precedence_silence)
8712           << BinaryOperator::getOpcodeStr(CondOpcode),
8713       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8714 
8715   SuggestParentheses(Self, OpLoc,
8716                      Self.PDiag(diag::note_precedence_conditional_first),
8717                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8718 }
8719 
8720 /// Compute the nullability of a conditional expression.
computeConditionalNullability(QualType ResTy,bool IsBin,QualType LHSTy,QualType RHSTy,ASTContext & Ctx)8721 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8722                                               QualType LHSTy, QualType RHSTy,
8723                                               ASTContext &Ctx) {
8724   if (!ResTy->isAnyPointerType())
8725     return ResTy;
8726 
8727   auto GetNullability = [&Ctx](QualType Ty) {
8728     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8729     if (Kind) {
8730       // For our purposes, treat _Nullable_result as _Nullable.
8731       if (*Kind == NullabilityKind::NullableResult)
8732         return NullabilityKind::Nullable;
8733       return *Kind;
8734     }
8735     return NullabilityKind::Unspecified;
8736   };
8737 
8738   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8739   NullabilityKind MergedKind;
8740 
8741   // Compute nullability of a binary conditional expression.
8742   if (IsBin) {
8743     if (LHSKind == NullabilityKind::NonNull)
8744       MergedKind = NullabilityKind::NonNull;
8745     else
8746       MergedKind = RHSKind;
8747   // Compute nullability of a normal conditional expression.
8748   } else {
8749     if (LHSKind == NullabilityKind::Nullable ||
8750         RHSKind == NullabilityKind::Nullable)
8751       MergedKind = NullabilityKind::Nullable;
8752     else if (LHSKind == NullabilityKind::NonNull)
8753       MergedKind = RHSKind;
8754     else if (RHSKind == NullabilityKind::NonNull)
8755       MergedKind = LHSKind;
8756     else
8757       MergedKind = NullabilityKind::Unspecified;
8758   }
8759 
8760   // Return if ResTy already has the correct nullability.
8761   if (GetNullability(ResTy) == MergedKind)
8762     return ResTy;
8763 
8764   // Strip all nullability from ResTy.
8765   while (ResTy->getNullability(Ctx))
8766     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8767 
8768   // Create a new AttributedType with the new nullability kind.
8769   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8770   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8771 }
8772 
8773 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8774 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)8775 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8776                                     SourceLocation ColonLoc,
8777                                     Expr *CondExpr, Expr *LHSExpr,
8778                                     Expr *RHSExpr) {
8779   if (!Context.isDependenceAllowed()) {
8780     // C cannot handle TypoExpr nodes in the condition because it
8781     // doesn't handle dependent types properly, so make sure any TypoExprs have
8782     // been dealt with before checking the operands.
8783     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8784     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8785     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8786 
8787     if (!CondResult.isUsable())
8788       return ExprError();
8789 
8790     if (LHSExpr) {
8791       if (!LHSResult.isUsable())
8792         return ExprError();
8793     }
8794 
8795     if (!RHSResult.isUsable())
8796       return ExprError();
8797 
8798     CondExpr = CondResult.get();
8799     LHSExpr = LHSResult.get();
8800     RHSExpr = RHSResult.get();
8801   }
8802 
8803   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8804   // was the condition.
8805   OpaqueValueExpr *opaqueValue = nullptr;
8806   Expr *commonExpr = nullptr;
8807   if (!LHSExpr) {
8808     commonExpr = CondExpr;
8809     // Lower out placeholder types first.  This is important so that we don't
8810     // try to capture a placeholder. This happens in few cases in C++; such
8811     // as Objective-C++'s dictionary subscripting syntax.
8812     if (commonExpr->hasPlaceholderType()) {
8813       ExprResult result = CheckPlaceholderExpr(commonExpr);
8814       if (!result.isUsable()) return ExprError();
8815       commonExpr = result.get();
8816     }
8817     // We usually want to apply unary conversions *before* saving, except
8818     // in the special case of a C++ l-value conditional.
8819     if (!(getLangOpts().CPlusPlus
8820           && !commonExpr->isTypeDependent()
8821           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8822           && commonExpr->isGLValue()
8823           && commonExpr->isOrdinaryOrBitFieldObject()
8824           && RHSExpr->isOrdinaryOrBitFieldObject()
8825           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8826       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8827       if (commonRes.isInvalid())
8828         return ExprError();
8829       commonExpr = commonRes.get();
8830     }
8831 
8832     // If the common expression is a class or array prvalue, materialize it
8833     // so that we can safely refer to it multiple times.
8834     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8835                                     commonExpr->getType()->isArrayType())) {
8836       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8837       if (MatExpr.isInvalid())
8838         return ExprError();
8839       commonExpr = MatExpr.get();
8840     }
8841 
8842     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8843                                                 commonExpr->getType(),
8844                                                 commonExpr->getValueKind(),
8845                                                 commonExpr->getObjectKind(),
8846                                                 commonExpr);
8847     LHSExpr = CondExpr = opaqueValue;
8848   }
8849 
8850   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8851   ExprValueKind VK = VK_PRValue;
8852   ExprObjectKind OK = OK_Ordinary;
8853   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8854   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8855                                              VK, OK, QuestionLoc);
8856   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8857       RHS.isInvalid())
8858     return ExprError();
8859 
8860   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8861                                 RHS.get());
8862 
8863   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8864 
8865   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8866                                          Context);
8867 
8868   if (!commonExpr)
8869     return new (Context)
8870         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8871                             RHS.get(), result, VK, OK);
8872 
8873   return new (Context) BinaryConditionalOperator(
8874       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8875       ColonLoc, result, VK, OK);
8876 }
8877 
8878 // Check if we have a conversion between incompatible cmse function pointer
8879 // types, that is, a conversion between a function pointer with the
8880 // cmse_nonsecure_call attribute and one without.
IsInvalidCmseNSCallConversion(Sema & S,QualType FromType,QualType ToType)8881 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8882                                           QualType ToType) {
8883   if (const auto *ToFn =
8884           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8885     if (const auto *FromFn =
8886             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8887       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8888       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8889 
8890       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8891     }
8892   }
8893   return false;
8894 }
8895 
8896 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8897 // being closely modeled after the C99 spec:-). The odd characteristic of this
8898 // routine is it effectively iqnores the qualifiers on the top level pointee.
8899 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8900 // FIXME: add a couple examples in this comment.
8901 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8902 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8903   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8904   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8905 
8906   // get the "pointed to" type (ignoring qualifiers at the top level)
8907   const Type *lhptee, *rhptee;
8908   Qualifiers lhq, rhq;
8909   std::tie(lhptee, lhq) =
8910       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8911   std::tie(rhptee, rhq) =
8912       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8913 
8914   Sema::AssignConvertType ConvTy = Sema::Compatible;
8915 
8916   // C99 6.5.16.1p1: This following citation is common to constraints
8917   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8918   // qualifiers of the type *pointed to* by the right;
8919 
8920   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8921   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8922       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8923     // Ignore lifetime for further calculation.
8924     lhq.removeObjCLifetime();
8925     rhq.removeObjCLifetime();
8926   }
8927 
8928   if (!lhq.compatiblyIncludes(rhq)) {
8929     // Treat address-space mismatches as fatal.
8930     if (!lhq.isAddressSpaceSupersetOf(rhq))
8931       return Sema::IncompatiblePointerDiscardsQualifiers;
8932 
8933     // It's okay to add or remove GC or lifetime qualifiers when converting to
8934     // and from void*.
8935     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8936                         .compatiblyIncludes(
8937                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8938              && (lhptee->isVoidType() || rhptee->isVoidType()))
8939       ; // keep old
8940 
8941     // Treat lifetime mismatches as fatal.
8942     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8943       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8944 
8945     // For GCC/MS compatibility, other qualifier mismatches are treated
8946     // as still compatible in C.
8947     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8948   }
8949 
8950   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8951   // incomplete type and the other is a pointer to a qualified or unqualified
8952   // version of void...
8953   if (lhptee->isVoidType()) {
8954     if (rhptee->isIncompleteOrObjectType())
8955       return ConvTy;
8956 
8957     // As an extension, we allow cast to/from void* to function pointer.
8958     assert(rhptee->isFunctionType());
8959     return Sema::FunctionVoidPointer;
8960   }
8961 
8962   if (rhptee->isVoidType()) {
8963     if (lhptee->isIncompleteOrObjectType())
8964       return ConvTy;
8965 
8966     // As an extension, we allow cast to/from void* to function pointer.
8967     assert(lhptee->isFunctionType());
8968     return Sema::FunctionVoidPointer;
8969   }
8970 
8971   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8972   // unqualified versions of compatible types, ...
8973   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8974   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8975     // Check if the pointee types are compatible ignoring the sign.
8976     // We explicitly check for char so that we catch "char" vs
8977     // "unsigned char" on systems where "char" is unsigned.
8978     if (lhptee->isCharType())
8979       ltrans = S.Context.UnsignedCharTy;
8980     else if (lhptee->hasSignedIntegerRepresentation())
8981       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8982 
8983     if (rhptee->isCharType())
8984       rtrans = S.Context.UnsignedCharTy;
8985     else if (rhptee->hasSignedIntegerRepresentation())
8986       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8987 
8988     if (ltrans == rtrans) {
8989       // Types are compatible ignoring the sign. Qualifier incompatibility
8990       // takes priority over sign incompatibility because the sign
8991       // warning can be disabled.
8992       if (ConvTy != Sema::Compatible)
8993         return ConvTy;
8994 
8995       return Sema::IncompatiblePointerSign;
8996     }
8997 
8998     // If we are a multi-level pointer, it's possible that our issue is simply
8999     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9000     // the eventual target type is the same and the pointers have the same
9001     // level of indirection, this must be the issue.
9002     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9003       do {
9004         std::tie(lhptee, lhq) =
9005           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9006         std::tie(rhptee, rhq) =
9007           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9008 
9009         // Inconsistent address spaces at this point is invalid, even if the
9010         // address spaces would be compatible.
9011         // FIXME: This doesn't catch address space mismatches for pointers of
9012         // different nesting levels, like:
9013         //   __local int *** a;
9014         //   int ** b = a;
9015         // It's not clear how to actually determine when such pointers are
9016         // invalidly incompatible.
9017         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9018           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9019 
9020       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9021 
9022       if (lhptee == rhptee)
9023         return Sema::IncompatibleNestedPointerQualifiers;
9024     }
9025 
9026     // General pointer incompatibility takes priority over qualifiers.
9027     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9028       return Sema::IncompatibleFunctionPointer;
9029     return Sema::IncompatiblePointer;
9030   }
9031   if (!S.getLangOpts().CPlusPlus &&
9032       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9033     return Sema::IncompatibleFunctionPointer;
9034   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9035     return Sema::IncompatibleFunctionPointer;
9036   return ConvTy;
9037 }
9038 
9039 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9040 /// block pointer types are compatible or whether a block and normal pointer
9041 /// are compatible. It is more restrict than comparing two function pointer
9042 // types.
9043 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)9044 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9045                                     QualType RHSType) {
9046   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9047   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9048 
9049   QualType lhptee, rhptee;
9050 
9051   // get the "pointed to" type (ignoring qualifiers at the top level)
9052   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9053   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9054 
9055   // In C++, the types have to match exactly.
9056   if (S.getLangOpts().CPlusPlus)
9057     return Sema::IncompatibleBlockPointer;
9058 
9059   Sema::AssignConvertType ConvTy = Sema::Compatible;
9060 
9061   // For blocks we enforce that qualifiers are identical.
9062   Qualifiers LQuals = lhptee.getLocalQualifiers();
9063   Qualifiers RQuals = rhptee.getLocalQualifiers();
9064   if (S.getLangOpts().OpenCL) {
9065     LQuals.removeAddressSpace();
9066     RQuals.removeAddressSpace();
9067   }
9068   if (LQuals != RQuals)
9069     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9070 
9071   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9072   // assignment.
9073   // The current behavior is similar to C++ lambdas. A block might be
9074   // assigned to a variable iff its return type and parameters are compatible
9075   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9076   // an assignment. Presumably it should behave in way that a function pointer
9077   // assignment does in C, so for each parameter and return type:
9078   //  * CVR and address space of LHS should be a superset of CVR and address
9079   //  space of RHS.
9080   //  * unqualified types should be compatible.
9081   if (S.getLangOpts().OpenCL) {
9082     if (!S.Context.typesAreBlockPointerCompatible(
9083             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9084             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9085       return Sema::IncompatibleBlockPointer;
9086   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9087     return Sema::IncompatibleBlockPointer;
9088 
9089   return ConvTy;
9090 }
9091 
9092 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9093 /// for assignment compatibility.
9094 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)9095 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9096                                    QualType RHSType) {
9097   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9098   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9099 
9100   if (LHSType->isObjCBuiltinType()) {
9101     // Class is not compatible with ObjC object pointers.
9102     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9103         !RHSType->isObjCQualifiedClassType())
9104       return Sema::IncompatiblePointer;
9105     return Sema::Compatible;
9106   }
9107   if (RHSType->isObjCBuiltinType()) {
9108     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9109         !LHSType->isObjCQualifiedClassType())
9110       return Sema::IncompatiblePointer;
9111     return Sema::Compatible;
9112   }
9113   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9114   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9115 
9116   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9117       // make an exception for id<P>
9118       !LHSType->isObjCQualifiedIdType())
9119     return Sema::CompatiblePointerDiscardsQualifiers;
9120 
9121   if (S.Context.typesAreCompatible(LHSType, RHSType))
9122     return Sema::Compatible;
9123   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9124     return Sema::IncompatibleObjCQualifiedId;
9125   return Sema::IncompatiblePointer;
9126 }
9127 
9128 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)9129 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9130                                  QualType LHSType, QualType RHSType) {
9131   // Fake up an opaque expression.  We don't actually care about what
9132   // cast operations are required, so if CheckAssignmentConstraints
9133   // adds casts to this they'll be wasted, but fortunately that doesn't
9134   // usually happen on valid code.
9135   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9136   ExprResult RHSPtr = &RHSExpr;
9137   CastKind K;
9138 
9139   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9140 }
9141 
9142 /// This helper function returns true if QT is a vector type that has element
9143 /// type ElementType.
isVector(QualType QT,QualType ElementType)9144 static bool isVector(QualType QT, QualType ElementType) {
9145   if (const VectorType *VT = QT->getAs<VectorType>())
9146     return VT->getElementType().getCanonicalType() == ElementType;
9147   return false;
9148 }
9149 
9150 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9151 /// has code to accommodate several GCC extensions when type checking
9152 /// pointers. Here are some objectionable examples that GCC considers warnings:
9153 ///
9154 ///  int a, *pint;
9155 ///  short *pshort;
9156 ///  struct foo *pfoo;
9157 ///
9158 ///  pint = pshort; // warning: assignment from incompatible pointer type
9159 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9160 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9161 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9162 ///
9163 /// As a result, the code for dealing with pointers is more complex than the
9164 /// C99 spec dictates.
9165 ///
9166 /// Sets 'Kind' for any result kind except Incompatible.
9167 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)9168 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9169                                  CastKind &Kind, bool ConvertRHS) {
9170   QualType RHSType = RHS.get()->getType();
9171   QualType OrigLHSType = LHSType;
9172 
9173   // Get canonical types.  We're not formatting these types, just comparing
9174   // them.
9175   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9176   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9177 
9178   // Common case: no conversion required.
9179   if (LHSType == RHSType) {
9180     Kind = CK_NoOp;
9181     return Compatible;
9182   }
9183 
9184   // If we have an atomic type, try a non-atomic assignment, then just add an
9185   // atomic qualification step.
9186   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9187     Sema::AssignConvertType result =
9188       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9189     if (result != Compatible)
9190       return result;
9191     if (Kind != CK_NoOp && ConvertRHS)
9192       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9193     Kind = CK_NonAtomicToAtomic;
9194     return Compatible;
9195   }
9196 
9197   // If the left-hand side is a reference type, then we are in a
9198   // (rare!) case where we've allowed the use of references in C,
9199   // e.g., as a parameter type in a built-in function. In this case,
9200   // just make sure that the type referenced is compatible with the
9201   // right-hand side type. The caller is responsible for adjusting
9202   // LHSType so that the resulting expression does not have reference
9203   // type.
9204   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9205     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9206       Kind = CK_LValueBitCast;
9207       return Compatible;
9208     }
9209     return Incompatible;
9210   }
9211 
9212   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9213   // to the same ExtVector type.
9214   if (LHSType->isExtVectorType()) {
9215     if (RHSType->isExtVectorType())
9216       return Incompatible;
9217     if (RHSType->isArithmeticType()) {
9218       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9219       if (ConvertRHS)
9220         RHS = prepareVectorSplat(LHSType, RHS.get());
9221       Kind = CK_VectorSplat;
9222       return Compatible;
9223     }
9224   }
9225 
9226   // Conversions to or from vector type.
9227   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9228     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9229       // Allow assignments of an AltiVec vector type to an equivalent GCC
9230       // vector type and vice versa
9231       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9232         Kind = CK_BitCast;
9233         return Compatible;
9234       }
9235 
9236       // If we are allowing lax vector conversions, and LHS and RHS are both
9237       // vectors, the total size only needs to be the same. This is a bitcast;
9238       // no bits are changed but the result type is different.
9239       if (isLaxVectorConversion(RHSType, LHSType)) {
9240         Kind = CK_BitCast;
9241         return IncompatibleVectors;
9242       }
9243     }
9244 
9245     // When the RHS comes from another lax conversion (e.g. binops between
9246     // scalars and vectors) the result is canonicalized as a vector. When the
9247     // LHS is also a vector, the lax is allowed by the condition above. Handle
9248     // the case where LHS is a scalar.
9249     if (LHSType->isScalarType()) {
9250       const VectorType *VecType = RHSType->getAs<VectorType>();
9251       if (VecType && VecType->getNumElements() == 1 &&
9252           isLaxVectorConversion(RHSType, LHSType)) {
9253         ExprResult *VecExpr = &RHS;
9254         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9255         Kind = CK_BitCast;
9256         return Compatible;
9257       }
9258     }
9259 
9260     // Allow assignments between fixed-length and sizeless SVE vectors.
9261     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9262         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9263       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9264           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9265         Kind = CK_BitCast;
9266         return Compatible;
9267       }
9268 
9269     return Incompatible;
9270   }
9271 
9272   // Diagnose attempts to convert between __float128 and long double where
9273   // such conversions currently can't be handled.
9274   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9275     return Incompatible;
9276 
9277   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9278   // discards the imaginary part.
9279   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9280       !LHSType->getAs<ComplexType>())
9281     return Incompatible;
9282 
9283   // Arithmetic conversions.
9284   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9285       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9286     if (ConvertRHS)
9287       Kind = PrepareScalarCast(RHS, LHSType);
9288     return Compatible;
9289   }
9290 
9291   // Conversions to normal pointers.
9292   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9293     // U* -> T*
9294     if (isa<PointerType>(RHSType)) {
9295       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9296       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9297       if (AddrSpaceL != AddrSpaceR)
9298         Kind = CK_AddressSpaceConversion;
9299       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9300         Kind = CK_NoOp;
9301       else
9302         Kind = CK_BitCast;
9303       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9304     }
9305 
9306     // int -> T*
9307     if (RHSType->isIntegerType()) {
9308       Kind = CK_IntegralToPointer; // FIXME: null?
9309       return IntToPointer;
9310     }
9311 
9312     // C pointers are not compatible with ObjC object pointers,
9313     // with two exceptions:
9314     if (isa<ObjCObjectPointerType>(RHSType)) {
9315       //  - conversions to void*
9316       if (LHSPointer->getPointeeType()->isVoidType()) {
9317         Kind = CK_BitCast;
9318         return Compatible;
9319       }
9320 
9321       //  - conversions from 'Class' to the redefinition type
9322       if (RHSType->isObjCClassType() &&
9323           Context.hasSameType(LHSType,
9324                               Context.getObjCClassRedefinitionType())) {
9325         Kind = CK_BitCast;
9326         return Compatible;
9327       }
9328 
9329       Kind = CK_BitCast;
9330       return IncompatiblePointer;
9331     }
9332 
9333     // U^ -> void*
9334     if (RHSType->getAs<BlockPointerType>()) {
9335       if (LHSPointer->getPointeeType()->isVoidType()) {
9336         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9337         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9338                                 ->getPointeeType()
9339                                 .getAddressSpace();
9340         Kind =
9341             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9342         return Compatible;
9343       }
9344     }
9345 
9346     return Incompatible;
9347   }
9348 
9349   // Conversions to block pointers.
9350   if (isa<BlockPointerType>(LHSType)) {
9351     // U^ -> T^
9352     if (RHSType->isBlockPointerType()) {
9353       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9354                               ->getPointeeType()
9355                               .getAddressSpace();
9356       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9357                               ->getPointeeType()
9358                               .getAddressSpace();
9359       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9360       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9361     }
9362 
9363     // int or null -> T^
9364     if (RHSType->isIntegerType()) {
9365       Kind = CK_IntegralToPointer; // FIXME: null
9366       return IntToBlockPointer;
9367     }
9368 
9369     // id -> T^
9370     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9371       Kind = CK_AnyPointerToBlockPointerCast;
9372       return Compatible;
9373     }
9374 
9375     // void* -> T^
9376     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9377       if (RHSPT->getPointeeType()->isVoidType()) {
9378         Kind = CK_AnyPointerToBlockPointerCast;
9379         return Compatible;
9380       }
9381 
9382     return Incompatible;
9383   }
9384 
9385   // Conversions to Objective-C pointers.
9386   if (isa<ObjCObjectPointerType>(LHSType)) {
9387     // A* -> B*
9388     if (RHSType->isObjCObjectPointerType()) {
9389       Kind = CK_BitCast;
9390       Sema::AssignConvertType result =
9391         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9392       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9393           result == Compatible &&
9394           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9395         result = IncompatibleObjCWeakRef;
9396       return result;
9397     }
9398 
9399     // int or null -> A*
9400     if (RHSType->isIntegerType()) {
9401       Kind = CK_IntegralToPointer; // FIXME: null
9402       return IntToPointer;
9403     }
9404 
9405     // In general, C pointers are not compatible with ObjC object pointers,
9406     // with two exceptions:
9407     if (isa<PointerType>(RHSType)) {
9408       Kind = CK_CPointerToObjCPointerCast;
9409 
9410       //  - conversions from 'void*'
9411       if (RHSType->isVoidPointerType()) {
9412         return Compatible;
9413       }
9414 
9415       //  - conversions to 'Class' from its redefinition type
9416       if (LHSType->isObjCClassType() &&
9417           Context.hasSameType(RHSType,
9418                               Context.getObjCClassRedefinitionType())) {
9419         return Compatible;
9420       }
9421 
9422       return IncompatiblePointer;
9423     }
9424 
9425     // Only under strict condition T^ is compatible with an Objective-C pointer.
9426     if (RHSType->isBlockPointerType() &&
9427         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9428       if (ConvertRHS)
9429         maybeExtendBlockObject(RHS);
9430       Kind = CK_BlockPointerToObjCPointerCast;
9431       return Compatible;
9432     }
9433 
9434     return Incompatible;
9435   }
9436 
9437   // Conversions from pointers that are not covered by the above.
9438   if (isa<PointerType>(RHSType)) {
9439     // T* -> _Bool
9440     if (LHSType == Context.BoolTy) {
9441       Kind = CK_PointerToBoolean;
9442       return Compatible;
9443     }
9444 
9445     // T* -> int
9446     if (LHSType->isIntegerType()) {
9447       Kind = CK_PointerToIntegral;
9448       return PointerToInt;
9449     }
9450 
9451     return Incompatible;
9452   }
9453 
9454   // Conversions from Objective-C pointers that are not covered by the above.
9455   if (isa<ObjCObjectPointerType>(RHSType)) {
9456     // T* -> _Bool
9457     if (LHSType == Context.BoolTy) {
9458       Kind = CK_PointerToBoolean;
9459       return Compatible;
9460     }
9461 
9462     // T* -> int
9463     if (LHSType->isIntegerType()) {
9464       Kind = CK_PointerToIntegral;
9465       return PointerToInt;
9466     }
9467 
9468     return Incompatible;
9469   }
9470 
9471   // struct A -> struct B
9472   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9473     if (Context.typesAreCompatible(LHSType, RHSType)) {
9474       Kind = CK_NoOp;
9475       return Compatible;
9476     }
9477   }
9478 
9479   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9480     Kind = CK_IntToOCLSampler;
9481     return Compatible;
9482   }
9483 
9484   return Incompatible;
9485 }
9486 
9487 /// Constructs a transparent union from an expression that is
9488 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)9489 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9490                                       ExprResult &EResult, QualType UnionType,
9491                                       FieldDecl *Field) {
9492   // Build an initializer list that designates the appropriate member
9493   // of the transparent union.
9494   Expr *E = EResult.get();
9495   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9496                                                    E, SourceLocation());
9497   Initializer->setType(UnionType);
9498   Initializer->setInitializedFieldInUnion(Field);
9499 
9500   // Build a compound literal constructing a value of the transparent
9501   // union type from this initializer list.
9502   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9503   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9504                                         VK_PRValue, Initializer, false);
9505 }
9506 
9507 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)9508 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9509                                                ExprResult &RHS) {
9510   QualType RHSType = RHS.get()->getType();
9511 
9512   // If the ArgType is a Union type, we want to handle a potential
9513   // transparent_union GCC extension.
9514   const RecordType *UT = ArgType->getAsUnionType();
9515   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9516     return Incompatible;
9517 
9518   // The field to initialize within the transparent union.
9519   RecordDecl *UD = UT->getDecl();
9520   FieldDecl *InitField = nullptr;
9521   // It's compatible if the expression matches any of the fields.
9522   for (auto *it : UD->fields()) {
9523     if (it->getType()->isPointerType()) {
9524       // If the transparent union contains a pointer type, we allow:
9525       // 1) void pointer
9526       // 2) null pointer constant
9527       if (RHSType->isPointerType())
9528         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9529           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9530           InitField = it;
9531           break;
9532         }
9533 
9534       if (RHS.get()->isNullPointerConstant(Context,
9535                                            Expr::NPC_ValueDependentIsNull)) {
9536         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9537                                 CK_NullToPointer);
9538         InitField = it;
9539         break;
9540       }
9541     }
9542 
9543     CastKind Kind;
9544     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9545           == Compatible) {
9546       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9547       InitField = it;
9548       break;
9549     }
9550   }
9551 
9552   if (!InitField)
9553     return Incompatible;
9554 
9555   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9556   return Compatible;
9557 }
9558 
9559 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)9560 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9561                                        bool Diagnose,
9562                                        bool DiagnoseCFAudited,
9563                                        bool ConvertRHS) {
9564   // We need to be able to tell the caller whether we diagnosed a problem, if
9565   // they ask us to issue diagnostics.
9566   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9567 
9568   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9569   // we can't avoid *all* modifications at the moment, so we need some somewhere
9570   // to put the updated value.
9571   ExprResult LocalRHS = CallerRHS;
9572   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9573 
9574   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9575     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9576       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9577           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9578         Diag(RHS.get()->getExprLoc(),
9579              diag::warn_noderef_to_dereferenceable_pointer)
9580             << RHS.get()->getSourceRange();
9581       }
9582     }
9583   }
9584 
9585   if (getLangOpts().CPlusPlus) {
9586     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9587       // C++ 5.17p3: If the left operand is not of class type, the
9588       // expression is implicitly converted (C++ 4) to the
9589       // cv-unqualified type of the left operand.
9590       QualType RHSType = RHS.get()->getType();
9591       if (Diagnose) {
9592         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9593                                         AA_Assigning);
9594       } else {
9595         ImplicitConversionSequence ICS =
9596             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9597                                   /*SuppressUserConversions=*/false,
9598                                   AllowedExplicit::None,
9599                                   /*InOverloadResolution=*/false,
9600                                   /*CStyle=*/false,
9601                                   /*AllowObjCWritebackConversion=*/false);
9602         if (ICS.isFailure())
9603           return Incompatible;
9604         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9605                                         ICS, AA_Assigning);
9606       }
9607       if (RHS.isInvalid())
9608         return Incompatible;
9609       Sema::AssignConvertType result = Compatible;
9610       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9611           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9612         result = IncompatibleObjCWeakRef;
9613       return result;
9614     }
9615 
9616     // FIXME: Currently, we fall through and treat C++ classes like C
9617     // structures.
9618     // FIXME: We also fall through for atomics; not sure what should
9619     // happen there, though.
9620   } else if (RHS.get()->getType() == Context.OverloadTy) {
9621     // As a set of extensions to C, we support overloading on functions. These
9622     // functions need to be resolved here.
9623     DeclAccessPair DAP;
9624     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9625             RHS.get(), LHSType, /*Complain=*/false, DAP))
9626       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9627     else
9628       return Incompatible;
9629   }
9630 
9631   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9632   // a null pointer constant.
9633   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9634        LHSType->isBlockPointerType()) &&
9635       RHS.get()->isNullPointerConstant(Context,
9636                                        Expr::NPC_ValueDependentIsNull)) {
9637     if (Diagnose || ConvertRHS) {
9638       CastKind Kind;
9639       CXXCastPath Path;
9640       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9641                              /*IgnoreBaseAccess=*/false, Diagnose);
9642       if (ConvertRHS)
9643         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9644     }
9645     return Compatible;
9646   }
9647 
9648   // OpenCL queue_t type assignment.
9649   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9650                                  Context, Expr::NPC_ValueDependentIsNull)) {
9651     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9652     return Compatible;
9653   }
9654 
9655   // This check seems unnatural, however it is necessary to ensure the proper
9656   // conversion of functions/arrays. If the conversion were done for all
9657   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9658   // expressions that suppress this implicit conversion (&, sizeof).
9659   //
9660   // Suppress this for references: C++ 8.5.3p5.
9661   if (!LHSType->isReferenceType()) {
9662     // FIXME: We potentially allocate here even if ConvertRHS is false.
9663     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9664     if (RHS.isInvalid())
9665       return Incompatible;
9666   }
9667   CastKind Kind;
9668   Sema::AssignConvertType result =
9669     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9670 
9671   // C99 6.5.16.1p2: The value of the right operand is converted to the
9672   // type of the assignment expression.
9673   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9674   // so that we can use references in built-in functions even in C.
9675   // The getNonReferenceType() call makes sure that the resulting expression
9676   // does not have reference type.
9677   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9678     QualType Ty = LHSType.getNonLValueExprType(Context);
9679     Expr *E = RHS.get();
9680 
9681     // Check for various Objective-C errors. If we are not reporting
9682     // diagnostics and just checking for errors, e.g., during overload
9683     // resolution, return Incompatible to indicate the failure.
9684     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9685         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9686                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9687       if (!Diagnose)
9688         return Incompatible;
9689     }
9690     if (getLangOpts().ObjC &&
9691         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9692                                            E->getType(), E, Diagnose) ||
9693          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9694       if (!Diagnose)
9695         return Incompatible;
9696       // Replace the expression with a corrected version and continue so we
9697       // can find further errors.
9698       RHS = E;
9699       return Compatible;
9700     }
9701 
9702     if (ConvertRHS)
9703       RHS = ImpCastExprToType(E, Ty, Kind);
9704   }
9705 
9706   return result;
9707 }
9708 
9709 namespace {
9710 /// The original operand to an operator, prior to the application of the usual
9711 /// arithmetic conversions and converting the arguments of a builtin operator
9712 /// candidate.
9713 struct OriginalOperand {
OriginalOperand__anon446c58fa0c11::OriginalOperand9714   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9715     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9716       Op = MTE->getSubExpr();
9717     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9718       Op = BTE->getSubExpr();
9719     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9720       Orig = ICE->getSubExprAsWritten();
9721       Conversion = ICE->getConversionFunction();
9722     }
9723   }
9724 
getType__anon446c58fa0c11::OriginalOperand9725   QualType getType() const { return Orig->getType(); }
9726 
9727   Expr *Orig;
9728   NamedDecl *Conversion;
9729 };
9730 }
9731 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9732 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9733                                ExprResult &RHS) {
9734   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9735 
9736   Diag(Loc, diag::err_typecheck_invalid_operands)
9737     << OrigLHS.getType() << OrigRHS.getType()
9738     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9739 
9740   // If a user-defined conversion was applied to either of the operands prior
9741   // to applying the built-in operator rules, tell the user about it.
9742   if (OrigLHS.Conversion) {
9743     Diag(OrigLHS.Conversion->getLocation(),
9744          diag::note_typecheck_invalid_operands_converted)
9745       << 0 << LHS.get()->getType();
9746   }
9747   if (OrigRHS.Conversion) {
9748     Diag(OrigRHS.Conversion->getLocation(),
9749          diag::note_typecheck_invalid_operands_converted)
9750       << 1 << RHS.get()->getType();
9751   }
9752 
9753   return QualType();
9754 }
9755 
9756 // Diagnose cases where a scalar was implicitly converted to a vector and
9757 // diagnose the underlying types. Otherwise, diagnose the error
9758 // as invalid vector logical operands for non-C++ cases.
InvalidLogicalVectorOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9759 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9760                                             ExprResult &RHS) {
9761   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9762   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9763 
9764   bool LHSNatVec = LHSType->isVectorType();
9765   bool RHSNatVec = RHSType->isVectorType();
9766 
9767   if (!(LHSNatVec && RHSNatVec)) {
9768     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9769     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9770     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9771         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9772         << Vector->getSourceRange();
9773     return QualType();
9774   }
9775 
9776   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9777       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9778       << RHS.get()->getSourceRange();
9779 
9780   return QualType();
9781 }
9782 
9783 /// Try to convert a value of non-vector type to a vector type by converting
9784 /// the type to the element type of the vector and then performing a splat.
9785 /// If the language is OpenCL, we only use conversions that promote scalar
9786 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9787 /// for float->int.
9788 ///
9789 /// OpenCL V2.0 6.2.6.p2:
9790 /// An error shall occur if any scalar operand type has greater rank
9791 /// than the type of the vector element.
9792 ///
9793 /// \param scalar - if non-null, actually perform the conversions
9794 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy,unsigned & DiagID)9795 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9796                                      QualType scalarTy,
9797                                      QualType vectorEltTy,
9798                                      QualType vectorTy,
9799                                      unsigned &DiagID) {
9800   // The conversion to apply to the scalar before splatting it,
9801   // if necessary.
9802   CastKind scalarCast = CK_NoOp;
9803 
9804   if (vectorEltTy->isIntegralType(S.Context)) {
9805     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9806         (scalarTy->isIntegerType() &&
9807          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9808       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9809       return true;
9810     }
9811     if (!scalarTy->isIntegralType(S.Context))
9812       return true;
9813     scalarCast = CK_IntegralCast;
9814   } else if (vectorEltTy->isRealFloatingType()) {
9815     if (scalarTy->isRealFloatingType()) {
9816       if (S.getLangOpts().OpenCL &&
9817           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9818         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9819         return true;
9820       }
9821       scalarCast = CK_FloatingCast;
9822     }
9823     else if (scalarTy->isIntegralType(S.Context))
9824       scalarCast = CK_IntegralToFloating;
9825     else
9826       return true;
9827   } else {
9828     return true;
9829   }
9830 
9831   // Adjust scalar if desired.
9832   if (scalar) {
9833     if (scalarCast != CK_NoOp)
9834       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9835     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9836   }
9837   return false;
9838 }
9839 
9840 /// Convert vector E to a vector with the same number of elements but different
9841 /// element type.
convertVector(Expr * E,QualType ElementType,Sema & S)9842 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9843   const auto *VecTy = E->getType()->getAs<VectorType>();
9844   assert(VecTy && "Expression E must be a vector");
9845   QualType NewVecTy = S.Context.getVectorType(ElementType,
9846                                               VecTy->getNumElements(),
9847                                               VecTy->getVectorKind());
9848 
9849   // Look through the implicit cast. Return the subexpression if its type is
9850   // NewVecTy.
9851   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9852     if (ICE->getSubExpr()->getType() == NewVecTy)
9853       return ICE->getSubExpr();
9854 
9855   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9856   return S.ImpCastExprToType(E, NewVecTy, Cast);
9857 }
9858 
9859 /// Test if a (constant) integer Int can be casted to another integer type
9860 /// IntTy without losing precision.
canConvertIntToOtherIntTy(Sema & S,ExprResult * Int,QualType OtherIntTy)9861 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9862                                       QualType OtherIntTy) {
9863   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9864 
9865   // Reject cases where the value of the Int is unknown as that would
9866   // possibly cause truncation, but accept cases where the scalar can be
9867   // demoted without loss of precision.
9868   Expr::EvalResult EVResult;
9869   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9870   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9871   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9872   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9873 
9874   if (CstInt) {
9875     // If the scalar is constant and is of a higher order and has more active
9876     // bits that the vector element type, reject it.
9877     llvm::APSInt Result = EVResult.Val.getInt();
9878     unsigned NumBits = IntSigned
9879                            ? (Result.isNegative() ? Result.getMinSignedBits()
9880                                                   : Result.getActiveBits())
9881                            : Result.getActiveBits();
9882     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9883       return true;
9884 
9885     // If the signedness of the scalar type and the vector element type
9886     // differs and the number of bits is greater than that of the vector
9887     // element reject it.
9888     return (IntSigned != OtherIntSigned &&
9889             NumBits > S.Context.getIntWidth(OtherIntTy));
9890   }
9891 
9892   // Reject cases where the value of the scalar is not constant and it's
9893   // order is greater than that of the vector element type.
9894   return (Order < 0);
9895 }
9896 
9897 /// Test if a (constant) integer Int can be casted to floating point type
9898 /// FloatTy without losing precision.
canConvertIntTyToFloatTy(Sema & S,ExprResult * Int,QualType FloatTy)9899 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9900                                      QualType FloatTy) {
9901   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9902 
9903   // Determine if the integer constant can be expressed as a floating point
9904   // number of the appropriate type.
9905   Expr::EvalResult EVResult;
9906   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9907 
9908   uint64_t Bits = 0;
9909   if (CstInt) {
9910     // Reject constants that would be truncated if they were converted to
9911     // the floating point type. Test by simple to/from conversion.
9912     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9913     //        could be avoided if there was a convertFromAPInt method
9914     //        which could signal back if implicit truncation occurred.
9915     llvm::APSInt Result = EVResult.Val.getInt();
9916     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9917     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9918                            llvm::APFloat::rmTowardZero);
9919     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9920                              !IntTy->hasSignedIntegerRepresentation());
9921     bool Ignored = false;
9922     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9923                            &Ignored);
9924     if (Result != ConvertBack)
9925       return true;
9926   } else {
9927     // Reject types that cannot be fully encoded into the mantissa of
9928     // the float.
9929     Bits = S.Context.getTypeSize(IntTy);
9930     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9931         S.Context.getFloatTypeSemantics(FloatTy));
9932     if (Bits > FloatPrec)
9933       return true;
9934   }
9935 
9936   return false;
9937 }
9938 
9939 /// Attempt to convert and splat Scalar into a vector whose types matches
9940 /// Vector following GCC conversion rules. The rule is that implicit
9941 /// conversion can occur when Scalar can be casted to match Vector's element
9942 /// type without causing truncation of Scalar.
tryGCCVectorConvertAndSplat(Sema & S,ExprResult * Scalar,ExprResult * Vector)9943 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9944                                         ExprResult *Vector) {
9945   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9946   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9947   const VectorType *VT = VectorTy->getAs<VectorType>();
9948 
9949   assert(!isa<ExtVectorType>(VT) &&
9950          "ExtVectorTypes should not be handled here!");
9951 
9952   QualType VectorEltTy = VT->getElementType();
9953 
9954   // Reject cases where the vector element type or the scalar element type are
9955   // not integral or floating point types.
9956   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9957     return true;
9958 
9959   // The conversion to apply to the scalar before splatting it,
9960   // if necessary.
9961   CastKind ScalarCast = CK_NoOp;
9962 
9963   // Accept cases where the vector elements are integers and the scalar is
9964   // an integer.
9965   // FIXME: Notionally if the scalar was a floating point value with a precise
9966   //        integral representation, we could cast it to an appropriate integer
9967   //        type and then perform the rest of the checks here. GCC will perform
9968   //        this conversion in some cases as determined by the input language.
9969   //        We should accept it on a language independent basis.
9970   if (VectorEltTy->isIntegralType(S.Context) &&
9971       ScalarTy->isIntegralType(S.Context) &&
9972       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9973 
9974     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9975       return true;
9976 
9977     ScalarCast = CK_IntegralCast;
9978   } else if (VectorEltTy->isIntegralType(S.Context) &&
9979              ScalarTy->isRealFloatingType()) {
9980     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9981       ScalarCast = CK_FloatingToIntegral;
9982     else
9983       return true;
9984   } else if (VectorEltTy->isRealFloatingType()) {
9985     if (ScalarTy->isRealFloatingType()) {
9986 
9987       // Reject cases where the scalar type is not a constant and has a higher
9988       // Order than the vector element type.
9989       llvm::APFloat Result(0.0);
9990 
9991       // Determine whether this is a constant scalar. In the event that the
9992       // value is dependent (and thus cannot be evaluated by the constant
9993       // evaluator), skip the evaluation. This will then diagnose once the
9994       // expression is instantiated.
9995       bool CstScalar = Scalar->get()->isValueDependent() ||
9996                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9997       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9998       if (!CstScalar && Order < 0)
9999         return true;
10000 
10001       // If the scalar cannot be safely casted to the vector element type,
10002       // reject it.
10003       if (CstScalar) {
10004         bool Truncated = false;
10005         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10006                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10007         if (Truncated)
10008           return true;
10009       }
10010 
10011       ScalarCast = CK_FloatingCast;
10012     } else if (ScalarTy->isIntegralType(S.Context)) {
10013       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10014         return true;
10015 
10016       ScalarCast = CK_IntegralToFloating;
10017     } else
10018       return true;
10019   } else if (ScalarTy->isEnumeralType())
10020     return true;
10021 
10022   // Adjust scalar if desired.
10023   if (Scalar) {
10024     if (ScalarCast != CK_NoOp)
10025       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10026     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10027   }
10028   return false;
10029 }
10030 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)10031 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10032                                    SourceLocation Loc, bool IsCompAssign,
10033                                    bool AllowBothBool,
10034                                    bool AllowBoolConversions) {
10035   if (!IsCompAssign) {
10036     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10037     if (LHS.isInvalid())
10038       return QualType();
10039   }
10040   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10041   if (RHS.isInvalid())
10042     return QualType();
10043 
10044   // For conversion purposes, we ignore any qualifiers.
10045   // For example, "const float" and "float" are equivalent.
10046   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10047   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10048 
10049   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10050   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10051   assert(LHSVecType || RHSVecType);
10052 
10053   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10054       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10055     return InvalidOperands(Loc, LHS, RHS);
10056 
10057   // AltiVec-style "vector bool op vector bool" combinations are allowed
10058   // for some operators but not others.
10059   if (!AllowBothBool &&
10060       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10061       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10062     return InvalidOperands(Loc, LHS, RHS);
10063 
10064   // If the vector types are identical, return.
10065   if (Context.hasSameType(LHSType, RHSType))
10066     return LHSType;
10067 
10068   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10069   if (LHSVecType && RHSVecType &&
10070       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10071     if (isa<ExtVectorType>(LHSVecType)) {
10072       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10073       return LHSType;
10074     }
10075 
10076     if (!IsCompAssign)
10077       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10078     return RHSType;
10079   }
10080 
10081   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10082   // can be mixed, with the result being the non-bool type.  The non-bool
10083   // operand must have integer element type.
10084   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10085       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10086       (Context.getTypeSize(LHSVecType->getElementType()) ==
10087        Context.getTypeSize(RHSVecType->getElementType()))) {
10088     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10089         LHSVecType->getElementType()->isIntegerType() &&
10090         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10091       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10092       return LHSType;
10093     }
10094     if (!IsCompAssign &&
10095         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10096         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10097         RHSVecType->getElementType()->isIntegerType()) {
10098       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10099       return RHSType;
10100     }
10101   }
10102 
10103   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10104   // since the ambiguity can affect the ABI.
10105   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10106     const VectorType *VecType = SecondType->getAs<VectorType>();
10107     return FirstType->isSizelessBuiltinType() && VecType &&
10108            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10109             VecType->getVectorKind() ==
10110                 VectorType::SveFixedLengthPredicateVector);
10111   };
10112 
10113   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10114     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10115     return QualType();
10116   }
10117 
10118   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10119   // since the ambiguity can affect the ABI.
10120   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10121     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10122     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10123 
10124     if (FirstVecType && SecondVecType)
10125       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10126              (SecondVecType->getVectorKind() ==
10127                   VectorType::SveFixedLengthDataVector ||
10128               SecondVecType->getVectorKind() ==
10129                   VectorType::SveFixedLengthPredicateVector);
10130 
10131     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10132            SecondVecType->getVectorKind() == VectorType::GenericVector;
10133   };
10134 
10135   if (IsSveGnuConversion(LHSType, RHSType) ||
10136       IsSveGnuConversion(RHSType, LHSType)) {
10137     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10138     return QualType();
10139   }
10140 
10141   // If there's a vector type and a scalar, try to convert the scalar to
10142   // the vector element type and splat.
10143   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10144   if (!RHSVecType) {
10145     if (isa<ExtVectorType>(LHSVecType)) {
10146       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10147                                     LHSVecType->getElementType(), LHSType,
10148                                     DiagID))
10149         return LHSType;
10150     } else {
10151       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10152         return LHSType;
10153     }
10154   }
10155   if (!LHSVecType) {
10156     if (isa<ExtVectorType>(RHSVecType)) {
10157       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10158                                     LHSType, RHSVecType->getElementType(),
10159                                     RHSType, DiagID))
10160         return RHSType;
10161     } else {
10162       if (LHS.get()->isLValue() ||
10163           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10164         return RHSType;
10165     }
10166   }
10167 
10168   // FIXME: The code below also handles conversion between vectors and
10169   // non-scalars, we should break this down into fine grained specific checks
10170   // and emit proper diagnostics.
10171   QualType VecType = LHSVecType ? LHSType : RHSType;
10172   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10173   QualType OtherType = LHSVecType ? RHSType : LHSType;
10174   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10175   if (isLaxVectorConversion(OtherType, VecType)) {
10176     // If we're allowing lax vector conversions, only the total (data) size
10177     // needs to be the same. For non compound assignment, if one of the types is
10178     // scalar, the result is always the vector type.
10179     if (!IsCompAssign) {
10180       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10181       return VecType;
10182     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10183     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10184     // type. Note that this is already done by non-compound assignments in
10185     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10186     // <1 x T> -> T. The result is also a vector type.
10187     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10188                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10189       ExprResult *RHSExpr = &RHS;
10190       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10191       return VecType;
10192     }
10193   }
10194 
10195   // Okay, the expression is invalid.
10196 
10197   // If there's a non-vector, non-real operand, diagnose that.
10198   if ((!RHSVecType && !RHSType->isRealType()) ||
10199       (!LHSVecType && !LHSType->isRealType())) {
10200     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10201       << LHSType << RHSType
10202       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10203     return QualType();
10204   }
10205 
10206   // OpenCL V1.1 6.2.6.p1:
10207   // If the operands are of more than one vector type, then an error shall
10208   // occur. Implicit conversions between vector types are not permitted, per
10209   // section 6.2.1.
10210   if (getLangOpts().OpenCL &&
10211       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10212       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10213     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10214                                                            << RHSType;
10215     return QualType();
10216   }
10217 
10218 
10219   // If there is a vector type that is not a ExtVector and a scalar, we reach
10220   // this point if scalar could not be converted to the vector's element type
10221   // without truncation.
10222   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10223       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10224     QualType Scalar = LHSVecType ? RHSType : LHSType;
10225     QualType Vector = LHSVecType ? LHSType : RHSType;
10226     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10227     Diag(Loc,
10228          diag::err_typecheck_vector_not_convertable_implict_truncation)
10229         << ScalarOrVector << Scalar << Vector;
10230 
10231     return QualType();
10232   }
10233 
10234   // Otherwise, use the generic diagnostic.
10235   Diag(Loc, DiagID)
10236     << LHSType << RHSType
10237     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10238   return QualType();
10239 }
10240 
10241 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10242 // expression.  These are mainly cases where the null pointer is used as an
10243 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)10244 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10245                                 SourceLocation Loc, bool IsCompare) {
10246   // The canonical way to check for a GNU null is with isNullPointerConstant,
10247   // but we use a bit of a hack here for speed; this is a relatively
10248   // hot path, and isNullPointerConstant is slow.
10249   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10250   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10251 
10252   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10253 
10254   // Avoid analyzing cases where the result will either be invalid (and
10255   // diagnosed as such) or entirely valid and not something to warn about.
10256   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10257       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10258     return;
10259 
10260   // Comparison operations would not make sense with a null pointer no matter
10261   // what the other expression is.
10262   if (!IsCompare) {
10263     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10264         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10265         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10266     return;
10267   }
10268 
10269   // The rest of the operations only make sense with a null pointer
10270   // if the other expression is a pointer.
10271   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10272       NonNullType->canDecayToPointerType())
10273     return;
10274 
10275   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10276       << LHSNull /* LHS is NULL */ << NonNullType
10277       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10278 }
10279 
DiagnoseDivisionSizeofPointerOrArray(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc)10280 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10281                                           SourceLocation Loc) {
10282   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10283   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10284   if (!LUE || !RUE)
10285     return;
10286   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10287       RUE->getKind() != UETT_SizeOf)
10288     return;
10289 
10290   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10291   QualType LHSTy = LHSArg->getType();
10292   QualType RHSTy;
10293 
10294   if (RUE->isArgumentType())
10295     RHSTy = RUE->getArgumentType().getNonReferenceType();
10296   else
10297     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10298 
10299   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10300     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10301       return;
10302 
10303     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10304     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10305       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10306         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10307             << LHSArgDecl;
10308     }
10309   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10310     QualType ArrayElemTy = ArrayTy->getElementType();
10311     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10312         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10313         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10314         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10315       return;
10316     S.Diag(Loc, diag::warn_division_sizeof_array)
10317         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10318     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10319       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10320         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10321             << LHSArgDecl;
10322     }
10323 
10324     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10325   }
10326 }
10327 
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)10328 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10329                                                ExprResult &RHS,
10330                                                SourceLocation Loc, bool IsDiv) {
10331   // Check for division/remainder by zero.
10332   Expr::EvalResult RHSValue;
10333   if (!RHS.get()->isValueDependent() &&
10334       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10335       RHSValue.Val.getInt() == 0)
10336     S.DiagRuntimeBehavior(Loc, RHS.get(),
10337                           S.PDiag(diag::warn_remainder_division_by_zero)
10338                             << IsDiv << RHS.get()->getSourceRange());
10339 }
10340 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)10341 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10342                                            SourceLocation Loc,
10343                                            bool IsCompAssign, bool IsDiv) {
10344   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10345 
10346   QualType LHSTy = LHS.get()->getType();
10347   QualType RHSTy = RHS.get()->getType();
10348   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10349     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10350                                /*AllowBothBool*/getLangOpts().AltiVec,
10351                                /*AllowBoolConversions*/false);
10352   if (!IsDiv &&
10353       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10354     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10355   // For division, only matrix-by-scalar is supported. Other combinations with
10356   // matrix types are invalid.
10357   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10358     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10359 
10360   QualType compType = UsualArithmeticConversions(
10361       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10362   if (LHS.isInvalid() || RHS.isInvalid())
10363     return QualType();
10364 
10365 
10366   if (compType.isNull() || !compType->isArithmeticType())
10367     return InvalidOperands(Loc, LHS, RHS);
10368   if (IsDiv) {
10369     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10370     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10371   }
10372   return compType;
10373 }
10374 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10375 QualType Sema::CheckRemainderOperands(
10376   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10377   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10378 
10379   if (LHS.get()->getType()->isVectorType() ||
10380       RHS.get()->getType()->isVectorType()) {
10381     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10382         RHS.get()->getType()->hasIntegerRepresentation())
10383       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10384                                  /*AllowBothBool*/getLangOpts().AltiVec,
10385                                  /*AllowBoolConversions*/false);
10386     return InvalidOperands(Loc, LHS, RHS);
10387   }
10388 
10389   QualType compType = UsualArithmeticConversions(
10390       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10391   if (LHS.isInvalid() || RHS.isInvalid())
10392     return QualType();
10393 
10394   if (compType.isNull() || !compType->isIntegerType())
10395     return InvalidOperands(Loc, LHS, RHS);
10396   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10397   return compType;
10398 }
10399 
10400 /// Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10401 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10402                                                 Expr *LHSExpr, Expr *RHSExpr) {
10403   S.Diag(Loc, S.getLangOpts().CPlusPlus
10404                 ? diag::err_typecheck_pointer_arith_void_type
10405                 : diag::ext_gnu_void_ptr)
10406     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10407                             << RHSExpr->getSourceRange();
10408 }
10409 
10410 /// Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10411 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10412                                             Expr *Pointer) {
10413   S.Diag(Loc, S.getLangOpts().CPlusPlus
10414                 ? diag::err_typecheck_pointer_arith_void_type
10415                 : diag::ext_gnu_void_ptr)
10416     << 0 /* one pointer */ << Pointer->getSourceRange();
10417 }
10418 
10419 /// Diagnose invalid arithmetic on a null pointer.
10420 ///
10421 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10422 /// idiom, which we recognize as a GNU extension.
10423 ///
diagnoseArithmeticOnNullPointer(Sema & S,SourceLocation Loc,Expr * Pointer,bool IsGNUIdiom)10424 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10425                                             Expr *Pointer, bool IsGNUIdiom) {
10426   if (IsGNUIdiom)
10427     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10428       << Pointer->getSourceRange();
10429   else
10430     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10431       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10432 }
10433 
10434 /// Diagnose invalid subraction on a null pointer.
10435 ///
diagnoseSubtractionOnNullPointer(Sema & S,SourceLocation Loc,Expr * Pointer,bool BothNull)10436 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10437                                              Expr *Pointer, bool BothNull) {
10438   // Null - null is valid in C++ [expr.add]p7
10439   if (BothNull && S.getLangOpts().CPlusPlus)
10440     return;
10441 
10442   // Is this s a macro from a system header?
10443   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10444     return;
10445 
10446   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10447       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10448 }
10449 
10450 /// Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)10451 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10452                                                     Expr *LHS, Expr *RHS) {
10453   assert(LHS->getType()->isAnyPointerType());
10454   assert(RHS->getType()->isAnyPointerType());
10455   S.Diag(Loc, S.getLangOpts().CPlusPlus
10456                 ? diag::err_typecheck_pointer_arith_function_type
10457                 : diag::ext_gnu_ptr_func_arith)
10458     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10459     // We only show the second type if it differs from the first.
10460     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10461                                                    RHS->getType())
10462     << RHS->getType()->getPointeeType()
10463     << LHS->getSourceRange() << RHS->getSourceRange();
10464 }
10465 
10466 /// Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10467 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10468                                                 Expr *Pointer) {
10469   assert(Pointer->getType()->isAnyPointerType());
10470   S.Diag(Loc, S.getLangOpts().CPlusPlus
10471                 ? diag::err_typecheck_pointer_arith_function_type
10472                 : diag::ext_gnu_ptr_func_arith)
10473     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10474     << 0 /* one pointer, so only one type */
10475     << Pointer->getSourceRange();
10476 }
10477 
10478 /// Emit error if Operand is incomplete pointer type
10479 ///
10480 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)10481 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10482                                                  Expr *Operand) {
10483   QualType ResType = Operand->getType();
10484   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10485     ResType = ResAtomicType->getValueType();
10486 
10487   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10488   QualType PointeeTy = ResType->getPointeeType();
10489   return S.RequireCompleteSizedType(
10490       Loc, PointeeTy,
10491       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10492       Operand->getSourceRange());
10493 }
10494 
10495 /// Check the validity of an arithmetic pointer operand.
10496 ///
10497 /// If the operand has pointer type, this code will check for pointer types
10498 /// which are invalid in arithmetic operations. These will be diagnosed
10499 /// appropriately, including whether or not the use is supported as an
10500 /// extension.
10501 ///
10502 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)10503 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10504                                             Expr *Operand) {
10505   QualType ResType = Operand->getType();
10506   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10507     ResType = ResAtomicType->getValueType();
10508 
10509   if (!ResType->isAnyPointerType()) return true;
10510 
10511   QualType PointeeTy = ResType->getPointeeType();
10512   if (PointeeTy->isVoidType()) {
10513     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10514     return !S.getLangOpts().CPlusPlus;
10515   }
10516   if (PointeeTy->isFunctionType()) {
10517     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10518     return !S.getLangOpts().CPlusPlus;
10519   }
10520 
10521   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10522 
10523   return true;
10524 }
10525 
10526 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10527 /// operands.
10528 ///
10529 /// This routine will diagnose any invalid arithmetic on pointer operands much
10530 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10531 /// for emitting a single diagnostic even for operations where both LHS and RHS
10532 /// are (potentially problematic) pointers.
10533 ///
10534 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10535 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10536                                                 Expr *LHSExpr, Expr *RHSExpr) {
10537   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10538   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10539   if (!isLHSPointer && !isRHSPointer) return true;
10540 
10541   QualType LHSPointeeTy, RHSPointeeTy;
10542   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10543   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10544 
10545   // if both are pointers check if operation is valid wrt address spaces
10546   if (isLHSPointer && isRHSPointer) {
10547     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10548       S.Diag(Loc,
10549              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10550           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10551           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10552       return false;
10553     }
10554   }
10555 
10556   // Check for arithmetic on pointers to incomplete types.
10557   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10558   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10559   if (isLHSVoidPtr || isRHSVoidPtr) {
10560     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10561     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10562     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10563 
10564     return !S.getLangOpts().CPlusPlus;
10565   }
10566 
10567   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10568   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10569   if (isLHSFuncPtr || isRHSFuncPtr) {
10570     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10571     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10572                                                                 RHSExpr);
10573     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10574 
10575     return !S.getLangOpts().CPlusPlus;
10576   }
10577 
10578   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10579     return false;
10580   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10581     return false;
10582 
10583   return true;
10584 }
10585 
10586 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10587 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10588 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10589                                   Expr *LHSExpr, Expr *RHSExpr) {
10590   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10591   Expr* IndexExpr = RHSExpr;
10592   if (!StrExpr) {
10593     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10594     IndexExpr = LHSExpr;
10595   }
10596 
10597   bool IsStringPlusInt = StrExpr &&
10598       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10599   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10600     return;
10601 
10602   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10603   Self.Diag(OpLoc, diag::warn_string_plus_int)
10604       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10605 
10606   // Only print a fixit for "str" + int, not for int + "str".
10607   if (IndexExpr == RHSExpr) {
10608     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10609     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10610         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10611         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10612         << FixItHint::CreateInsertion(EndLoc, "]");
10613   } else
10614     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10615 }
10616 
10617 /// Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10618 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10619                                    Expr *LHSExpr, Expr *RHSExpr) {
10620   const Expr *StringRefExpr = LHSExpr;
10621   const CharacterLiteral *CharExpr =
10622       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10623 
10624   if (!CharExpr) {
10625     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10626     StringRefExpr = RHSExpr;
10627   }
10628 
10629   if (!CharExpr || !StringRefExpr)
10630     return;
10631 
10632   const QualType StringType = StringRefExpr->getType();
10633 
10634   // Return if not a PointerType.
10635   if (!StringType->isAnyPointerType())
10636     return;
10637 
10638   // Return if not a CharacterType.
10639   if (!StringType->getPointeeType()->isAnyCharacterType())
10640     return;
10641 
10642   ASTContext &Ctx = Self.getASTContext();
10643   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10644 
10645   const QualType CharType = CharExpr->getType();
10646   if (!CharType->isAnyCharacterType() &&
10647       CharType->isIntegerType() &&
10648       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10649     Self.Diag(OpLoc, diag::warn_string_plus_char)
10650         << DiagRange << Ctx.CharTy;
10651   } else {
10652     Self.Diag(OpLoc, diag::warn_string_plus_char)
10653         << DiagRange << CharExpr->getType();
10654   }
10655 
10656   // Only print a fixit for str + char, not for char + str.
10657   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10658     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10659     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10660         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10661         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10662         << FixItHint::CreateInsertion(EndLoc, "]");
10663   } else {
10664     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10665   }
10666 }
10667 
10668 /// Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10669 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10670                                            Expr *LHSExpr, Expr *RHSExpr) {
10671   assert(LHSExpr->getType()->isAnyPointerType());
10672   assert(RHSExpr->getType()->isAnyPointerType());
10673   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10674     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10675     << RHSExpr->getSourceRange();
10676 }
10677 
10678 // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)10679 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10680                                      SourceLocation Loc, BinaryOperatorKind Opc,
10681                                      QualType* CompLHSTy) {
10682   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10683 
10684   if (LHS.get()->getType()->isVectorType() ||
10685       RHS.get()->getType()->isVectorType()) {
10686     QualType compType = CheckVectorOperands(
10687         LHS, RHS, Loc, CompLHSTy,
10688         /*AllowBothBool*/getLangOpts().AltiVec,
10689         /*AllowBoolConversions*/getLangOpts().ZVector);
10690     if (CompLHSTy) *CompLHSTy = compType;
10691     return compType;
10692   }
10693 
10694   if (LHS.get()->getType()->isConstantMatrixType() ||
10695       RHS.get()->getType()->isConstantMatrixType()) {
10696     QualType compType =
10697         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10698     if (CompLHSTy)
10699       *CompLHSTy = compType;
10700     return compType;
10701   }
10702 
10703   QualType compType = UsualArithmeticConversions(
10704       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10705   if (LHS.isInvalid() || RHS.isInvalid())
10706     return QualType();
10707 
10708   // Diagnose "string literal" '+' int and string '+' "char literal".
10709   if (Opc == BO_Add) {
10710     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10711     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10712   }
10713 
10714   // handle the common case first (both operands are arithmetic).
10715   if (!compType.isNull() && compType->isArithmeticType()) {
10716     if (CompLHSTy) *CompLHSTy = compType;
10717     return compType;
10718   }
10719 
10720   // Type-checking.  Ultimately the pointer's going to be in PExp;
10721   // note that we bias towards the LHS being the pointer.
10722   Expr *PExp = LHS.get(), *IExp = RHS.get();
10723 
10724   bool isObjCPointer;
10725   if (PExp->getType()->isPointerType()) {
10726     isObjCPointer = false;
10727   } else if (PExp->getType()->isObjCObjectPointerType()) {
10728     isObjCPointer = true;
10729   } else {
10730     std::swap(PExp, IExp);
10731     if (PExp->getType()->isPointerType()) {
10732       isObjCPointer = false;
10733     } else if (PExp->getType()->isObjCObjectPointerType()) {
10734       isObjCPointer = true;
10735     } else {
10736       return InvalidOperands(Loc, LHS, RHS);
10737     }
10738   }
10739   assert(PExp->getType()->isAnyPointerType());
10740 
10741   if (!IExp->getType()->isIntegerType())
10742     return InvalidOperands(Loc, LHS, RHS);
10743 
10744   // Adding to a null pointer results in undefined behavior.
10745   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10746           Context, Expr::NPC_ValueDependentIsNotNull)) {
10747     // In C++ adding zero to a null pointer is defined.
10748     Expr::EvalResult KnownVal;
10749     if (!getLangOpts().CPlusPlus ||
10750         (!IExp->isValueDependent() &&
10751          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10752           KnownVal.Val.getInt() != 0))) {
10753       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10754       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10755           Context, BO_Add, PExp, IExp);
10756       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10757     }
10758   }
10759 
10760   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10761     return QualType();
10762 
10763   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10764     return QualType();
10765 
10766   // Check array bounds for pointer arithemtic
10767   CheckArrayAccess(PExp, IExp);
10768 
10769   if (CompLHSTy) {
10770     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10771     if (LHSTy.isNull()) {
10772       LHSTy = LHS.get()->getType();
10773       if (LHSTy->isPromotableIntegerType())
10774         LHSTy = Context.getPromotedIntegerType(LHSTy);
10775     }
10776     *CompLHSTy = LHSTy;
10777   }
10778 
10779   return PExp->getType();
10780 }
10781 
10782 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)10783 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10784                                         SourceLocation Loc,
10785                                         QualType* CompLHSTy) {
10786   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10787 
10788   if (LHS.get()->getType()->isVectorType() ||
10789       RHS.get()->getType()->isVectorType()) {
10790     QualType compType = CheckVectorOperands(
10791         LHS, RHS, Loc, CompLHSTy,
10792         /*AllowBothBool*/getLangOpts().AltiVec,
10793         /*AllowBoolConversions*/getLangOpts().ZVector);
10794     if (CompLHSTy) *CompLHSTy = compType;
10795     return compType;
10796   }
10797 
10798   if (LHS.get()->getType()->isConstantMatrixType() ||
10799       RHS.get()->getType()->isConstantMatrixType()) {
10800     QualType compType =
10801         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10802     if (CompLHSTy)
10803       *CompLHSTy = compType;
10804     return compType;
10805   }
10806 
10807   QualType compType = UsualArithmeticConversions(
10808       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10809   if (LHS.isInvalid() || RHS.isInvalid())
10810     return QualType();
10811 
10812   // Enforce type constraints: C99 6.5.6p3.
10813 
10814   // Handle the common case first (both operands are arithmetic).
10815   if (!compType.isNull() && compType->isArithmeticType()) {
10816     if (CompLHSTy) *CompLHSTy = compType;
10817     return compType;
10818   }
10819 
10820   // Either ptr - int   or   ptr - ptr.
10821   if (LHS.get()->getType()->isAnyPointerType()) {
10822     QualType lpointee = LHS.get()->getType()->getPointeeType();
10823 
10824     // Diagnose bad cases where we step over interface counts.
10825     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10826         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10827       return QualType();
10828 
10829     // The result type of a pointer-int computation is the pointer type.
10830     if (RHS.get()->getType()->isIntegerType()) {
10831       // Subtracting from a null pointer should produce a warning.
10832       // The last argument to the diagnose call says this doesn't match the
10833       // GNU int-to-pointer idiom.
10834       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10835                                            Expr::NPC_ValueDependentIsNotNull)) {
10836         // In C++ adding zero to a null pointer is defined.
10837         Expr::EvalResult KnownVal;
10838         if (!getLangOpts().CPlusPlus ||
10839             (!RHS.get()->isValueDependent() &&
10840              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10841               KnownVal.Val.getInt() != 0))) {
10842           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10843         }
10844       }
10845 
10846       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10847         return QualType();
10848 
10849       // Check array bounds for pointer arithemtic
10850       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10851                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10852 
10853       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10854       return LHS.get()->getType();
10855     }
10856 
10857     // Handle pointer-pointer subtractions.
10858     if (const PointerType *RHSPTy
10859           = RHS.get()->getType()->getAs<PointerType>()) {
10860       QualType rpointee = RHSPTy->getPointeeType();
10861 
10862       if (getLangOpts().CPlusPlus) {
10863         // Pointee types must be the same: C++ [expr.add]
10864         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10865           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10866         }
10867       } else {
10868         // Pointee types must be compatible C99 6.5.6p3
10869         if (!Context.typesAreCompatible(
10870                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10871                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10872           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10873           return QualType();
10874         }
10875       }
10876 
10877       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10878                                                LHS.get(), RHS.get()))
10879         return QualType();
10880 
10881       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10882           Context, Expr::NPC_ValueDependentIsNotNull);
10883       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
10884           Context, Expr::NPC_ValueDependentIsNotNull);
10885 
10886       // Subtracting nullptr or from nullptr is suspect
10887       if (LHSIsNullPtr)
10888         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
10889       if (RHSIsNullPtr)
10890         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
10891 
10892       // The pointee type may have zero size.  As an extension, a structure or
10893       // union may have zero size or an array may have zero length.  In this
10894       // case subtraction does not make sense.
10895       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10896         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10897         if (ElementSize.isZero()) {
10898           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10899             << rpointee.getUnqualifiedType()
10900             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10901         }
10902       }
10903 
10904       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10905       return Context.getPointerDiffType();
10906     }
10907   }
10908 
10909   return InvalidOperands(Loc, LHS, RHS);
10910 }
10911 
isScopedEnumerationType(QualType T)10912 static bool isScopedEnumerationType(QualType T) {
10913   if (const EnumType *ET = T->getAs<EnumType>())
10914     return ET->getDecl()->isScoped();
10915   return false;
10916 }
10917 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)10918 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10919                                    SourceLocation Loc, BinaryOperatorKind Opc,
10920                                    QualType LHSType) {
10921   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10922   // so skip remaining warnings as we don't want to modify values within Sema.
10923   if (S.getLangOpts().OpenCL)
10924     return;
10925 
10926   // Check right/shifter operand
10927   Expr::EvalResult RHSResult;
10928   if (RHS.get()->isValueDependent() ||
10929       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10930     return;
10931   llvm::APSInt Right = RHSResult.Val.getInt();
10932 
10933   if (Right.isNegative()) {
10934     S.DiagRuntimeBehavior(Loc, RHS.get(),
10935                           S.PDiag(diag::warn_shift_negative)
10936                             << RHS.get()->getSourceRange());
10937     return;
10938   }
10939 
10940   QualType LHSExprType = LHS.get()->getType();
10941   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10942   if (LHSExprType->isExtIntType())
10943     LeftSize = S.Context.getIntWidth(LHSExprType);
10944   else if (LHSExprType->isFixedPointType()) {
10945     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10946     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10947   }
10948   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10949   if (Right.uge(LeftBits)) {
10950     S.DiagRuntimeBehavior(Loc, RHS.get(),
10951                           S.PDiag(diag::warn_shift_gt_typewidth)
10952                             << RHS.get()->getSourceRange());
10953     return;
10954   }
10955 
10956   // FIXME: We probably need to handle fixed point types specially here.
10957   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10958     return;
10959 
10960   // When left shifting an ICE which is signed, we can check for overflow which
10961   // according to C++ standards prior to C++2a has undefined behavior
10962   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10963   // more than the maximum value representable in the result type, so never
10964   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10965   // expression is still probably a bug.)
10966   Expr::EvalResult LHSResult;
10967   if (LHS.get()->isValueDependent() ||
10968       LHSType->hasUnsignedIntegerRepresentation() ||
10969       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10970     return;
10971   llvm::APSInt Left = LHSResult.Val.getInt();
10972 
10973   // If LHS does not have a signed type and non-negative value
10974   // then, the behavior is undefined before C++2a. Warn about it.
10975   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10976       !S.getLangOpts().CPlusPlus20) {
10977     S.DiagRuntimeBehavior(Loc, LHS.get(),
10978                           S.PDiag(diag::warn_shift_lhs_negative)
10979                             << LHS.get()->getSourceRange());
10980     return;
10981   }
10982 
10983   llvm::APInt ResultBits =
10984       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10985   if (LeftBits.uge(ResultBits))
10986     return;
10987   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10988   Result = Result.shl(Right);
10989 
10990   // Print the bit representation of the signed integer as an unsigned
10991   // hexadecimal number.
10992   SmallString<40> HexResult;
10993   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10994 
10995   // If we are only missing a sign bit, this is less likely to result in actual
10996   // bugs -- if the result is cast back to an unsigned type, it will have the
10997   // expected value. Thus we place this behind a different warning that can be
10998   // turned off separately if needed.
10999   if (LeftBits == ResultBits - 1) {
11000     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11001         << HexResult << LHSType
11002         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11003     return;
11004   }
11005 
11006   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11007     << HexResult.str() << Result.getMinSignedBits() << LHSType
11008     << Left.getBitWidth() << LHS.get()->getSourceRange()
11009     << RHS.get()->getSourceRange();
11010 }
11011 
11012 /// Return the resulting type when a vector is shifted
11013 ///        by a scalar or vector shift amount.
checkVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)11014 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11015                                  SourceLocation Loc, bool IsCompAssign) {
11016   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11017   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11018       !LHS.get()->getType()->isVectorType()) {
11019     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11020       << RHS.get()->getType() << LHS.get()->getType()
11021       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11022     return QualType();
11023   }
11024 
11025   if (!IsCompAssign) {
11026     LHS = S.UsualUnaryConversions(LHS.get());
11027     if (LHS.isInvalid()) return QualType();
11028   }
11029 
11030   RHS = S.UsualUnaryConversions(RHS.get());
11031   if (RHS.isInvalid()) return QualType();
11032 
11033   QualType LHSType = LHS.get()->getType();
11034   // Note that LHS might be a scalar because the routine calls not only in
11035   // OpenCL case.
11036   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11037   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11038 
11039   // Note that RHS might not be a vector.
11040   QualType RHSType = RHS.get()->getType();
11041   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11042   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11043 
11044   // The operands need to be integers.
11045   if (!LHSEleType->isIntegerType()) {
11046     S.Diag(Loc, diag::err_typecheck_expect_int)
11047       << LHS.get()->getType() << LHS.get()->getSourceRange();
11048     return QualType();
11049   }
11050 
11051   if (!RHSEleType->isIntegerType()) {
11052     S.Diag(Loc, diag::err_typecheck_expect_int)
11053       << RHS.get()->getType() << RHS.get()->getSourceRange();
11054     return QualType();
11055   }
11056 
11057   if (!LHSVecTy) {
11058     assert(RHSVecTy);
11059     if (IsCompAssign)
11060       return RHSType;
11061     if (LHSEleType != RHSEleType) {
11062       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11063       LHSEleType = RHSEleType;
11064     }
11065     QualType VecTy =
11066         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11067     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11068     LHSType = VecTy;
11069   } else if (RHSVecTy) {
11070     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11071     // are applied component-wise. So if RHS is a vector, then ensure
11072     // that the number of elements is the same as LHS...
11073     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11074       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11075         << LHS.get()->getType() << RHS.get()->getType()
11076         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11077       return QualType();
11078     }
11079     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11080       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11081       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11082       if (LHSBT != RHSBT &&
11083           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11084         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11085             << LHS.get()->getType() << RHS.get()->getType()
11086             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11087       }
11088     }
11089   } else {
11090     // ...else expand RHS to match the number of elements in LHS.
11091     QualType VecTy =
11092       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11093     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11094   }
11095 
11096   return LHSType;
11097 }
11098 
11099 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)11100 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11101                                   SourceLocation Loc, BinaryOperatorKind Opc,
11102                                   bool IsCompAssign) {
11103   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11104 
11105   // Vector shifts promote their scalar inputs to vector type.
11106   if (LHS.get()->getType()->isVectorType() ||
11107       RHS.get()->getType()->isVectorType()) {
11108     if (LangOpts.ZVector) {
11109       // The shift operators for the z vector extensions work basically
11110       // like general shifts, except that neither the LHS nor the RHS is
11111       // allowed to be a "vector bool".
11112       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11113         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11114           return InvalidOperands(Loc, LHS, RHS);
11115       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11116         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11117           return InvalidOperands(Loc, LHS, RHS);
11118     }
11119     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11120   }
11121 
11122   // Shifts don't perform usual arithmetic conversions, they just do integer
11123   // promotions on each operand. C99 6.5.7p3
11124 
11125   // For the LHS, do usual unary conversions, but then reset them away
11126   // if this is a compound assignment.
11127   ExprResult OldLHS = LHS;
11128   LHS = UsualUnaryConversions(LHS.get());
11129   if (LHS.isInvalid())
11130     return QualType();
11131   QualType LHSType = LHS.get()->getType();
11132   if (IsCompAssign) LHS = OldLHS;
11133 
11134   // The RHS is simpler.
11135   RHS = UsualUnaryConversions(RHS.get());
11136   if (RHS.isInvalid())
11137     return QualType();
11138   QualType RHSType = RHS.get()->getType();
11139 
11140   // C99 6.5.7p2: Each of the operands shall have integer type.
11141   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11142   if ((!LHSType->isFixedPointOrIntegerType() &&
11143        !LHSType->hasIntegerRepresentation()) ||
11144       !RHSType->hasIntegerRepresentation())
11145     return InvalidOperands(Loc, LHS, RHS);
11146 
11147   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11148   // hasIntegerRepresentation() above instead of this.
11149   if (isScopedEnumerationType(LHSType) ||
11150       isScopedEnumerationType(RHSType)) {
11151     return InvalidOperands(Loc, LHS, RHS);
11152   }
11153   // Sanity-check shift operands
11154   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11155 
11156   // "The type of the result is that of the promoted left operand."
11157   return LHSType;
11158 }
11159 
11160 /// Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)11161 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11162                                               ExprResult &LHS, ExprResult &RHS,
11163                                               bool IsError) {
11164   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11165                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11166     << LHS.get()->getType() << RHS.get()->getType()
11167     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11168 }
11169 
11170 /// Returns false if the pointers are converted to a composite type,
11171 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)11172 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11173                                            ExprResult &LHS, ExprResult &RHS) {
11174   // C++ [expr.rel]p2:
11175   //   [...] Pointer conversions (4.10) and qualification
11176   //   conversions (4.4) are performed on pointer operands (or on
11177   //   a pointer operand and a null pointer constant) to bring
11178   //   them to their composite pointer type. [...]
11179   //
11180   // C++ [expr.eq]p1 uses the same notion for (in)equality
11181   // comparisons of pointers.
11182 
11183   QualType LHSType = LHS.get()->getType();
11184   QualType RHSType = RHS.get()->getType();
11185   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11186          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11187 
11188   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11189   if (T.isNull()) {
11190     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11191         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11192       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11193     else
11194       S.InvalidOperands(Loc, LHS, RHS);
11195     return true;
11196   }
11197 
11198   return false;
11199 }
11200 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)11201 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11202                                                     ExprResult &LHS,
11203                                                     ExprResult &RHS,
11204                                                     bool IsError) {
11205   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11206                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11207     << LHS.get()->getType() << RHS.get()->getType()
11208     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11209 }
11210 
isObjCObjectLiteral(ExprResult & E)11211 static bool isObjCObjectLiteral(ExprResult &E) {
11212   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11213   case Stmt::ObjCArrayLiteralClass:
11214   case Stmt::ObjCDictionaryLiteralClass:
11215   case Stmt::ObjCStringLiteralClass:
11216   case Stmt::ObjCBoxedExprClass:
11217     return true;
11218   default:
11219     // Note that ObjCBoolLiteral is NOT an object literal!
11220     return false;
11221   }
11222 }
11223 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)11224 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11225   const ObjCObjectPointerType *Type =
11226     LHS->getType()->getAs<ObjCObjectPointerType>();
11227 
11228   // If this is not actually an Objective-C object, bail out.
11229   if (!Type)
11230     return false;
11231 
11232   // Get the LHS object's interface type.
11233   QualType InterfaceType = Type->getPointeeType();
11234 
11235   // If the RHS isn't an Objective-C object, bail out.
11236   if (!RHS->getType()->isObjCObjectPointerType())
11237     return false;
11238 
11239   // Try to find the -isEqual: method.
11240   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11241   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11242                                                       InterfaceType,
11243                                                       /*IsInstance=*/true);
11244   if (!Method) {
11245     if (Type->isObjCIdType()) {
11246       // For 'id', just check the global pool.
11247       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11248                                                   /*receiverId=*/true);
11249     } else {
11250       // Check protocols.
11251       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11252                                              /*IsInstance=*/true);
11253     }
11254   }
11255 
11256   if (!Method)
11257     return false;
11258 
11259   QualType T = Method->parameters()[0]->getType();
11260   if (!T->isObjCObjectPointerType())
11261     return false;
11262 
11263   QualType R = Method->getReturnType();
11264   if (!R->isScalarType())
11265     return false;
11266 
11267   return true;
11268 }
11269 
CheckLiteralKind(Expr * FromE)11270 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11271   FromE = FromE->IgnoreParenImpCasts();
11272   switch (FromE->getStmtClass()) {
11273     default:
11274       break;
11275     case Stmt::ObjCStringLiteralClass:
11276       // "string literal"
11277       return LK_String;
11278     case Stmt::ObjCArrayLiteralClass:
11279       // "array literal"
11280       return LK_Array;
11281     case Stmt::ObjCDictionaryLiteralClass:
11282       // "dictionary literal"
11283       return LK_Dictionary;
11284     case Stmt::BlockExprClass:
11285       return LK_Block;
11286     case Stmt::ObjCBoxedExprClass: {
11287       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11288       switch (Inner->getStmtClass()) {
11289         case Stmt::IntegerLiteralClass:
11290         case Stmt::FloatingLiteralClass:
11291         case Stmt::CharacterLiteralClass:
11292         case Stmt::ObjCBoolLiteralExprClass:
11293         case Stmt::CXXBoolLiteralExprClass:
11294           // "numeric literal"
11295           return LK_Numeric;
11296         case Stmt::ImplicitCastExprClass: {
11297           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11298           // Boolean literals can be represented by implicit casts.
11299           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11300             return LK_Numeric;
11301           break;
11302         }
11303         default:
11304           break;
11305       }
11306       return LK_Boxed;
11307     }
11308   }
11309   return LK_None;
11310 }
11311 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)11312 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11313                                           ExprResult &LHS, ExprResult &RHS,
11314                                           BinaryOperator::Opcode Opc){
11315   Expr *Literal;
11316   Expr *Other;
11317   if (isObjCObjectLiteral(LHS)) {
11318     Literal = LHS.get();
11319     Other = RHS.get();
11320   } else {
11321     Literal = RHS.get();
11322     Other = LHS.get();
11323   }
11324 
11325   // Don't warn on comparisons against nil.
11326   Other = Other->IgnoreParenCasts();
11327   if (Other->isNullPointerConstant(S.getASTContext(),
11328                                    Expr::NPC_ValueDependentIsNotNull))
11329     return;
11330 
11331   // This should be kept in sync with warn_objc_literal_comparison.
11332   // LK_String should always be after the other literals, since it has its own
11333   // warning flag.
11334   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11335   assert(LiteralKind != Sema::LK_Block);
11336   if (LiteralKind == Sema::LK_None) {
11337     llvm_unreachable("Unknown Objective-C object literal kind");
11338   }
11339 
11340   if (LiteralKind == Sema::LK_String)
11341     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11342       << Literal->getSourceRange();
11343   else
11344     S.Diag(Loc, diag::warn_objc_literal_comparison)
11345       << LiteralKind << Literal->getSourceRange();
11346 
11347   if (BinaryOperator::isEqualityOp(Opc) &&
11348       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11349     SourceLocation Start = LHS.get()->getBeginLoc();
11350     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11351     CharSourceRange OpRange =
11352       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11353 
11354     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11355       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11356       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11357       << FixItHint::CreateInsertion(End, "]");
11358   }
11359 }
11360 
11361 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
diagnoseLogicalNotOnLHSofCheck(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11362 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11363                                            ExprResult &RHS, SourceLocation Loc,
11364                                            BinaryOperatorKind Opc) {
11365   // Check that left hand side is !something.
11366   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11367   if (!UO || UO->getOpcode() != UO_LNot) return;
11368 
11369   // Only check if the right hand side is non-bool arithmetic type.
11370   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11371 
11372   // Make sure that the something in !something is not bool.
11373   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11374   if (SubExpr->isKnownToHaveBooleanValue()) return;
11375 
11376   // Emit warning.
11377   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11378   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11379       << Loc << IsBitwiseOp;
11380 
11381   // First note suggest !(x < y)
11382   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11383   SourceLocation FirstClose = RHS.get()->getEndLoc();
11384   FirstClose = S.getLocForEndOfToken(FirstClose);
11385   if (FirstClose.isInvalid())
11386     FirstOpen = SourceLocation();
11387   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11388       << IsBitwiseOp
11389       << FixItHint::CreateInsertion(FirstOpen, "(")
11390       << FixItHint::CreateInsertion(FirstClose, ")");
11391 
11392   // Second note suggests (!x) < y
11393   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11394   SourceLocation SecondClose = LHS.get()->getEndLoc();
11395   SecondClose = S.getLocForEndOfToken(SecondClose);
11396   if (SecondClose.isInvalid())
11397     SecondOpen = SourceLocation();
11398   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11399       << FixItHint::CreateInsertion(SecondOpen, "(")
11400       << FixItHint::CreateInsertion(SecondClose, ")");
11401 }
11402 
11403 // Returns true if E refers to a non-weak array.
checkForArray(const Expr * E)11404 static bool checkForArray(const Expr *E) {
11405   const ValueDecl *D = nullptr;
11406   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11407     D = DR->getDecl();
11408   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11409     if (Mem->isImplicitAccess())
11410       D = Mem->getMemberDecl();
11411   }
11412   if (!D)
11413     return false;
11414   return D->getType()->isArrayType() && !D->isWeak();
11415 }
11416 
11417 /// Diagnose some forms of syntactically-obvious tautological comparison.
diagnoseTautologicalComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS,BinaryOperatorKind Opc)11418 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11419                                            Expr *LHS, Expr *RHS,
11420                                            BinaryOperatorKind Opc) {
11421   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11422   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11423 
11424   QualType LHSType = LHS->getType();
11425   QualType RHSType = RHS->getType();
11426   if (LHSType->hasFloatingRepresentation() ||
11427       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11428       S.inTemplateInstantiation())
11429     return;
11430 
11431   // Comparisons between two array types are ill-formed for operator<=>, so
11432   // we shouldn't emit any additional warnings about it.
11433   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11434     return;
11435 
11436   // For non-floating point types, check for self-comparisons of the form
11437   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11438   // often indicate logic errors in the program.
11439   //
11440   // NOTE: Don't warn about comparison expressions resulting from macro
11441   // expansion. Also don't warn about comparisons which are only self
11442   // comparisons within a template instantiation. The warnings should catch
11443   // obvious cases in the definition of the template anyways. The idea is to
11444   // warn when the typed comparison operator will always evaluate to the same
11445   // result.
11446 
11447   // Used for indexing into %select in warn_comparison_always
11448   enum {
11449     AlwaysConstant,
11450     AlwaysTrue,
11451     AlwaysFalse,
11452     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11453   };
11454 
11455   // C++2a [depr.array.comp]:
11456   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11457   //   operands of array type are deprecated.
11458   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11459       RHSStripped->getType()->isArrayType()) {
11460     S.Diag(Loc, diag::warn_depr_array_comparison)
11461         << LHS->getSourceRange() << RHS->getSourceRange()
11462         << LHSStripped->getType() << RHSStripped->getType();
11463     // Carry on to produce the tautological comparison warning, if this
11464     // expression is potentially-evaluated, we can resolve the array to a
11465     // non-weak declaration, and so on.
11466   }
11467 
11468   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11469     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11470       unsigned Result;
11471       switch (Opc) {
11472       case BO_EQ:
11473       case BO_LE:
11474       case BO_GE:
11475         Result = AlwaysTrue;
11476         break;
11477       case BO_NE:
11478       case BO_LT:
11479       case BO_GT:
11480         Result = AlwaysFalse;
11481         break;
11482       case BO_Cmp:
11483         Result = AlwaysEqual;
11484         break;
11485       default:
11486         Result = AlwaysConstant;
11487         break;
11488       }
11489       S.DiagRuntimeBehavior(Loc, nullptr,
11490                             S.PDiag(diag::warn_comparison_always)
11491                                 << 0 /*self-comparison*/
11492                                 << Result);
11493     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11494       // What is it always going to evaluate to?
11495       unsigned Result;
11496       switch (Opc) {
11497       case BO_EQ: // e.g. array1 == array2
11498         Result = AlwaysFalse;
11499         break;
11500       case BO_NE: // e.g. array1 != array2
11501         Result = AlwaysTrue;
11502         break;
11503       default: // e.g. array1 <= array2
11504         // The best we can say is 'a constant'
11505         Result = AlwaysConstant;
11506         break;
11507       }
11508       S.DiagRuntimeBehavior(Loc, nullptr,
11509                             S.PDiag(diag::warn_comparison_always)
11510                                 << 1 /*array comparison*/
11511                                 << Result);
11512     }
11513   }
11514 
11515   if (isa<CastExpr>(LHSStripped))
11516     LHSStripped = LHSStripped->IgnoreParenCasts();
11517   if (isa<CastExpr>(RHSStripped))
11518     RHSStripped = RHSStripped->IgnoreParenCasts();
11519 
11520   // Warn about comparisons against a string constant (unless the other
11521   // operand is null); the user probably wants string comparison function.
11522   Expr *LiteralString = nullptr;
11523   Expr *LiteralStringStripped = nullptr;
11524   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11525       !RHSStripped->isNullPointerConstant(S.Context,
11526                                           Expr::NPC_ValueDependentIsNull)) {
11527     LiteralString = LHS;
11528     LiteralStringStripped = LHSStripped;
11529   } else if ((isa<StringLiteral>(RHSStripped) ||
11530               isa<ObjCEncodeExpr>(RHSStripped)) &&
11531              !LHSStripped->isNullPointerConstant(S.Context,
11532                                           Expr::NPC_ValueDependentIsNull)) {
11533     LiteralString = RHS;
11534     LiteralStringStripped = RHSStripped;
11535   }
11536 
11537   if (LiteralString) {
11538     S.DiagRuntimeBehavior(Loc, nullptr,
11539                           S.PDiag(diag::warn_stringcompare)
11540                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11541                               << LiteralString->getSourceRange());
11542   }
11543 }
11544 
castKindToImplicitConversionKind(CastKind CK)11545 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11546   switch (CK) {
11547   default: {
11548 #ifndef NDEBUG
11549     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11550                  << "\n";
11551 #endif
11552     llvm_unreachable("unhandled cast kind");
11553   }
11554   case CK_UserDefinedConversion:
11555     return ICK_Identity;
11556   case CK_LValueToRValue:
11557     return ICK_Lvalue_To_Rvalue;
11558   case CK_ArrayToPointerDecay:
11559     return ICK_Array_To_Pointer;
11560   case CK_FunctionToPointerDecay:
11561     return ICK_Function_To_Pointer;
11562   case CK_IntegralCast:
11563     return ICK_Integral_Conversion;
11564   case CK_FloatingCast:
11565     return ICK_Floating_Conversion;
11566   case CK_IntegralToFloating:
11567   case CK_FloatingToIntegral:
11568     return ICK_Floating_Integral;
11569   case CK_IntegralComplexCast:
11570   case CK_FloatingComplexCast:
11571   case CK_FloatingComplexToIntegralComplex:
11572   case CK_IntegralComplexToFloatingComplex:
11573     return ICK_Complex_Conversion;
11574   case CK_FloatingComplexToReal:
11575   case CK_FloatingRealToComplex:
11576   case CK_IntegralComplexToReal:
11577   case CK_IntegralRealToComplex:
11578     return ICK_Complex_Real;
11579   }
11580 }
11581 
checkThreeWayNarrowingConversion(Sema & S,QualType ToType,Expr * E,QualType FromType,SourceLocation Loc)11582 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11583                                              QualType FromType,
11584                                              SourceLocation Loc) {
11585   // Check for a narrowing implicit conversion.
11586   StandardConversionSequence SCS;
11587   SCS.setAsIdentityConversion();
11588   SCS.setToType(0, FromType);
11589   SCS.setToType(1, ToType);
11590   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11591     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11592 
11593   APValue PreNarrowingValue;
11594   QualType PreNarrowingType;
11595   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11596                                PreNarrowingType,
11597                                /*IgnoreFloatToIntegralConversion*/ true)) {
11598   case NK_Dependent_Narrowing:
11599     // Implicit conversion to a narrower type, but the expression is
11600     // value-dependent so we can't tell whether it's actually narrowing.
11601   case NK_Not_Narrowing:
11602     return false;
11603 
11604   case NK_Constant_Narrowing:
11605     // Implicit conversion to a narrower type, and the value is not a constant
11606     // expression.
11607     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11608         << /*Constant*/ 1
11609         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11610     return true;
11611 
11612   case NK_Variable_Narrowing:
11613     // Implicit conversion to a narrower type, and the value is not a constant
11614     // expression.
11615   case NK_Type_Narrowing:
11616     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11617         << /*Constant*/ 0 << FromType << ToType;
11618     // TODO: It's not a constant expression, but what if the user intended it
11619     // to be? Can we produce notes to help them figure out why it isn't?
11620     return true;
11621   }
11622   llvm_unreachable("unhandled case in switch");
11623 }
11624 
checkArithmeticOrEnumeralThreeWayCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)11625 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11626                                                          ExprResult &LHS,
11627                                                          ExprResult &RHS,
11628                                                          SourceLocation Loc) {
11629   QualType LHSType = LHS.get()->getType();
11630   QualType RHSType = RHS.get()->getType();
11631   // Dig out the original argument type and expression before implicit casts
11632   // were applied. These are the types/expressions we need to check the
11633   // [expr.spaceship] requirements against.
11634   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11635   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11636   QualType LHSStrippedType = LHSStripped.get()->getType();
11637   QualType RHSStrippedType = RHSStripped.get()->getType();
11638 
11639   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11640   // other is not, the program is ill-formed.
11641   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11642     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11643     return QualType();
11644   }
11645 
11646   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11647   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11648                     RHSStrippedType->isEnumeralType();
11649   if (NumEnumArgs == 1) {
11650     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11651     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11652     if (OtherTy->hasFloatingRepresentation()) {
11653       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11654       return QualType();
11655     }
11656   }
11657   if (NumEnumArgs == 2) {
11658     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11659     // type E, the operator yields the result of converting the operands
11660     // to the underlying type of E and applying <=> to the converted operands.
11661     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11662       S.InvalidOperands(Loc, LHS, RHS);
11663       return QualType();
11664     }
11665     QualType IntType =
11666         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11667     assert(IntType->isArithmeticType());
11668 
11669     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11670     // promote the boolean type, and all other promotable integer types, to
11671     // avoid this.
11672     if (IntType->isPromotableIntegerType())
11673       IntType = S.Context.getPromotedIntegerType(IntType);
11674 
11675     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11676     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11677     LHSType = RHSType = IntType;
11678   }
11679 
11680   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11681   // usual arithmetic conversions are applied to the operands.
11682   QualType Type =
11683       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11684   if (LHS.isInvalid() || RHS.isInvalid())
11685     return QualType();
11686   if (Type.isNull())
11687     return S.InvalidOperands(Loc, LHS, RHS);
11688 
11689   Optional<ComparisonCategoryType> CCT =
11690       getComparisonCategoryForBuiltinCmp(Type);
11691   if (!CCT)
11692     return S.InvalidOperands(Loc, LHS, RHS);
11693 
11694   bool HasNarrowing = checkThreeWayNarrowingConversion(
11695       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11696   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11697                                                    RHS.get()->getBeginLoc());
11698   if (HasNarrowing)
11699     return QualType();
11700 
11701   assert(!Type.isNull() && "composite type for <=> has not been set");
11702 
11703   return S.CheckComparisonCategoryType(
11704       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11705 }
11706 
checkArithmeticOrEnumeralCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11707 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11708                                                  ExprResult &RHS,
11709                                                  SourceLocation Loc,
11710                                                  BinaryOperatorKind Opc) {
11711   if (Opc == BO_Cmp)
11712     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11713 
11714   // C99 6.5.8p3 / C99 6.5.9p4
11715   QualType Type =
11716       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11717   if (LHS.isInvalid() || RHS.isInvalid())
11718     return QualType();
11719   if (Type.isNull())
11720     return S.InvalidOperands(Loc, LHS, RHS);
11721   assert(Type->isArithmeticType() || Type->isEnumeralType());
11722 
11723   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11724     return S.InvalidOperands(Loc, LHS, RHS);
11725 
11726   // Check for comparisons of floating point operands using != and ==.
11727   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11728     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11729 
11730   // The result of comparisons is 'bool' in C++, 'int' in C.
11731   return S.Context.getLogicalOperationType();
11732 }
11733 
CheckPtrComparisonWithNullChar(ExprResult & E,ExprResult & NullE)11734 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11735   if (!NullE.get()->getType()->isAnyPointerType())
11736     return;
11737   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11738   if (!E.get()->getType()->isAnyPointerType() &&
11739       E.get()->isNullPointerConstant(Context,
11740                                      Expr::NPC_ValueDependentIsNotNull) ==
11741         Expr::NPCK_ZeroExpression) {
11742     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11743       if (CL->getValue() == 0)
11744         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11745             << NullValue
11746             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11747                                             NullValue ? "NULL" : "(void *)0");
11748     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11749         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11750         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11751         if (T == Context.CharTy)
11752           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11753               << NullValue
11754               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11755                                               NullValue ? "NULL" : "(void *)0");
11756       }
11757   }
11758 }
11759 
11760 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11761 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11762                                     SourceLocation Loc,
11763                                     BinaryOperatorKind Opc) {
11764   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11765   bool IsThreeWay = Opc == BO_Cmp;
11766   bool IsOrdered = IsRelational || IsThreeWay;
11767   auto IsAnyPointerType = [](ExprResult E) {
11768     QualType Ty = E.get()->getType();
11769     return Ty->isPointerType() || Ty->isMemberPointerType();
11770   };
11771 
11772   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11773   // type, array-to-pointer, ..., conversions are performed on both operands to
11774   // bring them to their composite type.
11775   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11776   // any type-related checks.
11777   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11778     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11779     if (LHS.isInvalid())
11780       return QualType();
11781     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11782     if (RHS.isInvalid())
11783       return QualType();
11784   } else {
11785     LHS = DefaultLvalueConversion(LHS.get());
11786     if (LHS.isInvalid())
11787       return QualType();
11788     RHS = DefaultLvalueConversion(RHS.get());
11789     if (RHS.isInvalid())
11790       return QualType();
11791   }
11792 
11793   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11794   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11795     CheckPtrComparisonWithNullChar(LHS, RHS);
11796     CheckPtrComparisonWithNullChar(RHS, LHS);
11797   }
11798 
11799   // Handle vector comparisons separately.
11800   if (LHS.get()->getType()->isVectorType() ||
11801       RHS.get()->getType()->isVectorType())
11802     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11803 
11804   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11805   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11806 
11807   QualType LHSType = LHS.get()->getType();
11808   QualType RHSType = RHS.get()->getType();
11809   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11810       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11811     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11812 
11813   const Expr::NullPointerConstantKind LHSNullKind =
11814       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11815   const Expr::NullPointerConstantKind RHSNullKind =
11816       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11817   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11818   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11819 
11820   auto computeResultTy = [&]() {
11821     if (Opc != BO_Cmp)
11822       return Context.getLogicalOperationType();
11823     assert(getLangOpts().CPlusPlus);
11824     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11825 
11826     QualType CompositeTy = LHS.get()->getType();
11827     assert(!CompositeTy->isReferenceType());
11828 
11829     Optional<ComparisonCategoryType> CCT =
11830         getComparisonCategoryForBuiltinCmp(CompositeTy);
11831     if (!CCT)
11832       return InvalidOperands(Loc, LHS, RHS);
11833 
11834     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11835       // P0946R0: Comparisons between a null pointer constant and an object
11836       // pointer result in std::strong_equality, which is ill-formed under
11837       // P1959R0.
11838       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11839           << (LHSIsNull ? LHS.get()->getSourceRange()
11840                         : RHS.get()->getSourceRange());
11841       return QualType();
11842     }
11843 
11844     return CheckComparisonCategoryType(
11845         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11846   };
11847 
11848   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11849     bool IsEquality = Opc == BO_EQ;
11850     if (RHSIsNull)
11851       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11852                                    RHS.get()->getSourceRange());
11853     else
11854       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11855                                    LHS.get()->getSourceRange());
11856   }
11857 
11858   if (IsOrdered && LHSType->isFunctionPointerType() &&
11859       RHSType->isFunctionPointerType()) {
11860     // Valid unless a relational comparison of function pointers
11861     bool IsError = Opc == BO_Cmp;
11862     auto DiagID =
11863         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
11864         : getLangOpts().CPlusPlus
11865             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
11866             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
11867     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11868                       << RHS.get()->getSourceRange();
11869     if (IsError)
11870       return QualType();
11871   }
11872 
11873   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11874       (RHSType->isIntegerType() && !RHSIsNull)) {
11875     // Skip normal pointer conversion checks in this case; we have better
11876     // diagnostics for this below.
11877   } else if (getLangOpts().CPlusPlus) {
11878     // Equality comparison of a function pointer to a void pointer is invalid,
11879     // but we allow it as an extension.
11880     // FIXME: If we really want to allow this, should it be part of composite
11881     // pointer type computation so it works in conditionals too?
11882     if (!IsOrdered &&
11883         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11884          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11885       // This is a gcc extension compatibility comparison.
11886       // In a SFINAE context, we treat this as a hard error to maintain
11887       // conformance with the C++ standard.
11888       diagnoseFunctionPointerToVoidComparison(
11889           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11890 
11891       if (isSFINAEContext())
11892         return QualType();
11893 
11894       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11895       return computeResultTy();
11896     }
11897 
11898     // C++ [expr.eq]p2:
11899     //   If at least one operand is a pointer [...] bring them to their
11900     //   composite pointer type.
11901     // C++ [expr.spaceship]p6
11902     //  If at least one of the operands is of pointer type, [...] bring them
11903     //  to their composite pointer type.
11904     // C++ [expr.rel]p2:
11905     //   If both operands are pointers, [...] bring them to their composite
11906     //   pointer type.
11907     // For <=>, the only valid non-pointer types are arrays and functions, and
11908     // we already decayed those, so this is really the same as the relational
11909     // comparison rule.
11910     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11911             (IsOrdered ? 2 : 1) &&
11912         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11913                                          RHSType->isObjCObjectPointerType()))) {
11914       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11915         return QualType();
11916       return computeResultTy();
11917     }
11918   } else if (LHSType->isPointerType() &&
11919              RHSType->isPointerType()) { // C99 6.5.8p2
11920     // All of the following pointer-related warnings are GCC extensions, except
11921     // when handling null pointer constants.
11922     QualType LCanPointeeTy =
11923       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11924     QualType RCanPointeeTy =
11925       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11926 
11927     // C99 6.5.9p2 and C99 6.5.8p2
11928     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11929                                    RCanPointeeTy.getUnqualifiedType())) {
11930       if (IsRelational) {
11931         // Pointers both need to point to complete or incomplete types
11932         if ((LCanPointeeTy->isIncompleteType() !=
11933              RCanPointeeTy->isIncompleteType()) &&
11934             !getLangOpts().C11) {
11935           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11936               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11937               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11938               << RCanPointeeTy->isIncompleteType();
11939         }
11940       }
11941     } else if (!IsRelational &&
11942                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11943       // Valid unless comparison between non-null pointer and function pointer
11944       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11945           && !LHSIsNull && !RHSIsNull)
11946         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11947                                                 /*isError*/false);
11948     } else {
11949       // Invalid
11950       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11951     }
11952     if (LCanPointeeTy != RCanPointeeTy) {
11953       // Treat NULL constant as a special case in OpenCL.
11954       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11955         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11956           Diag(Loc,
11957                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11958               << LHSType << RHSType << 0 /* comparison */
11959               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11960         }
11961       }
11962       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11963       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11964       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11965                                                : CK_BitCast;
11966       if (LHSIsNull && !RHSIsNull)
11967         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11968       else
11969         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11970     }
11971     return computeResultTy();
11972   }
11973 
11974   if (getLangOpts().CPlusPlus) {
11975     // C++ [expr.eq]p4:
11976     //   Two operands of type std::nullptr_t or one operand of type
11977     //   std::nullptr_t and the other a null pointer constant compare equal.
11978     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11979       if (LHSType->isNullPtrType()) {
11980         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11981         return computeResultTy();
11982       }
11983       if (RHSType->isNullPtrType()) {
11984         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11985         return computeResultTy();
11986       }
11987     }
11988 
11989     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11990     // These aren't covered by the composite pointer type rules.
11991     if (!IsOrdered && RHSType->isNullPtrType() &&
11992         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11993       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11994       return computeResultTy();
11995     }
11996     if (!IsOrdered && LHSType->isNullPtrType() &&
11997         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11998       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11999       return computeResultTy();
12000     }
12001 
12002     if (IsRelational &&
12003         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12004          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12005       // HACK: Relational comparison of nullptr_t against a pointer type is
12006       // invalid per DR583, but we allow it within std::less<> and friends,
12007       // since otherwise common uses of it break.
12008       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12009       // friends to have std::nullptr_t overload candidates.
12010       DeclContext *DC = CurContext;
12011       if (isa<FunctionDecl>(DC))
12012         DC = DC->getParent();
12013       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12014         if (CTSD->isInStdNamespace() &&
12015             llvm::StringSwitch<bool>(CTSD->getName())
12016                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12017                 .Default(false)) {
12018           if (RHSType->isNullPtrType())
12019             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12020           else
12021             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12022           return computeResultTy();
12023         }
12024       }
12025     }
12026 
12027     // C++ [expr.eq]p2:
12028     //   If at least one operand is a pointer to member, [...] bring them to
12029     //   their composite pointer type.
12030     if (!IsOrdered &&
12031         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12032       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12033         return QualType();
12034       else
12035         return computeResultTy();
12036     }
12037   }
12038 
12039   // Handle block pointer types.
12040   if (!IsOrdered && LHSType->isBlockPointerType() &&
12041       RHSType->isBlockPointerType()) {
12042     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12043     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12044 
12045     if (!LHSIsNull && !RHSIsNull &&
12046         !Context.typesAreCompatible(lpointee, rpointee)) {
12047       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12048         << LHSType << RHSType << LHS.get()->getSourceRange()
12049         << RHS.get()->getSourceRange();
12050     }
12051     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12052     return computeResultTy();
12053   }
12054 
12055   // Allow block pointers to be compared with null pointer constants.
12056   if (!IsOrdered
12057       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12058           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12059     if (!LHSIsNull && !RHSIsNull) {
12060       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12061              ->getPointeeType()->isVoidType())
12062             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12063                 ->getPointeeType()->isVoidType())))
12064         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12065           << LHSType << RHSType << LHS.get()->getSourceRange()
12066           << RHS.get()->getSourceRange();
12067     }
12068     if (LHSIsNull && !RHSIsNull)
12069       LHS = ImpCastExprToType(LHS.get(), RHSType,
12070                               RHSType->isPointerType() ? CK_BitCast
12071                                 : CK_AnyPointerToBlockPointerCast);
12072     else
12073       RHS = ImpCastExprToType(RHS.get(), LHSType,
12074                               LHSType->isPointerType() ? CK_BitCast
12075                                 : CK_AnyPointerToBlockPointerCast);
12076     return computeResultTy();
12077   }
12078 
12079   if (LHSType->isObjCObjectPointerType() ||
12080       RHSType->isObjCObjectPointerType()) {
12081     const PointerType *LPT = LHSType->getAs<PointerType>();
12082     const PointerType *RPT = RHSType->getAs<PointerType>();
12083     if (LPT || RPT) {
12084       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12085       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12086 
12087       if (!LPtrToVoid && !RPtrToVoid &&
12088           !Context.typesAreCompatible(LHSType, RHSType)) {
12089         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12090                                           /*isError*/false);
12091       }
12092       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12093       // the RHS, but we have test coverage for this behavior.
12094       // FIXME: Consider using convertPointersToCompositeType in C++.
12095       if (LHSIsNull && !RHSIsNull) {
12096         Expr *E = LHS.get();
12097         if (getLangOpts().ObjCAutoRefCount)
12098           CheckObjCConversion(SourceRange(), RHSType, E,
12099                               CCK_ImplicitConversion);
12100         LHS = ImpCastExprToType(E, RHSType,
12101                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12102       }
12103       else {
12104         Expr *E = RHS.get();
12105         if (getLangOpts().ObjCAutoRefCount)
12106           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12107                               /*Diagnose=*/true,
12108                               /*DiagnoseCFAudited=*/false, Opc);
12109         RHS = ImpCastExprToType(E, LHSType,
12110                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12111       }
12112       return computeResultTy();
12113     }
12114     if (LHSType->isObjCObjectPointerType() &&
12115         RHSType->isObjCObjectPointerType()) {
12116       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12117         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12118                                           /*isError*/false);
12119       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12120         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12121 
12122       if (LHSIsNull && !RHSIsNull)
12123         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12124       else
12125         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12126       return computeResultTy();
12127     }
12128 
12129     if (!IsOrdered && LHSType->isBlockPointerType() &&
12130         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12131       LHS = ImpCastExprToType(LHS.get(), RHSType,
12132                               CK_BlockPointerToObjCPointerCast);
12133       return computeResultTy();
12134     } else if (!IsOrdered &&
12135                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12136                RHSType->isBlockPointerType()) {
12137       RHS = ImpCastExprToType(RHS.get(), LHSType,
12138                               CK_BlockPointerToObjCPointerCast);
12139       return computeResultTy();
12140     }
12141   }
12142   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12143       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12144     unsigned DiagID = 0;
12145     bool isError = false;
12146     if (LangOpts.DebuggerSupport) {
12147       // Under a debugger, allow the comparison of pointers to integers,
12148       // since users tend to want to compare addresses.
12149     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12150                (RHSIsNull && RHSType->isIntegerType())) {
12151       if (IsOrdered) {
12152         isError = getLangOpts().CPlusPlus;
12153         DiagID =
12154           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12155                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12156       }
12157     } else if (getLangOpts().CPlusPlus) {
12158       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12159       isError = true;
12160     } else if (IsOrdered)
12161       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12162     else
12163       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12164 
12165     if (DiagID) {
12166       Diag(Loc, DiagID)
12167         << LHSType << RHSType << LHS.get()->getSourceRange()
12168         << RHS.get()->getSourceRange();
12169       if (isError)
12170         return QualType();
12171     }
12172 
12173     if (LHSType->isIntegerType())
12174       LHS = ImpCastExprToType(LHS.get(), RHSType,
12175                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12176     else
12177       RHS = ImpCastExprToType(RHS.get(), LHSType,
12178                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12179     return computeResultTy();
12180   }
12181 
12182   // Handle block pointers.
12183   if (!IsOrdered && RHSIsNull
12184       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12185     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12186     return computeResultTy();
12187   }
12188   if (!IsOrdered && LHSIsNull
12189       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12190     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12191     return computeResultTy();
12192   }
12193 
12194   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12195     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12196       return computeResultTy();
12197     }
12198 
12199     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12200       return computeResultTy();
12201     }
12202 
12203     if (LHSIsNull && RHSType->isQueueT()) {
12204       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12205       return computeResultTy();
12206     }
12207 
12208     if (LHSType->isQueueT() && RHSIsNull) {
12209       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12210       return computeResultTy();
12211     }
12212   }
12213 
12214   return InvalidOperands(Loc, LHS, RHS);
12215 }
12216 
12217 // Return a signed ext_vector_type that is of identical size and number of
12218 // elements. For floating point vectors, return an integer type of identical
12219 // size and number of elements. In the non ext_vector_type case, search from
12220 // the largest type to the smallest type to avoid cases where long long == long,
12221 // where long gets picked over long long.
GetSignedVectorType(QualType V)12222 QualType Sema::GetSignedVectorType(QualType V) {
12223   const VectorType *VTy = V->castAs<VectorType>();
12224   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12225 
12226   if (isa<ExtVectorType>(VTy)) {
12227     if (TypeSize == Context.getTypeSize(Context.CharTy))
12228       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12229     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12230       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12231     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12232       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12233     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12234       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12235     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12236            "Unhandled vector element size in vector compare");
12237     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12238   }
12239 
12240   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12241     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12242                                  VectorType::GenericVector);
12243   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12244     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12245                                  VectorType::GenericVector);
12246   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12247     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12248                                  VectorType::GenericVector);
12249   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12250     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12251                                  VectorType::GenericVector);
12252   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12253          "Unhandled vector element size in vector compare");
12254   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12255                                VectorType::GenericVector);
12256 }
12257 
12258 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12259 /// operates on extended vector types.  Instead of producing an IntTy result,
12260 /// like a scalar comparison, a vector comparison produces a vector of integer
12261 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12262 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12263                                           SourceLocation Loc,
12264                                           BinaryOperatorKind Opc) {
12265   if (Opc == BO_Cmp) {
12266     Diag(Loc, diag::err_three_way_vector_comparison);
12267     return QualType();
12268   }
12269 
12270   // Check to make sure we're operating on vectors of the same type and width,
12271   // Allowing one side to be a scalar of element type.
12272   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12273                               /*AllowBothBool*/true,
12274                               /*AllowBoolConversions*/getLangOpts().ZVector);
12275   if (vType.isNull())
12276     return vType;
12277 
12278   QualType LHSType = LHS.get()->getType();
12279 
12280   // Determine the return type of a vector compare. By default clang will return
12281   // a scalar for all vector compares except vector bool and vector pixel.
12282   // With the gcc compiler we will always return a vector type and with the xl
12283   // compiler we will always return a scalar type. This switch allows choosing
12284   // which behavior is prefered.
12285   if (getLangOpts().AltiVec) {
12286     switch (getLangOpts().getAltivecSrcCompat()) {
12287     case LangOptions::AltivecSrcCompatKind::Mixed:
12288       // If AltiVec, the comparison results in a numeric type, i.e.
12289       // bool for C++, int for C
12290       if (vType->castAs<VectorType>()->getVectorKind() ==
12291           VectorType::AltiVecVector)
12292         return Context.getLogicalOperationType();
12293       else
12294         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12295       break;
12296     case LangOptions::AltivecSrcCompatKind::GCC:
12297       // For GCC we always return the vector type.
12298       break;
12299     case LangOptions::AltivecSrcCompatKind::XL:
12300       return Context.getLogicalOperationType();
12301       break;
12302     }
12303   }
12304 
12305   // For non-floating point types, check for self-comparisons of the form
12306   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12307   // often indicate logic errors in the program.
12308   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12309 
12310   // Check for comparisons of floating point operands using != and ==.
12311   if (BinaryOperator::isEqualityOp(Opc) &&
12312       LHSType->hasFloatingRepresentation()) {
12313     assert(RHS.get()->getType()->hasFloatingRepresentation());
12314     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12315   }
12316 
12317   // Return a signed type for the vector.
12318   return GetSignedVectorType(vType);
12319 }
12320 
diagnoseXorMisusedAsPow(Sema & S,const ExprResult & XorLHS,const ExprResult & XorRHS,const SourceLocation Loc)12321 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12322                                     const ExprResult &XorRHS,
12323                                     const SourceLocation Loc) {
12324   // Do not diagnose macros.
12325   if (Loc.isMacroID())
12326     return;
12327 
12328   // Do not diagnose if both LHS and RHS are macros.
12329   if (XorLHS.get()->getExprLoc().isMacroID() &&
12330       XorRHS.get()->getExprLoc().isMacroID())
12331     return;
12332 
12333   bool Negative = false;
12334   bool ExplicitPlus = false;
12335   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12336   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12337 
12338   if (!LHSInt)
12339     return;
12340   if (!RHSInt) {
12341     // Check negative literals.
12342     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12343       UnaryOperatorKind Opc = UO->getOpcode();
12344       if (Opc != UO_Minus && Opc != UO_Plus)
12345         return;
12346       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12347       if (!RHSInt)
12348         return;
12349       Negative = (Opc == UO_Minus);
12350       ExplicitPlus = !Negative;
12351     } else {
12352       return;
12353     }
12354   }
12355 
12356   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12357   llvm::APInt RightSideValue = RHSInt->getValue();
12358   if (LeftSideValue != 2 && LeftSideValue != 10)
12359     return;
12360 
12361   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12362     return;
12363 
12364   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12365       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12366   llvm::StringRef ExprStr =
12367       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12368 
12369   CharSourceRange XorRange =
12370       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12371   llvm::StringRef XorStr =
12372       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12373   // Do not diagnose if xor keyword/macro is used.
12374   if (XorStr == "xor")
12375     return;
12376 
12377   std::string LHSStr = std::string(Lexer::getSourceText(
12378       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12379       S.getSourceManager(), S.getLangOpts()));
12380   std::string RHSStr = std::string(Lexer::getSourceText(
12381       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12382       S.getSourceManager(), S.getLangOpts()));
12383 
12384   if (Negative) {
12385     RightSideValue = -RightSideValue;
12386     RHSStr = "-" + RHSStr;
12387   } else if (ExplicitPlus) {
12388     RHSStr = "+" + RHSStr;
12389   }
12390 
12391   StringRef LHSStrRef = LHSStr;
12392   StringRef RHSStrRef = RHSStr;
12393   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12394   // literals.
12395   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12396       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12397       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12398       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12399       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12400       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12401       LHSStrRef.find('\'') != StringRef::npos ||
12402       RHSStrRef.find('\'') != StringRef::npos)
12403     return;
12404 
12405   bool SuggestXor =
12406       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12407   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12408   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12409   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12410     std::string SuggestedExpr = "1 << " + RHSStr;
12411     bool Overflow = false;
12412     llvm::APInt One = (LeftSideValue - 1);
12413     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12414     if (Overflow) {
12415       if (RightSideIntValue < 64)
12416         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12417             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12418             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12419       else if (RightSideIntValue == 64)
12420         S.Diag(Loc, diag::warn_xor_used_as_pow)
12421             << ExprStr << toString(XorValue, 10, true);
12422       else
12423         return;
12424     } else {
12425       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12426           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12427           << toString(PowValue, 10, true)
12428           << FixItHint::CreateReplacement(
12429                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12430     }
12431 
12432     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12433         << ("0x2 ^ " + RHSStr) << SuggestXor;
12434   } else if (LeftSideValue == 10) {
12435     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12436     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12437         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12438         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12439     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12440         << ("0xA ^ " + RHSStr) << SuggestXor;
12441   }
12442 }
12443 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)12444 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12445                                           SourceLocation Loc) {
12446   // Ensure that either both operands are of the same vector type, or
12447   // one operand is of a vector type and the other is of its element type.
12448   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12449                                        /*AllowBothBool*/true,
12450                                        /*AllowBoolConversions*/false);
12451   if (vType.isNull())
12452     return InvalidOperands(Loc, LHS, RHS);
12453   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12454       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12455     return InvalidOperands(Loc, LHS, RHS);
12456   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12457   //        usage of the logical operators && and || with vectors in C. This
12458   //        check could be notionally dropped.
12459   if (!getLangOpts().CPlusPlus &&
12460       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12461     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12462 
12463   return GetSignedVectorType(LHS.get()->getType());
12464 }
12465 
CheckMatrixElementwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12466 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12467                                               SourceLocation Loc,
12468                                               bool IsCompAssign) {
12469   if (!IsCompAssign) {
12470     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12471     if (LHS.isInvalid())
12472       return QualType();
12473   }
12474   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12475   if (RHS.isInvalid())
12476     return QualType();
12477 
12478   // For conversion purposes, we ignore any qualifiers.
12479   // For example, "const float" and "float" are equivalent.
12480   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12481   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12482 
12483   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12484   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12485   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12486 
12487   if (Context.hasSameType(LHSType, RHSType))
12488     return LHSType;
12489 
12490   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12491   // case we have to return InvalidOperands.
12492   ExprResult OriginalLHS = LHS;
12493   ExprResult OriginalRHS = RHS;
12494   if (LHSMatType && !RHSMatType) {
12495     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12496     if (!RHS.isInvalid())
12497       return LHSType;
12498 
12499     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12500   }
12501 
12502   if (!LHSMatType && RHSMatType) {
12503     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12504     if (!LHS.isInvalid())
12505       return RHSType;
12506     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12507   }
12508 
12509   return InvalidOperands(Loc, LHS, RHS);
12510 }
12511 
CheckMatrixMultiplyOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12512 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12513                                            SourceLocation Loc,
12514                                            bool IsCompAssign) {
12515   if (!IsCompAssign) {
12516     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12517     if (LHS.isInvalid())
12518       return QualType();
12519   }
12520   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12521   if (RHS.isInvalid())
12522     return QualType();
12523 
12524   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12525   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12526   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12527 
12528   if (LHSMatType && RHSMatType) {
12529     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12530       return InvalidOperands(Loc, LHS, RHS);
12531 
12532     if (!Context.hasSameType(LHSMatType->getElementType(),
12533                              RHSMatType->getElementType()))
12534       return InvalidOperands(Loc, LHS, RHS);
12535 
12536     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12537                                          LHSMatType->getNumRows(),
12538                                          RHSMatType->getNumColumns());
12539   }
12540   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12541 }
12542 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12543 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12544                                            SourceLocation Loc,
12545                                            BinaryOperatorKind Opc) {
12546   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12547 
12548   bool IsCompAssign =
12549       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12550 
12551   if (LHS.get()->getType()->isVectorType() ||
12552       RHS.get()->getType()->isVectorType()) {
12553     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12554         RHS.get()->getType()->hasIntegerRepresentation())
12555       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12556                         /*AllowBothBool*/true,
12557                         /*AllowBoolConversions*/getLangOpts().ZVector);
12558     return InvalidOperands(Loc, LHS, RHS);
12559   }
12560 
12561   if (Opc == BO_And)
12562     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12563 
12564   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12565       RHS.get()->getType()->hasFloatingRepresentation())
12566     return InvalidOperands(Loc, LHS, RHS);
12567 
12568   ExprResult LHSResult = LHS, RHSResult = RHS;
12569   QualType compType = UsualArithmeticConversions(
12570       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12571   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12572     return QualType();
12573   LHS = LHSResult.get();
12574   RHS = RHSResult.get();
12575 
12576   if (Opc == BO_Xor)
12577     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12578 
12579   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12580     return compType;
12581   return InvalidOperands(Loc, LHS, RHS);
12582 }
12583 
12584 // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12585 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12586                                            SourceLocation Loc,
12587                                            BinaryOperatorKind Opc) {
12588   // Check vector operands differently.
12589   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12590     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12591 
12592   bool EnumConstantInBoolContext = false;
12593   for (const ExprResult &HS : {LHS, RHS}) {
12594     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12595       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12596       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12597         EnumConstantInBoolContext = true;
12598     }
12599   }
12600 
12601   if (EnumConstantInBoolContext)
12602     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12603 
12604   // Diagnose cases where the user write a logical and/or but probably meant a
12605   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12606   // is a constant.
12607   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12608       !LHS.get()->getType()->isBooleanType() &&
12609       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12610       // Don't warn in macros or template instantiations.
12611       !Loc.isMacroID() && !inTemplateInstantiation()) {
12612     // If the RHS can be constant folded, and if it constant folds to something
12613     // that isn't 0 or 1 (which indicate a potential logical operation that
12614     // happened to fold to true/false) then warn.
12615     // Parens on the RHS are ignored.
12616     Expr::EvalResult EVResult;
12617     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12618       llvm::APSInt Result = EVResult.Val.getInt();
12619       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12620            !RHS.get()->getExprLoc().isMacroID()) ||
12621           (Result != 0 && Result != 1)) {
12622         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12623           << RHS.get()->getSourceRange()
12624           << (Opc == BO_LAnd ? "&&" : "||");
12625         // Suggest replacing the logical operator with the bitwise version
12626         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12627             << (Opc == BO_LAnd ? "&" : "|")
12628             << FixItHint::CreateReplacement(SourceRange(
12629                                                  Loc, getLocForEndOfToken(Loc)),
12630                                             Opc == BO_LAnd ? "&" : "|");
12631         if (Opc == BO_LAnd)
12632           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12633           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12634               << FixItHint::CreateRemoval(
12635                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12636                                  RHS.get()->getEndLoc()));
12637       }
12638     }
12639   }
12640 
12641   if (!Context.getLangOpts().CPlusPlus) {
12642     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12643     // not operate on the built-in scalar and vector float types.
12644     if (Context.getLangOpts().OpenCL &&
12645         Context.getLangOpts().OpenCLVersion < 120) {
12646       if (LHS.get()->getType()->isFloatingType() ||
12647           RHS.get()->getType()->isFloatingType())
12648         return InvalidOperands(Loc, LHS, RHS);
12649     }
12650 
12651     LHS = UsualUnaryConversions(LHS.get());
12652     if (LHS.isInvalid())
12653       return QualType();
12654 
12655     RHS = UsualUnaryConversions(RHS.get());
12656     if (RHS.isInvalid())
12657       return QualType();
12658 
12659     if (!LHS.get()->getType()->isScalarType() ||
12660         !RHS.get()->getType()->isScalarType())
12661       return InvalidOperands(Loc, LHS, RHS);
12662 
12663     return Context.IntTy;
12664   }
12665 
12666   // The following is safe because we only use this method for
12667   // non-overloadable operands.
12668 
12669   // C++ [expr.log.and]p1
12670   // C++ [expr.log.or]p1
12671   // The operands are both contextually converted to type bool.
12672   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12673   if (LHSRes.isInvalid())
12674     return InvalidOperands(Loc, LHS, RHS);
12675   LHS = LHSRes;
12676 
12677   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12678   if (RHSRes.isInvalid())
12679     return InvalidOperands(Loc, LHS, RHS);
12680   RHS = RHSRes;
12681 
12682   // C++ [expr.log.and]p2
12683   // C++ [expr.log.or]p2
12684   // The result is a bool.
12685   return Context.BoolTy;
12686 }
12687 
IsReadonlyMessage(Expr * E,Sema & S)12688 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12689   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12690   if (!ME) return false;
12691   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12692   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12693       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12694   if (!Base) return false;
12695   return Base->getMethodDecl() != nullptr;
12696 }
12697 
12698 /// Is the given expression (which must be 'const') a reference to a
12699 /// variable which was originally non-const, but which has become
12700 /// 'const' due to being captured within a block?
12701 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)12702 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12703   assert(E->isLValue() && E->getType().isConstQualified());
12704   E = E->IgnoreParens();
12705 
12706   // Must be a reference to a declaration from an enclosing scope.
12707   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12708   if (!DRE) return NCCK_None;
12709   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12710 
12711   // The declaration must be a variable which is not declared 'const'.
12712   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12713   if (!var) return NCCK_None;
12714   if (var->getType().isConstQualified()) return NCCK_None;
12715   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12716 
12717   // Decide whether the first capture was for a block or a lambda.
12718   DeclContext *DC = S.CurContext, *Prev = nullptr;
12719   // Decide whether the first capture was for a block or a lambda.
12720   while (DC) {
12721     // For init-capture, it is possible that the variable belongs to the
12722     // template pattern of the current context.
12723     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12724       if (var->isInitCapture() &&
12725           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12726         break;
12727     if (DC == var->getDeclContext())
12728       break;
12729     Prev = DC;
12730     DC = DC->getParent();
12731   }
12732   // Unless we have an init-capture, we've gone one step too far.
12733   if (!var->isInitCapture())
12734     DC = Prev;
12735   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12736 }
12737 
IsTypeModifiable(QualType Ty,bool IsDereference)12738 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12739   Ty = Ty.getNonReferenceType();
12740   if (IsDereference && Ty->isPointerType())
12741     Ty = Ty->getPointeeType();
12742   return !Ty.isConstQualified();
12743 }
12744 
12745 // Update err_typecheck_assign_const and note_typecheck_assign_const
12746 // when this enum is changed.
12747 enum {
12748   ConstFunction,
12749   ConstVariable,
12750   ConstMember,
12751   ConstMethod,
12752   NestedConstMember,
12753   ConstUnknown,  // Keep as last element
12754 };
12755 
12756 /// Emit the "read-only variable not assignable" error and print notes to give
12757 /// more information about why the variable is not assignable, such as pointing
12758 /// to the declaration of a const variable, showing that a method is const, or
12759 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)12760 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12761                                     SourceLocation Loc) {
12762   SourceRange ExprRange = E->getSourceRange();
12763 
12764   // Only emit one error on the first const found.  All other consts will emit
12765   // a note to the error.
12766   bool DiagnosticEmitted = false;
12767 
12768   // Track if the current expression is the result of a dereference, and if the
12769   // next checked expression is the result of a dereference.
12770   bool IsDereference = false;
12771   bool NextIsDereference = false;
12772 
12773   // Loop to process MemberExpr chains.
12774   while (true) {
12775     IsDereference = NextIsDereference;
12776 
12777     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12778     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12779       NextIsDereference = ME->isArrow();
12780       const ValueDecl *VD = ME->getMemberDecl();
12781       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12782         // Mutable fields can be modified even if the class is const.
12783         if (Field->isMutable()) {
12784           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12785           break;
12786         }
12787 
12788         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12789           if (!DiagnosticEmitted) {
12790             S.Diag(Loc, diag::err_typecheck_assign_const)
12791                 << ExprRange << ConstMember << false /*static*/ << Field
12792                 << Field->getType();
12793             DiagnosticEmitted = true;
12794           }
12795           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12796               << ConstMember << false /*static*/ << Field << Field->getType()
12797               << Field->getSourceRange();
12798         }
12799         E = ME->getBase();
12800         continue;
12801       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12802         if (VDecl->getType().isConstQualified()) {
12803           if (!DiagnosticEmitted) {
12804             S.Diag(Loc, diag::err_typecheck_assign_const)
12805                 << ExprRange << ConstMember << true /*static*/ << VDecl
12806                 << VDecl->getType();
12807             DiagnosticEmitted = true;
12808           }
12809           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12810               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12811               << VDecl->getSourceRange();
12812         }
12813         // Static fields do not inherit constness from parents.
12814         break;
12815       }
12816       break; // End MemberExpr
12817     } else if (const ArraySubscriptExpr *ASE =
12818                    dyn_cast<ArraySubscriptExpr>(E)) {
12819       E = ASE->getBase()->IgnoreParenImpCasts();
12820       continue;
12821     } else if (const ExtVectorElementExpr *EVE =
12822                    dyn_cast<ExtVectorElementExpr>(E)) {
12823       E = EVE->getBase()->IgnoreParenImpCasts();
12824       continue;
12825     }
12826     break;
12827   }
12828 
12829   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12830     // Function calls
12831     const FunctionDecl *FD = CE->getDirectCallee();
12832     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12833       if (!DiagnosticEmitted) {
12834         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12835                                                       << ConstFunction << FD;
12836         DiagnosticEmitted = true;
12837       }
12838       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12839              diag::note_typecheck_assign_const)
12840           << ConstFunction << FD << FD->getReturnType()
12841           << FD->getReturnTypeSourceRange();
12842     }
12843   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12844     // Point to variable declaration.
12845     if (const ValueDecl *VD = DRE->getDecl()) {
12846       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12847         if (!DiagnosticEmitted) {
12848           S.Diag(Loc, diag::err_typecheck_assign_const)
12849               << ExprRange << ConstVariable << VD << VD->getType();
12850           DiagnosticEmitted = true;
12851         }
12852         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12853             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12854       }
12855     }
12856   } else if (isa<CXXThisExpr>(E)) {
12857     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12858       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12859         if (MD->isConst()) {
12860           if (!DiagnosticEmitted) {
12861             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12862                                                           << ConstMethod << MD;
12863             DiagnosticEmitted = true;
12864           }
12865           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12866               << ConstMethod << MD << MD->getSourceRange();
12867         }
12868       }
12869     }
12870   }
12871 
12872   if (DiagnosticEmitted)
12873     return;
12874 
12875   // Can't determine a more specific message, so display the generic error.
12876   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12877 }
12878 
12879 enum OriginalExprKind {
12880   OEK_Variable,
12881   OEK_Member,
12882   OEK_LValue
12883 };
12884 
DiagnoseRecursiveConstFields(Sema & S,const ValueDecl * VD,const RecordType * Ty,SourceLocation Loc,SourceRange Range,OriginalExprKind OEK,bool & DiagnosticEmitted)12885 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12886                                          const RecordType *Ty,
12887                                          SourceLocation Loc, SourceRange Range,
12888                                          OriginalExprKind OEK,
12889                                          bool &DiagnosticEmitted) {
12890   std::vector<const RecordType *> RecordTypeList;
12891   RecordTypeList.push_back(Ty);
12892   unsigned NextToCheckIndex = 0;
12893   // We walk the record hierarchy breadth-first to ensure that we print
12894   // diagnostics in field nesting order.
12895   while (RecordTypeList.size() > NextToCheckIndex) {
12896     bool IsNested = NextToCheckIndex > 0;
12897     for (const FieldDecl *Field :
12898          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12899       // First, check every field for constness.
12900       QualType FieldTy = Field->getType();
12901       if (FieldTy.isConstQualified()) {
12902         if (!DiagnosticEmitted) {
12903           S.Diag(Loc, diag::err_typecheck_assign_const)
12904               << Range << NestedConstMember << OEK << VD
12905               << IsNested << Field;
12906           DiagnosticEmitted = true;
12907         }
12908         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12909             << NestedConstMember << IsNested << Field
12910             << FieldTy << Field->getSourceRange();
12911       }
12912 
12913       // Then we append it to the list to check next in order.
12914       FieldTy = FieldTy.getCanonicalType();
12915       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12916         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12917           RecordTypeList.push_back(FieldRecTy);
12918       }
12919     }
12920     ++NextToCheckIndex;
12921   }
12922 }
12923 
12924 /// Emit an error for the case where a record we are trying to assign to has a
12925 /// const-qualified field somewhere in its hierarchy.
DiagnoseRecursiveConstFields(Sema & S,const Expr * E,SourceLocation Loc)12926 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12927                                          SourceLocation Loc) {
12928   QualType Ty = E->getType();
12929   assert(Ty->isRecordType() && "lvalue was not record?");
12930   SourceRange Range = E->getSourceRange();
12931   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12932   bool DiagEmitted = false;
12933 
12934   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12935     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12936             Range, OEK_Member, DiagEmitted);
12937   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12938     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12939             Range, OEK_Variable, DiagEmitted);
12940   else
12941     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12942             Range, OEK_LValue, DiagEmitted);
12943   if (!DiagEmitted)
12944     DiagnoseConstAssignment(S, E, Loc);
12945 }
12946 
12947 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12948 /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)12949 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12950   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12951 
12952   S.CheckShadowingDeclModification(E, Loc);
12953 
12954   SourceLocation OrigLoc = Loc;
12955   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12956                                                               &Loc);
12957   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12958     IsLV = Expr::MLV_InvalidMessageExpression;
12959   if (IsLV == Expr::MLV_Valid)
12960     return false;
12961 
12962   unsigned DiagID = 0;
12963   bool NeedType = false;
12964   switch (IsLV) { // C99 6.5.16p2
12965   case Expr::MLV_ConstQualified:
12966     // Use a specialized diagnostic when we're assigning to an object
12967     // from an enclosing function or block.
12968     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12969       if (NCCK == NCCK_Block)
12970         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12971       else
12972         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12973       break;
12974     }
12975 
12976     // In ARC, use some specialized diagnostics for occasions where we
12977     // infer 'const'.  These are always pseudo-strong variables.
12978     if (S.getLangOpts().ObjCAutoRefCount) {
12979       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12980       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12981         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12982 
12983         // Use the normal diagnostic if it's pseudo-__strong but the
12984         // user actually wrote 'const'.
12985         if (var->isARCPseudoStrong() &&
12986             (!var->getTypeSourceInfo() ||
12987              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12988           // There are three pseudo-strong cases:
12989           //  - self
12990           ObjCMethodDecl *method = S.getCurMethodDecl();
12991           if (method && var == method->getSelfDecl()) {
12992             DiagID = method->isClassMethod()
12993               ? diag::err_typecheck_arc_assign_self_class_method
12994               : diag::err_typecheck_arc_assign_self;
12995 
12996           //  - Objective-C externally_retained attribute.
12997           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12998                      isa<ParmVarDecl>(var)) {
12999             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13000 
13001           //  - fast enumeration variables
13002           } else {
13003             DiagID = diag::err_typecheck_arr_assign_enumeration;
13004           }
13005 
13006           SourceRange Assign;
13007           if (Loc != OrigLoc)
13008             Assign = SourceRange(OrigLoc, OrigLoc);
13009           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13010           // We need to preserve the AST regardless, so migration tool
13011           // can do its job.
13012           return false;
13013         }
13014       }
13015     }
13016 
13017     // If none of the special cases above are triggered, then this is a
13018     // simple const assignment.
13019     if (DiagID == 0) {
13020       DiagnoseConstAssignment(S, E, Loc);
13021       return true;
13022     }
13023 
13024     break;
13025   case Expr::MLV_ConstAddrSpace:
13026     DiagnoseConstAssignment(S, E, Loc);
13027     return true;
13028   case Expr::MLV_ConstQualifiedField:
13029     DiagnoseRecursiveConstFields(S, E, Loc);
13030     return true;
13031   case Expr::MLV_ArrayType:
13032   case Expr::MLV_ArrayTemporary:
13033     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13034     NeedType = true;
13035     break;
13036   case Expr::MLV_NotObjectType:
13037     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13038     NeedType = true;
13039     break;
13040   case Expr::MLV_LValueCast:
13041     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13042     break;
13043   case Expr::MLV_Valid:
13044     llvm_unreachable("did not take early return for MLV_Valid");
13045   case Expr::MLV_InvalidExpression:
13046   case Expr::MLV_MemberFunction:
13047   case Expr::MLV_ClassTemporary:
13048     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13049     break;
13050   case Expr::MLV_IncompleteType:
13051   case Expr::MLV_IncompleteVoidType:
13052     return S.RequireCompleteType(Loc, E->getType(),
13053              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13054   case Expr::MLV_DuplicateVectorComponents:
13055     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13056     break;
13057   case Expr::MLV_NoSetterProperty:
13058     llvm_unreachable("readonly properties should be processed differently");
13059   case Expr::MLV_InvalidMessageExpression:
13060     DiagID = diag::err_readonly_message_assignment;
13061     break;
13062   case Expr::MLV_SubObjCPropertySetting:
13063     DiagID = diag::err_no_subobject_property_setting;
13064     break;
13065   }
13066 
13067   SourceRange Assign;
13068   if (Loc != OrigLoc)
13069     Assign = SourceRange(OrigLoc, OrigLoc);
13070   if (NeedType)
13071     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13072   else
13073     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13074   return true;
13075 }
13076 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)13077 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13078                                          SourceLocation Loc,
13079                                          Sema &Sema) {
13080   if (Sema.inTemplateInstantiation())
13081     return;
13082   if (Sema.isUnevaluatedContext())
13083     return;
13084   if (Loc.isInvalid() || Loc.isMacroID())
13085     return;
13086   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13087     return;
13088 
13089   // C / C++ fields
13090   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13091   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13092   if (ML && MR) {
13093     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13094       return;
13095     const ValueDecl *LHSDecl =
13096         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13097     const ValueDecl *RHSDecl =
13098         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13099     if (LHSDecl != RHSDecl)
13100       return;
13101     if (LHSDecl->getType().isVolatileQualified())
13102       return;
13103     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13104       if (RefTy->getPointeeType().isVolatileQualified())
13105         return;
13106 
13107     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13108   }
13109 
13110   // Objective-C instance variables
13111   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13112   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13113   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13114     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13115     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13116     if (RL && RR && RL->getDecl() == RR->getDecl())
13117       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13118   }
13119 }
13120 
13121 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)13122 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13123                                        SourceLocation Loc,
13124                                        QualType CompoundType) {
13125   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13126 
13127   // Verify that LHS is a modifiable lvalue, and emit error if not.
13128   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13129     return QualType();
13130 
13131   QualType LHSType = LHSExpr->getType();
13132   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13133                                              CompoundType;
13134   // OpenCL v1.2 s6.1.1.1 p2:
13135   // The half data type can only be used to declare a pointer to a buffer that
13136   // contains half values
13137   if (getLangOpts().OpenCL &&
13138       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13139       LHSType->isHalfType()) {
13140     Diag(Loc, diag::err_opencl_half_load_store) << 1
13141         << LHSType.getUnqualifiedType();
13142     return QualType();
13143   }
13144 
13145   AssignConvertType ConvTy;
13146   if (CompoundType.isNull()) {
13147     Expr *RHSCheck = RHS.get();
13148 
13149     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13150 
13151     QualType LHSTy(LHSType);
13152     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13153     if (RHS.isInvalid())
13154       return QualType();
13155     // Special case of NSObject attributes on c-style pointer types.
13156     if (ConvTy == IncompatiblePointer &&
13157         ((Context.isObjCNSObjectType(LHSType) &&
13158           RHSType->isObjCObjectPointerType()) ||
13159          (Context.isObjCNSObjectType(RHSType) &&
13160           LHSType->isObjCObjectPointerType())))
13161       ConvTy = Compatible;
13162 
13163     if (ConvTy == Compatible &&
13164         LHSType->isObjCObjectType())
13165         Diag(Loc, diag::err_objc_object_assignment)
13166           << LHSType;
13167 
13168     // If the RHS is a unary plus or minus, check to see if they = and + are
13169     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13170     // instead of "x += 4".
13171     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13172       RHSCheck = ICE->getSubExpr();
13173     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13174       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13175           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13176           // Only if the two operators are exactly adjacent.
13177           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13178           // And there is a space or other character before the subexpr of the
13179           // unary +/-.  We don't want to warn on "x=-1".
13180           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13181           UO->getSubExpr()->getBeginLoc().isFileID()) {
13182         Diag(Loc, diag::warn_not_compound_assign)
13183           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13184           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13185       }
13186     }
13187 
13188     if (ConvTy == Compatible) {
13189       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13190         // Warn about retain cycles where a block captures the LHS, but
13191         // not if the LHS is a simple variable into which the block is
13192         // being stored...unless that variable can be captured by reference!
13193         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13194         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13195         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13196           checkRetainCycles(LHSExpr, RHS.get());
13197       }
13198 
13199       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13200           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13201         // It is safe to assign a weak reference into a strong variable.
13202         // Although this code can still have problems:
13203         //   id x = self.weakProp;
13204         //   id y = self.weakProp;
13205         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13206         // paths through the function. This should be revisited if
13207         // -Wrepeated-use-of-weak is made flow-sensitive.
13208         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13209         // variable, which will be valid for the current autorelease scope.
13210         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13211                              RHS.get()->getBeginLoc()))
13212           getCurFunction()->markSafeWeakUse(RHS.get());
13213 
13214       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13215         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13216       }
13217     }
13218   } else {
13219     // Compound assignment "x += y"
13220     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13221   }
13222 
13223   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13224                                RHS.get(), AA_Assigning))
13225     return QualType();
13226 
13227   CheckForNullPointerDereference(*this, LHSExpr);
13228 
13229   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13230     if (CompoundType.isNull()) {
13231       // C++2a [expr.ass]p5:
13232       //   A simple-assignment whose left operand is of a volatile-qualified
13233       //   type is deprecated unless the assignment is either a discarded-value
13234       //   expression or an unevaluated operand
13235       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13236     } else {
13237       // C++2a [expr.ass]p6:
13238       //   [Compound-assignment] expressions are deprecated if E1 has
13239       //   volatile-qualified type
13240       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13241     }
13242   }
13243 
13244   // C99 6.5.16p3: The type of an assignment expression is the type of the
13245   // left operand unless the left operand has qualified type, in which case
13246   // it is the unqualified version of the type of the left operand.
13247   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13248   // is converted to the type of the assignment expression (above).
13249   // C++ 5.17p1: the type of the assignment expression is that of its left
13250   // operand.
13251   return (getLangOpts().CPlusPlus
13252           ? LHSType : LHSType.getUnqualifiedType());
13253 }
13254 
13255 // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)13256 static bool IgnoreCommaOperand(const Expr *E) {
13257   E = E->IgnoreParens();
13258 
13259   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13260     if (CE->getCastKind() == CK_ToVoid) {
13261       return true;
13262     }
13263 
13264     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13265     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13266         CE->getSubExpr()->getType()->isDependentType()) {
13267       return true;
13268     }
13269   }
13270 
13271   return false;
13272 }
13273 
13274 // Look for instances where it is likely the comma operator is confused with
13275 // another operator.  There is an explicit list of acceptable expressions for
13276 // the left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)13277 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13278   // No warnings in macros
13279   if (Loc.isMacroID())
13280     return;
13281 
13282   // Don't warn in template instantiations.
13283   if (inTemplateInstantiation())
13284     return;
13285 
13286   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13287   // instead, skip more than needed, then call back into here with the
13288   // CommaVisitor in SemaStmt.cpp.
13289   // The listed locations are the initialization and increment portions
13290   // of a for loop.  The additional checks are on the condition of
13291   // if statements, do/while loops, and for loops.
13292   // Differences in scope flags for C89 mode requires the extra logic.
13293   const unsigned ForIncrementFlags =
13294       getLangOpts().C99 || getLangOpts().CPlusPlus
13295           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13296           : Scope::ContinueScope | Scope::BreakScope;
13297   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13298   const unsigned ScopeFlags = getCurScope()->getFlags();
13299   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13300       (ScopeFlags & ForInitFlags) == ForInitFlags)
13301     return;
13302 
13303   // If there are multiple comma operators used together, get the RHS of the
13304   // of the comma operator as the LHS.
13305   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13306     if (BO->getOpcode() != BO_Comma)
13307       break;
13308     LHS = BO->getRHS();
13309   }
13310 
13311   // Only allow some expressions on LHS to not warn.
13312   if (IgnoreCommaOperand(LHS))
13313     return;
13314 
13315   Diag(Loc, diag::warn_comma_operator);
13316   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13317       << LHS->getSourceRange()
13318       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13319                                     LangOpts.CPlusPlus ? "static_cast<void>("
13320                                                        : "(void)(")
13321       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13322                                     ")");
13323 }
13324 
13325 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)13326 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13327                                    SourceLocation Loc) {
13328   LHS = S.CheckPlaceholderExpr(LHS.get());
13329   RHS = S.CheckPlaceholderExpr(RHS.get());
13330   if (LHS.isInvalid() || RHS.isInvalid())
13331     return QualType();
13332 
13333   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13334   // operands, but not unary promotions.
13335   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13336 
13337   // So we treat the LHS as a ignored value, and in C++ we allow the
13338   // containing site to determine what should be done with the RHS.
13339   LHS = S.IgnoredValueConversions(LHS.get());
13340   if (LHS.isInvalid())
13341     return QualType();
13342 
13343   S.DiagnoseUnusedExprResult(LHS.get());
13344 
13345   if (!S.getLangOpts().CPlusPlus) {
13346     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13347     if (RHS.isInvalid())
13348       return QualType();
13349     if (!RHS.get()->getType()->isVoidType())
13350       S.RequireCompleteType(Loc, RHS.get()->getType(),
13351                             diag::err_incomplete_type);
13352   }
13353 
13354   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13355     S.DiagnoseCommaOperator(LHS.get(), Loc);
13356 
13357   return RHS.get()->getType();
13358 }
13359 
13360 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13361 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)13362 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13363                                                ExprValueKind &VK,
13364                                                ExprObjectKind &OK,
13365                                                SourceLocation OpLoc,
13366                                                bool IsInc, bool IsPrefix) {
13367   if (Op->isTypeDependent())
13368     return S.Context.DependentTy;
13369 
13370   QualType ResType = Op->getType();
13371   // Atomic types can be used for increment / decrement where the non-atomic
13372   // versions can, so ignore the _Atomic() specifier for the purpose of
13373   // checking.
13374   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13375     ResType = ResAtomicType->getValueType();
13376 
13377   assert(!ResType.isNull() && "no type for increment/decrement expression");
13378 
13379   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13380     // Decrement of bool is not allowed.
13381     if (!IsInc) {
13382       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13383       return QualType();
13384     }
13385     // Increment of bool sets it to true, but is deprecated.
13386     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13387                                               : diag::warn_increment_bool)
13388       << Op->getSourceRange();
13389   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13390     // Error on enum increments and decrements in C++ mode
13391     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13392     return QualType();
13393   } else if (ResType->isRealType()) {
13394     // OK!
13395   } else if (ResType->isPointerType()) {
13396     // C99 6.5.2.4p2, 6.5.6p2
13397     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13398       return QualType();
13399   } else if (ResType->isObjCObjectPointerType()) {
13400     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13401     // Otherwise, we just need a complete type.
13402     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13403         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13404       return QualType();
13405   } else if (ResType->isAnyComplexType()) {
13406     // C99 does not support ++/-- on complex types, we allow as an extension.
13407     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13408       << ResType << Op->getSourceRange();
13409   } else if (ResType->isPlaceholderType()) {
13410     ExprResult PR = S.CheckPlaceholderExpr(Op);
13411     if (PR.isInvalid()) return QualType();
13412     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13413                                           IsInc, IsPrefix);
13414   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13415     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13416   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13417              (ResType->castAs<VectorType>()->getVectorKind() !=
13418               VectorType::AltiVecBool)) {
13419     // The z vector extensions allow ++ and -- for non-bool vectors.
13420   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13421             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13422     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13423   } else {
13424     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13425       << ResType << int(IsInc) << Op->getSourceRange();
13426     return QualType();
13427   }
13428   // At this point, we know we have a real, complex or pointer type.
13429   // Now make sure the operand is a modifiable lvalue.
13430   if (CheckForModifiableLvalue(Op, OpLoc, S))
13431     return QualType();
13432   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13433     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13434     //   An operand with volatile-qualified type is deprecated
13435     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13436         << IsInc << ResType;
13437   }
13438   // In C++, a prefix increment is the same type as the operand. Otherwise
13439   // (in C or with postfix), the increment is the unqualified type of the
13440   // operand.
13441   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13442     VK = VK_LValue;
13443     OK = Op->getObjectKind();
13444     return ResType;
13445   } else {
13446     VK = VK_PRValue;
13447     return ResType.getUnqualifiedType();
13448   }
13449 }
13450 
13451 
13452 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13453 /// This routine allows us to typecheck complex/recursive expressions
13454 /// where the declaration is needed for type checking. We only need to
13455 /// handle cases when the expression references a function designator
13456 /// or is an lvalue. Here are some examples:
13457 ///  - &(x) => x
13458 ///  - &*****f => f for f a function designator.
13459 ///  - &s.xx => s
13460 ///  - &s.zz[1].yy -> s, if zz is an array
13461 ///  - *(x + 1) -> x, if x is an array
13462 ///  - &"123"[2] -> 0
13463 ///  - & __real__ x -> x
13464 ///
13465 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13466 /// members.
getPrimaryDecl(Expr * E)13467 static ValueDecl *getPrimaryDecl(Expr *E) {
13468   switch (E->getStmtClass()) {
13469   case Stmt::DeclRefExprClass:
13470     return cast<DeclRefExpr>(E)->getDecl();
13471   case Stmt::MemberExprClass:
13472     // If this is an arrow operator, the address is an offset from
13473     // the base's value, so the object the base refers to is
13474     // irrelevant.
13475     if (cast<MemberExpr>(E)->isArrow())
13476       return nullptr;
13477     // Otherwise, the expression refers to a part of the base
13478     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13479   case Stmt::ArraySubscriptExprClass: {
13480     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13481     // promotion of register arrays earlier.
13482     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13483     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13484       if (ICE->getSubExpr()->getType()->isArrayType())
13485         return getPrimaryDecl(ICE->getSubExpr());
13486     }
13487     return nullptr;
13488   }
13489   case Stmt::UnaryOperatorClass: {
13490     UnaryOperator *UO = cast<UnaryOperator>(E);
13491 
13492     switch(UO->getOpcode()) {
13493     case UO_Real:
13494     case UO_Imag:
13495     case UO_Extension:
13496       return getPrimaryDecl(UO->getSubExpr());
13497     default:
13498       return nullptr;
13499     }
13500   }
13501   case Stmt::ParenExprClass:
13502     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13503   case Stmt::ImplicitCastExprClass:
13504     // If the result of an implicit cast is an l-value, we care about
13505     // the sub-expression; otherwise, the result here doesn't matter.
13506     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13507   case Stmt::CXXUuidofExprClass:
13508     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13509   default:
13510     return nullptr;
13511   }
13512 }
13513 
13514 namespace {
13515 enum {
13516   AO_Bit_Field = 0,
13517   AO_Vector_Element = 1,
13518   AO_Property_Expansion = 2,
13519   AO_Register_Variable = 3,
13520   AO_Matrix_Element = 4,
13521   AO_No_Error = 5
13522 };
13523 }
13524 /// Diagnose invalid operand for address of operations.
13525 ///
13526 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)13527 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13528                                          Expr *E, unsigned Type) {
13529   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13530 }
13531 
13532 /// CheckAddressOfOperand - The operand of & must be either a function
13533 /// designator or an lvalue designating an object. If it is an lvalue, the
13534 /// object cannot be declared with storage class register or be a bit field.
13535 /// Note: The usual conversions are *not* applied to the operand of the &
13536 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13537 /// In C++, the operand might be an overloaded function name, in which case
13538 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)13539 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13540   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13541     if (PTy->getKind() == BuiltinType::Overload) {
13542       Expr *E = OrigOp.get()->IgnoreParens();
13543       if (!isa<OverloadExpr>(E)) {
13544         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13545         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13546           << OrigOp.get()->getSourceRange();
13547         return QualType();
13548       }
13549 
13550       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13551       if (isa<UnresolvedMemberExpr>(Ovl))
13552         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13553           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13554             << OrigOp.get()->getSourceRange();
13555           return QualType();
13556         }
13557 
13558       return Context.OverloadTy;
13559     }
13560 
13561     if (PTy->getKind() == BuiltinType::UnknownAny)
13562       return Context.UnknownAnyTy;
13563 
13564     if (PTy->getKind() == BuiltinType::BoundMember) {
13565       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13566         << OrigOp.get()->getSourceRange();
13567       return QualType();
13568     }
13569 
13570     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13571     if (OrigOp.isInvalid()) return QualType();
13572   }
13573 
13574   if (OrigOp.get()->isTypeDependent())
13575     return Context.DependentTy;
13576 
13577   assert(!OrigOp.get()->getType()->isPlaceholderType());
13578 
13579   // Make sure to ignore parentheses in subsequent checks
13580   Expr *op = OrigOp.get()->IgnoreParens();
13581 
13582   // In OpenCL captures for blocks called as lambda functions
13583   // are located in the private address space. Blocks used in
13584   // enqueue_kernel can be located in a different address space
13585   // depending on a vendor implementation. Thus preventing
13586   // taking an address of the capture to avoid invalid AS casts.
13587   if (LangOpts.OpenCL) {
13588     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13589     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13590       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13591       return QualType();
13592     }
13593   }
13594 
13595   if (getLangOpts().C99) {
13596     // Implement C99-only parts of addressof rules.
13597     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13598       if (uOp->getOpcode() == UO_Deref)
13599         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13600         // (assuming the deref expression is valid).
13601         return uOp->getSubExpr()->getType();
13602     }
13603     // Technically, there should be a check for array subscript
13604     // expressions here, but the result of one is always an lvalue anyway.
13605   }
13606   ValueDecl *dcl = getPrimaryDecl(op);
13607 
13608   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13609     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13610                                            op->getBeginLoc()))
13611       return QualType();
13612 
13613   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13614   unsigned AddressOfError = AO_No_Error;
13615 
13616   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13617     bool sfinae = (bool)isSFINAEContext();
13618     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13619                                   : diag::ext_typecheck_addrof_temporary)
13620       << op->getType() << op->getSourceRange();
13621     if (sfinae)
13622       return QualType();
13623     // Materialize the temporary as an lvalue so that we can take its address.
13624     OrigOp = op =
13625         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13626   } else if (isa<ObjCSelectorExpr>(op)) {
13627     return Context.getPointerType(op->getType());
13628   } else if (lval == Expr::LV_MemberFunction) {
13629     // If it's an instance method, make a member pointer.
13630     // The expression must have exactly the form &A::foo.
13631 
13632     // If the underlying expression isn't a decl ref, give up.
13633     if (!isa<DeclRefExpr>(op)) {
13634       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13635         << OrigOp.get()->getSourceRange();
13636       return QualType();
13637     }
13638     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13639     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13640 
13641     // The id-expression was parenthesized.
13642     if (OrigOp.get() != DRE) {
13643       Diag(OpLoc, diag::err_parens_pointer_member_function)
13644         << OrigOp.get()->getSourceRange();
13645 
13646     // The method was named without a qualifier.
13647     } else if (!DRE->getQualifier()) {
13648       if (MD->getParent()->getName().empty())
13649         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13650           << op->getSourceRange();
13651       else {
13652         SmallString<32> Str;
13653         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13654         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13655           << op->getSourceRange()
13656           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13657       }
13658     }
13659 
13660     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13661     if (isa<CXXDestructorDecl>(MD))
13662       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13663 
13664     QualType MPTy = Context.getMemberPointerType(
13665         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13666     // Under the MS ABI, lock down the inheritance model now.
13667     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13668       (void)isCompleteType(OpLoc, MPTy);
13669     return MPTy;
13670   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13671     // C99 6.5.3.2p1
13672     // The operand must be either an l-value or a function designator
13673     if (!op->getType()->isFunctionType()) {
13674       // Use a special diagnostic for loads from property references.
13675       if (isa<PseudoObjectExpr>(op)) {
13676         AddressOfError = AO_Property_Expansion;
13677       } else {
13678         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13679           << op->getType() << op->getSourceRange();
13680         return QualType();
13681       }
13682     }
13683   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13684     // The operand cannot be a bit-field
13685     AddressOfError = AO_Bit_Field;
13686   } else if (op->getObjectKind() == OK_VectorComponent) {
13687     // The operand cannot be an element of a vector
13688     AddressOfError = AO_Vector_Element;
13689   } else if (op->getObjectKind() == OK_MatrixComponent) {
13690     // The operand cannot be an element of a matrix.
13691     AddressOfError = AO_Matrix_Element;
13692   } else if (dcl) { // C99 6.5.3.2p1
13693     // We have an lvalue with a decl. Make sure the decl is not declared
13694     // with the register storage-class specifier.
13695     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13696       // in C++ it is not error to take address of a register
13697       // variable (c++03 7.1.1P3)
13698       if (vd->getStorageClass() == SC_Register &&
13699           !getLangOpts().CPlusPlus) {
13700         AddressOfError = AO_Register_Variable;
13701       }
13702     } else if (isa<MSPropertyDecl>(dcl)) {
13703       AddressOfError = AO_Property_Expansion;
13704     } else if (isa<FunctionTemplateDecl>(dcl)) {
13705       return Context.OverloadTy;
13706     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13707       // Okay: we can take the address of a field.
13708       // Could be a pointer to member, though, if there is an explicit
13709       // scope qualifier for the class.
13710       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13711         DeclContext *Ctx = dcl->getDeclContext();
13712         if (Ctx && Ctx->isRecord()) {
13713           if (dcl->getType()->isReferenceType()) {
13714             Diag(OpLoc,
13715                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13716               << dcl->getDeclName() << dcl->getType();
13717             return QualType();
13718           }
13719 
13720           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13721             Ctx = Ctx->getParent();
13722 
13723           QualType MPTy = Context.getMemberPointerType(
13724               op->getType(),
13725               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13726           // Under the MS ABI, lock down the inheritance model now.
13727           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13728             (void)isCompleteType(OpLoc, MPTy);
13729           return MPTy;
13730         }
13731       }
13732     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13733                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13734       llvm_unreachable("Unknown/unexpected decl type");
13735   }
13736 
13737   if (AddressOfError != AO_No_Error) {
13738     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13739     return QualType();
13740   }
13741 
13742   if (lval == Expr::LV_IncompleteVoidType) {
13743     // Taking the address of a void variable is technically illegal, but we
13744     // allow it in cases which are otherwise valid.
13745     // Example: "extern void x; void* y = &x;".
13746     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13747   }
13748 
13749   // If the operand has type "type", the result has type "pointer to type".
13750   if (op->getType()->isObjCObjectType())
13751     return Context.getObjCObjectPointerType(op->getType());
13752 
13753   CheckAddressOfPackedMember(op);
13754 
13755   return Context.getPointerType(op->getType());
13756 }
13757 
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)13758 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13759   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13760   if (!DRE)
13761     return;
13762   const Decl *D = DRE->getDecl();
13763   if (!D)
13764     return;
13765   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13766   if (!Param)
13767     return;
13768   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13769     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13770       return;
13771   if (FunctionScopeInfo *FD = S.getCurFunction())
13772     if (!FD->ModifiedNonNullParams.count(Param))
13773       FD->ModifiedNonNullParams.insert(Param);
13774 }
13775 
13776 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)13777 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13778                                         SourceLocation OpLoc) {
13779   if (Op->isTypeDependent())
13780     return S.Context.DependentTy;
13781 
13782   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13783   if (ConvResult.isInvalid())
13784     return QualType();
13785   Op = ConvResult.get();
13786   QualType OpTy = Op->getType();
13787   QualType Result;
13788 
13789   if (isa<CXXReinterpretCastExpr>(Op)) {
13790     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13791     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13792                                      Op->getSourceRange());
13793   }
13794 
13795   if (const PointerType *PT = OpTy->getAs<PointerType>())
13796   {
13797     Result = PT->getPointeeType();
13798   }
13799   else if (const ObjCObjectPointerType *OPT =
13800              OpTy->getAs<ObjCObjectPointerType>())
13801     Result = OPT->getPointeeType();
13802   else {
13803     ExprResult PR = S.CheckPlaceholderExpr(Op);
13804     if (PR.isInvalid()) return QualType();
13805     if (PR.get() != Op)
13806       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13807   }
13808 
13809   if (Result.isNull()) {
13810     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13811       << OpTy << Op->getSourceRange();
13812     return QualType();
13813   }
13814 
13815   // Note that per both C89 and C99, indirection is always legal, even if Result
13816   // is an incomplete type or void.  It would be possible to warn about
13817   // dereferencing a void pointer, but it's completely well-defined, and such a
13818   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13819   // for pointers to 'void' but is fine for any other pointer type:
13820   //
13821   // C++ [expr.unary.op]p1:
13822   //   [...] the expression to which [the unary * operator] is applied shall
13823   //   be a pointer to an object type, or a pointer to a function type
13824   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13825     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13826       << OpTy << Op->getSourceRange();
13827 
13828   // Dereferences are usually l-values...
13829   VK = VK_LValue;
13830 
13831   // ...except that certain expressions are never l-values in C.
13832   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13833     VK = VK_PRValue;
13834 
13835   return Result;
13836 }
13837 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)13838 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13839   BinaryOperatorKind Opc;
13840   switch (Kind) {
13841   default: llvm_unreachable("Unknown binop!");
13842   case tok::periodstar:           Opc = BO_PtrMemD; break;
13843   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13844   case tok::star:                 Opc = BO_Mul; break;
13845   case tok::slash:                Opc = BO_Div; break;
13846   case tok::percent:              Opc = BO_Rem; break;
13847   case tok::plus:                 Opc = BO_Add; break;
13848   case tok::minus:                Opc = BO_Sub; break;
13849   case tok::lessless:             Opc = BO_Shl; break;
13850   case tok::greatergreater:       Opc = BO_Shr; break;
13851   case tok::lessequal:            Opc = BO_LE; break;
13852   case tok::less:                 Opc = BO_LT; break;
13853   case tok::greaterequal:         Opc = BO_GE; break;
13854   case tok::greater:              Opc = BO_GT; break;
13855   case tok::exclaimequal:         Opc = BO_NE; break;
13856   case tok::equalequal:           Opc = BO_EQ; break;
13857   case tok::spaceship:            Opc = BO_Cmp; break;
13858   case tok::amp:                  Opc = BO_And; break;
13859   case tok::caret:                Opc = BO_Xor; break;
13860   case tok::pipe:                 Opc = BO_Or; break;
13861   case tok::ampamp:               Opc = BO_LAnd; break;
13862   case tok::pipepipe:             Opc = BO_LOr; break;
13863   case tok::equal:                Opc = BO_Assign; break;
13864   case tok::starequal:            Opc = BO_MulAssign; break;
13865   case tok::slashequal:           Opc = BO_DivAssign; break;
13866   case tok::percentequal:         Opc = BO_RemAssign; break;
13867   case tok::plusequal:            Opc = BO_AddAssign; break;
13868   case tok::minusequal:           Opc = BO_SubAssign; break;
13869   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13870   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13871   case tok::ampequal:             Opc = BO_AndAssign; break;
13872   case tok::caretequal:           Opc = BO_XorAssign; break;
13873   case tok::pipeequal:            Opc = BO_OrAssign; break;
13874   case tok::comma:                Opc = BO_Comma; break;
13875   }
13876   return Opc;
13877 }
13878 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)13879 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13880   tok::TokenKind Kind) {
13881   UnaryOperatorKind Opc;
13882   switch (Kind) {
13883   default: llvm_unreachable("Unknown unary op!");
13884   case tok::plusplus:     Opc = UO_PreInc; break;
13885   case tok::minusminus:   Opc = UO_PreDec; break;
13886   case tok::amp:          Opc = UO_AddrOf; break;
13887   case tok::star:         Opc = UO_Deref; break;
13888   case tok::plus:         Opc = UO_Plus; break;
13889   case tok::minus:        Opc = UO_Minus; break;
13890   case tok::tilde:        Opc = UO_Not; break;
13891   case tok::exclaim:      Opc = UO_LNot; break;
13892   case tok::kw___real:    Opc = UO_Real; break;
13893   case tok::kw___imag:    Opc = UO_Imag; break;
13894   case tok::kw___extension__: Opc = UO_Extension; break;
13895   }
13896   return Opc;
13897 }
13898 
13899 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13900 /// This warning suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc,bool IsBuiltin)13901 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13902                                    SourceLocation OpLoc, bool IsBuiltin) {
13903   if (S.inTemplateInstantiation())
13904     return;
13905   if (S.isUnevaluatedContext())
13906     return;
13907   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13908     return;
13909   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13910   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13911   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13912   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13913   if (!LHSDeclRef || !RHSDeclRef ||
13914       LHSDeclRef->getLocation().isMacroID() ||
13915       RHSDeclRef->getLocation().isMacroID())
13916     return;
13917   const ValueDecl *LHSDecl =
13918     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13919   const ValueDecl *RHSDecl =
13920     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13921   if (LHSDecl != RHSDecl)
13922     return;
13923   if (LHSDecl->getType().isVolatileQualified())
13924     return;
13925   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13926     if (RefTy->getPointeeType().isVolatileQualified())
13927       return;
13928 
13929   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13930                           : diag::warn_self_assignment_overloaded)
13931       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13932       << RHSExpr->getSourceRange();
13933 }
13934 
13935 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13936 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)13937 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13938                                           SourceLocation OpLoc) {
13939   if (!S.getLangOpts().ObjC)
13940     return;
13941 
13942   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13943   const Expr *LHS = L.get();
13944   const Expr *RHS = R.get();
13945 
13946   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13947     ObjCPointerExpr = LHS;
13948     OtherExpr = RHS;
13949   }
13950   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13951     ObjCPointerExpr = RHS;
13952     OtherExpr = LHS;
13953   }
13954 
13955   // This warning is deliberately made very specific to reduce false
13956   // positives with logic that uses '&' for hashing.  This logic mainly
13957   // looks for code trying to introspect into tagged pointers, which
13958   // code should generally never do.
13959   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13960     unsigned Diag = diag::warn_objc_pointer_masking;
13961     // Determine if we are introspecting the result of performSelectorXXX.
13962     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13963     // Special case messages to -performSelector and friends, which
13964     // can return non-pointer values boxed in a pointer value.
13965     // Some clients may wish to silence warnings in this subcase.
13966     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13967       Selector S = ME->getSelector();
13968       StringRef SelArg0 = S.getNameForSlot(0);
13969       if (SelArg0.startswith("performSelector"))
13970         Diag = diag::warn_objc_pointer_masking_performSelector;
13971     }
13972 
13973     S.Diag(OpLoc, Diag)
13974       << ObjCPointerExpr->getSourceRange();
13975   }
13976 }
13977 
getDeclFromExpr(Expr * E)13978 static NamedDecl *getDeclFromExpr(Expr *E) {
13979   if (!E)
13980     return nullptr;
13981   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13982     return DRE->getDecl();
13983   if (auto *ME = dyn_cast<MemberExpr>(E))
13984     return ME->getMemberDecl();
13985   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13986     return IRE->getDecl();
13987   return nullptr;
13988 }
13989 
13990 // This helper function promotes a binary operator's operands (which are of a
13991 // half vector type) to a vector of floats and then truncates the result to
13992 // a vector of either half or short.
convertHalfVecBinOp(Sema & S,ExprResult LHS,ExprResult RHS,BinaryOperatorKind Opc,QualType ResultTy,ExprValueKind VK,ExprObjectKind OK,bool IsCompAssign,SourceLocation OpLoc,FPOptionsOverride FPFeatures)13993 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13994                                       BinaryOperatorKind Opc, QualType ResultTy,
13995                                       ExprValueKind VK, ExprObjectKind OK,
13996                                       bool IsCompAssign, SourceLocation OpLoc,
13997                                       FPOptionsOverride FPFeatures) {
13998   auto &Context = S.getASTContext();
13999   assert((isVector(ResultTy, Context.HalfTy) ||
14000           isVector(ResultTy, Context.ShortTy)) &&
14001          "Result must be a vector of half or short");
14002   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14003          isVector(RHS.get()->getType(), Context.HalfTy) &&
14004          "both operands expected to be a half vector");
14005 
14006   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14007   QualType BinOpResTy = RHS.get()->getType();
14008 
14009   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14010   // change BinOpResTy to a vector of ints.
14011   if (isVector(ResultTy, Context.ShortTy))
14012     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14013 
14014   if (IsCompAssign)
14015     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14016                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14017                                           BinOpResTy, BinOpResTy);
14018 
14019   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14020   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14021                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14022   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14023 }
14024 
14025 static std::pair<ExprResult, ExprResult>
CorrectDelayedTyposInBinOp(Sema & S,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14026 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14027                            Expr *RHSExpr) {
14028   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14029   if (!S.Context.isDependenceAllowed()) {
14030     // C cannot handle TypoExpr nodes on either side of a binop because it
14031     // doesn't handle dependent types properly, so make sure any TypoExprs have
14032     // been dealt with before checking the operands.
14033     LHS = S.CorrectDelayedTyposInExpr(LHS);
14034     RHS = S.CorrectDelayedTyposInExpr(
14035         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14036         [Opc, LHS](Expr *E) {
14037           if (Opc != BO_Assign)
14038             return ExprResult(E);
14039           // Avoid correcting the RHS to the same Expr as the LHS.
14040           Decl *D = getDeclFromExpr(E);
14041           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14042         });
14043   }
14044   return std::make_pair(LHS, RHS);
14045 }
14046 
14047 /// Returns true if conversion between vectors of halfs and vectors of floats
14048 /// is needed.
needsConversionOfHalfVec(bool OpRequiresConversion,ASTContext & Ctx,Expr * E0,Expr * E1=nullptr)14049 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14050                                      Expr *E0, Expr *E1 = nullptr) {
14051   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14052       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14053     return false;
14054 
14055   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14056     QualType Ty = E->IgnoreImplicit()->getType();
14057 
14058     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14059     // to vectors of floats. Although the element type of the vectors is __fp16,
14060     // the vectors shouldn't be treated as storage-only types. See the
14061     // discussion here: https://reviews.llvm.org/rG825235c140e7
14062     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14063       if (VT->getVectorKind() == VectorType::NeonVector)
14064         return false;
14065       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14066     }
14067     return false;
14068   };
14069 
14070   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14071 }
14072 
14073 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14074 /// operator @p Opc at location @c TokLoc. This routine only supports
14075 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14076 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14077                                     BinaryOperatorKind Opc,
14078                                     Expr *LHSExpr, Expr *RHSExpr) {
14079   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14080     // The syntax only allows initializer lists on the RHS of assignment,
14081     // so we don't need to worry about accepting invalid code for
14082     // non-assignment operators.
14083     // C++11 5.17p9:
14084     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14085     //   of x = {} is x = T().
14086     InitializationKind Kind = InitializationKind::CreateDirectList(
14087         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14088     InitializedEntity Entity =
14089         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14090     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14091     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14092     if (Init.isInvalid())
14093       return Init;
14094     RHSExpr = Init.get();
14095   }
14096 
14097   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14098   QualType ResultTy;     // Result type of the binary operator.
14099   // The following two variables are used for compound assignment operators
14100   QualType CompLHSTy;    // Type of LHS after promotions for computation
14101   QualType CompResultTy; // Type of computation result
14102   ExprValueKind VK = VK_PRValue;
14103   ExprObjectKind OK = OK_Ordinary;
14104   bool ConvertHalfVec = false;
14105 
14106   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14107   if (!LHS.isUsable() || !RHS.isUsable())
14108     return ExprError();
14109 
14110   if (getLangOpts().OpenCL) {
14111     QualType LHSTy = LHSExpr->getType();
14112     QualType RHSTy = RHSExpr->getType();
14113     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14114     // the ATOMIC_VAR_INIT macro.
14115     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14116       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14117       if (BO_Assign == Opc)
14118         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14119       else
14120         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14121       return ExprError();
14122     }
14123 
14124     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14125     // only with a builtin functions and therefore should be disallowed here.
14126     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14127         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14128         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14129         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14130       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14131       return ExprError();
14132     }
14133   }
14134 
14135   switch (Opc) {
14136   case BO_Assign:
14137     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14138     if (getLangOpts().CPlusPlus &&
14139         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14140       VK = LHS.get()->getValueKind();
14141       OK = LHS.get()->getObjectKind();
14142     }
14143     if (!ResultTy.isNull()) {
14144       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14145       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14146 
14147       // Avoid copying a block to the heap if the block is assigned to a local
14148       // auto variable that is declared in the same scope as the block. This
14149       // optimization is unsafe if the local variable is declared in an outer
14150       // scope. For example:
14151       //
14152       // BlockTy b;
14153       // {
14154       //   b = ^{...};
14155       // }
14156       // // It is unsafe to invoke the block here if it wasn't copied to the
14157       // // heap.
14158       // b();
14159 
14160       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14161         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14162           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14163             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14164               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14165 
14166       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14167         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14168                               NTCUC_Assignment, NTCUK_Copy);
14169     }
14170     RecordModifiableNonNullParam(*this, LHS.get());
14171     break;
14172   case BO_PtrMemD:
14173   case BO_PtrMemI:
14174     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14175                                             Opc == BO_PtrMemI);
14176     break;
14177   case BO_Mul:
14178   case BO_Div:
14179     ConvertHalfVec = true;
14180     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14181                                            Opc == BO_Div);
14182     break;
14183   case BO_Rem:
14184     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14185     break;
14186   case BO_Add:
14187     ConvertHalfVec = true;
14188     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14189     break;
14190   case BO_Sub:
14191     ConvertHalfVec = true;
14192     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14193     break;
14194   case BO_Shl:
14195   case BO_Shr:
14196     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14197     break;
14198   case BO_LE:
14199   case BO_LT:
14200   case BO_GE:
14201   case BO_GT:
14202     ConvertHalfVec = true;
14203     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14204     break;
14205   case BO_EQ:
14206   case BO_NE:
14207     ConvertHalfVec = true;
14208     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14209     break;
14210   case BO_Cmp:
14211     ConvertHalfVec = true;
14212     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14213     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14214     break;
14215   case BO_And:
14216     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14217     LLVM_FALLTHROUGH;
14218   case BO_Xor:
14219   case BO_Or:
14220     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14221     break;
14222   case BO_LAnd:
14223   case BO_LOr:
14224     ConvertHalfVec = true;
14225     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14226     break;
14227   case BO_MulAssign:
14228   case BO_DivAssign:
14229     ConvertHalfVec = true;
14230     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14231                                                Opc == BO_DivAssign);
14232     CompLHSTy = CompResultTy;
14233     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14234       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14235     break;
14236   case BO_RemAssign:
14237     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14238     CompLHSTy = CompResultTy;
14239     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14240       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14241     break;
14242   case BO_AddAssign:
14243     ConvertHalfVec = true;
14244     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14245     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14246       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14247     break;
14248   case BO_SubAssign:
14249     ConvertHalfVec = true;
14250     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14251     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14252       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14253     break;
14254   case BO_ShlAssign:
14255   case BO_ShrAssign:
14256     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14257     CompLHSTy = CompResultTy;
14258     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14259       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14260     break;
14261   case BO_AndAssign:
14262   case BO_OrAssign: // fallthrough
14263     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14264     LLVM_FALLTHROUGH;
14265   case BO_XorAssign:
14266     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14267     CompLHSTy = CompResultTy;
14268     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14269       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14270     break;
14271   case BO_Comma:
14272     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14273     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14274       VK = RHS.get()->getValueKind();
14275       OK = RHS.get()->getObjectKind();
14276     }
14277     break;
14278   }
14279   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14280     return ExprError();
14281 
14282   // Some of the binary operations require promoting operands of half vector to
14283   // float vectors and truncating the result back to half vector. For now, we do
14284   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14285   // arm64).
14286   assert(
14287       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14288                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14289       "both sides are half vectors or neither sides are");
14290   ConvertHalfVec =
14291       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14292 
14293   // Check for array bounds violations for both sides of the BinaryOperator
14294   CheckArrayAccess(LHS.get());
14295   CheckArrayAccess(RHS.get());
14296 
14297   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14298     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14299                                                  &Context.Idents.get("object_setClass"),
14300                                                  SourceLocation(), LookupOrdinaryName);
14301     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14302       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14303       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14304           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14305                                         "object_setClass(")
14306           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14307                                           ",")
14308           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14309     }
14310     else
14311       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14312   }
14313   else if (const ObjCIvarRefExpr *OIRE =
14314            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14315     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14316 
14317   // Opc is not a compound assignment if CompResultTy is null.
14318   if (CompResultTy.isNull()) {
14319     if (ConvertHalfVec)
14320       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14321                                  OpLoc, CurFPFeatureOverrides());
14322     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14323                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14324   }
14325 
14326   // Handle compound assignments.
14327   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14328       OK_ObjCProperty) {
14329     VK = VK_LValue;
14330     OK = LHS.get()->getObjectKind();
14331   }
14332 
14333   // The LHS is not converted to the result type for fixed-point compound
14334   // assignment as the common type is computed on demand. Reset the CompLHSTy
14335   // to the LHS type we would have gotten after unary conversions.
14336   if (CompResultTy->isFixedPointType())
14337     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14338 
14339   if (ConvertHalfVec)
14340     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14341                                OpLoc, CurFPFeatureOverrides());
14342 
14343   return CompoundAssignOperator::Create(
14344       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14345       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14346 }
14347 
14348 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14349 /// operators are mixed in a way that suggests that the programmer forgot that
14350 /// comparison operators have higher precedence. The most typical example of
14351 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14352 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14353                                       SourceLocation OpLoc, Expr *LHSExpr,
14354                                       Expr *RHSExpr) {
14355   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14356   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14357 
14358   // Check that one of the sides is a comparison operator and the other isn't.
14359   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14360   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14361   if (isLeftComp == isRightComp)
14362     return;
14363 
14364   // Bitwise operations are sometimes used as eager logical ops.
14365   // Don't diagnose this.
14366   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14367   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14368   if (isLeftBitwise || isRightBitwise)
14369     return;
14370 
14371   SourceRange DiagRange = isLeftComp
14372                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14373                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14374   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14375   SourceRange ParensRange =
14376       isLeftComp
14377           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14378           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14379 
14380   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14381     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14382   SuggestParentheses(Self, OpLoc,
14383     Self.PDiag(diag::note_precedence_silence) << OpStr,
14384     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14385   SuggestParentheses(Self, OpLoc,
14386     Self.PDiag(diag::note_precedence_bitwise_first)
14387       << BinaryOperator::getOpcodeStr(Opc),
14388     ParensRange);
14389 }
14390 
14391 /// It accepts a '&&' expr that is inside a '||' one.
14392 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14393 /// in parentheses.
14394 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)14395 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14396                                        BinaryOperator *Bop) {
14397   assert(Bop->getOpcode() == BO_LAnd);
14398   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14399       << Bop->getSourceRange() << OpLoc;
14400   SuggestParentheses(Self, Bop->getOperatorLoc(),
14401     Self.PDiag(diag::note_precedence_silence)
14402       << Bop->getOpcodeStr(),
14403     Bop->getSourceRange());
14404 }
14405 
14406 /// Returns true if the given expression can be evaluated as a constant
14407 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)14408 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14409   bool Res;
14410   return !E->isValueDependent() &&
14411          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14412 }
14413 
14414 /// Returns true if the given expression can be evaluated as a constant
14415 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)14416 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14417   bool Res;
14418   return !E->isValueDependent() &&
14419          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14420 }
14421 
14422 /// Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14423 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14424                                              Expr *LHSExpr, Expr *RHSExpr) {
14425   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14426     if (Bop->getOpcode() == BO_LAnd) {
14427       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14428       if (EvaluatesAsFalse(S, RHSExpr))
14429         return;
14430       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14431       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14432         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14433     } else if (Bop->getOpcode() == BO_LOr) {
14434       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14435         // If it's "a || b && 1 || c" we didn't warn earlier for
14436         // "a || b && 1", but warn now.
14437         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14438           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14439       }
14440     }
14441   }
14442 }
14443 
14444 /// Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14445 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14446                                              Expr *LHSExpr, Expr *RHSExpr) {
14447   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14448     if (Bop->getOpcode() == BO_LAnd) {
14449       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14450       if (EvaluatesAsFalse(S, LHSExpr))
14451         return;
14452       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14453       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14454         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14455     }
14456   }
14457 }
14458 
14459 /// Look for bitwise op in the left or right hand of a bitwise op with
14460 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14461 /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)14462 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14463                                          SourceLocation OpLoc, Expr *SubExpr) {
14464   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14465     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14466       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14467         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14468         << Bop->getSourceRange() << OpLoc;
14469       SuggestParentheses(S, Bop->getOperatorLoc(),
14470         S.PDiag(diag::note_precedence_silence)
14471           << Bop->getOpcodeStr(),
14472         Bop->getSourceRange());
14473     }
14474   }
14475 }
14476 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)14477 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14478                                     Expr *SubExpr, StringRef Shift) {
14479   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14480     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14481       StringRef Op = Bop->getOpcodeStr();
14482       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14483           << Bop->getSourceRange() << OpLoc << Shift << Op;
14484       SuggestParentheses(S, Bop->getOperatorLoc(),
14485           S.PDiag(diag::note_precedence_silence) << Op,
14486           Bop->getSourceRange());
14487     }
14488   }
14489 }
14490 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14491 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14492                                  Expr *LHSExpr, Expr *RHSExpr) {
14493   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14494   if (!OCE)
14495     return;
14496 
14497   FunctionDecl *FD = OCE->getDirectCallee();
14498   if (!FD || !FD->isOverloadedOperator())
14499     return;
14500 
14501   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14502   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14503     return;
14504 
14505   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14506       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14507       << (Kind == OO_LessLess);
14508   SuggestParentheses(S, OCE->getOperatorLoc(),
14509                      S.PDiag(diag::note_precedence_silence)
14510                          << (Kind == OO_LessLess ? "<<" : ">>"),
14511                      OCE->getSourceRange());
14512   SuggestParentheses(
14513       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14514       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14515 }
14516 
14517 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14518 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14519 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14520                                     SourceLocation OpLoc, Expr *LHSExpr,
14521                                     Expr *RHSExpr){
14522   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14523   if (BinaryOperator::isBitwiseOp(Opc))
14524     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14525 
14526   // Diagnose "arg1 & arg2 | arg3"
14527   if ((Opc == BO_Or || Opc == BO_Xor) &&
14528       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14529     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14530     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14531   }
14532 
14533   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14534   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14535   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14536     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14537     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14538   }
14539 
14540   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14541       || Opc == BO_Shr) {
14542     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14543     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14544     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14545   }
14546 
14547   // Warn on overloaded shift operators and comparisons, such as:
14548   // cout << 5 == 4;
14549   if (BinaryOperator::isComparisonOp(Opc))
14550     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14551 }
14552 
14553 // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)14554 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14555                             tok::TokenKind Kind,
14556                             Expr *LHSExpr, Expr *RHSExpr) {
14557   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14558   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14559   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14560 
14561   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14562   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14563 
14564   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14565 }
14566 
LookupBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,UnresolvedSetImpl & Functions)14567 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14568                        UnresolvedSetImpl &Functions) {
14569   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14570   if (OverOp != OO_None && OverOp != OO_Equal)
14571     LookupOverloadedOperatorName(OverOp, S, Functions);
14572 
14573   // In C++20 onwards, we may have a second operator to look up.
14574   if (getLangOpts().CPlusPlus20) {
14575     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14576       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14577   }
14578 }
14579 
14580 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)14581 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14582                                        BinaryOperatorKind Opc,
14583                                        Expr *LHS, Expr *RHS) {
14584   switch (Opc) {
14585   case BO_Assign:
14586   case BO_DivAssign:
14587   case BO_RemAssign:
14588   case BO_SubAssign:
14589   case BO_AndAssign:
14590   case BO_OrAssign:
14591   case BO_XorAssign:
14592     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14593     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14594     break;
14595   default:
14596     break;
14597   }
14598 
14599   // Find all of the overloaded operators visible from this point.
14600   UnresolvedSet<16> Functions;
14601   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14602 
14603   // Build the (potentially-overloaded, potentially-dependent)
14604   // binary operation.
14605   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14606 }
14607 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14608 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14609                             BinaryOperatorKind Opc,
14610                             Expr *LHSExpr, Expr *RHSExpr) {
14611   ExprResult LHS, RHS;
14612   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14613   if (!LHS.isUsable() || !RHS.isUsable())
14614     return ExprError();
14615   LHSExpr = LHS.get();
14616   RHSExpr = RHS.get();
14617 
14618   // We want to end up calling one of checkPseudoObjectAssignment
14619   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14620   // both expressions are overloadable or either is type-dependent),
14621   // or CreateBuiltinBinOp (in any other case).  We also want to get
14622   // any placeholder types out of the way.
14623 
14624   // Handle pseudo-objects in the LHS.
14625   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14626     // Assignments with a pseudo-object l-value need special analysis.
14627     if (pty->getKind() == BuiltinType::PseudoObject &&
14628         BinaryOperator::isAssignmentOp(Opc))
14629       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14630 
14631     // Don't resolve overloads if the other type is overloadable.
14632     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14633       // We can't actually test that if we still have a placeholder,
14634       // though.  Fortunately, none of the exceptions we see in that
14635       // code below are valid when the LHS is an overload set.  Note
14636       // that an overload set can be dependently-typed, but it never
14637       // instantiates to having an overloadable type.
14638       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14639       if (resolvedRHS.isInvalid()) return ExprError();
14640       RHSExpr = resolvedRHS.get();
14641 
14642       if (RHSExpr->isTypeDependent() ||
14643           RHSExpr->getType()->isOverloadableType())
14644         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14645     }
14646 
14647     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14648     // template, diagnose the missing 'template' keyword instead of diagnosing
14649     // an invalid use of a bound member function.
14650     //
14651     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14652     // to C++1z [over.over]/1.4, but we already checked for that case above.
14653     if (Opc == BO_LT && inTemplateInstantiation() &&
14654         (pty->getKind() == BuiltinType::BoundMember ||
14655          pty->getKind() == BuiltinType::Overload)) {
14656       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14657       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14658           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14659             return isa<FunctionTemplateDecl>(ND);
14660           })) {
14661         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14662                                 : OE->getNameLoc(),
14663              diag::err_template_kw_missing)
14664           << OE->getName().getAsString() << "";
14665         return ExprError();
14666       }
14667     }
14668 
14669     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14670     if (LHS.isInvalid()) return ExprError();
14671     LHSExpr = LHS.get();
14672   }
14673 
14674   // Handle pseudo-objects in the RHS.
14675   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14676     // An overload in the RHS can potentially be resolved by the type
14677     // being assigned to.
14678     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14679       if (getLangOpts().CPlusPlus &&
14680           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14681            LHSExpr->getType()->isOverloadableType()))
14682         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14683 
14684       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14685     }
14686 
14687     // Don't resolve overloads if the other type is overloadable.
14688     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14689         LHSExpr->getType()->isOverloadableType())
14690       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14691 
14692     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14693     if (!resolvedRHS.isUsable()) return ExprError();
14694     RHSExpr = resolvedRHS.get();
14695   }
14696 
14697   if (getLangOpts().CPlusPlus) {
14698     // If either expression is type-dependent, always build an
14699     // overloaded op.
14700     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14701       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14702 
14703     // Otherwise, build an overloaded op if either expression has an
14704     // overloadable type.
14705     if (LHSExpr->getType()->isOverloadableType() ||
14706         RHSExpr->getType()->isOverloadableType())
14707       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14708   }
14709 
14710   if (getLangOpts().RecoveryAST &&
14711       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14712     assert(!getLangOpts().CPlusPlus);
14713     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14714            "Should only occur in error-recovery path.");
14715     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14716       // C [6.15.16] p3:
14717       // An assignment expression has the value of the left operand after the
14718       // assignment, but is not an lvalue.
14719       return CompoundAssignOperator::Create(
14720           Context, LHSExpr, RHSExpr, Opc,
14721           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14722           OpLoc, CurFPFeatureOverrides());
14723     QualType ResultType;
14724     switch (Opc) {
14725     case BO_Assign:
14726       ResultType = LHSExpr->getType().getUnqualifiedType();
14727       break;
14728     case BO_LT:
14729     case BO_GT:
14730     case BO_LE:
14731     case BO_GE:
14732     case BO_EQ:
14733     case BO_NE:
14734     case BO_LAnd:
14735     case BO_LOr:
14736       // These operators have a fixed result type regardless of operands.
14737       ResultType = Context.IntTy;
14738       break;
14739     case BO_Comma:
14740       ResultType = RHSExpr->getType();
14741       break;
14742     default:
14743       ResultType = Context.DependentTy;
14744       break;
14745     }
14746     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14747                                   VK_PRValue, OK_Ordinary, OpLoc,
14748                                   CurFPFeatureOverrides());
14749   }
14750 
14751   // Build a built-in binary operation.
14752   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14753 }
14754 
isOverflowingIntegerType(ASTContext & Ctx,QualType T)14755 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14756   if (T.isNull() || T->isDependentType())
14757     return false;
14758 
14759   if (!T->isPromotableIntegerType())
14760     return true;
14761 
14762   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14763 }
14764 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)14765 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14766                                       UnaryOperatorKind Opc,
14767                                       Expr *InputExpr) {
14768   ExprResult Input = InputExpr;
14769   ExprValueKind VK = VK_PRValue;
14770   ExprObjectKind OK = OK_Ordinary;
14771   QualType resultType;
14772   bool CanOverflow = false;
14773 
14774   bool ConvertHalfVec = false;
14775   if (getLangOpts().OpenCL) {
14776     QualType Ty = InputExpr->getType();
14777     // The only legal unary operation for atomics is '&'.
14778     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14779     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14780     // only with a builtin functions and therefore should be disallowed here.
14781         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14782         || Ty->isBlockPointerType())) {
14783       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14784                        << InputExpr->getType()
14785                        << Input.get()->getSourceRange());
14786     }
14787   }
14788 
14789   switch (Opc) {
14790   case UO_PreInc:
14791   case UO_PreDec:
14792   case UO_PostInc:
14793   case UO_PostDec:
14794     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14795                                                 OpLoc,
14796                                                 Opc == UO_PreInc ||
14797                                                 Opc == UO_PostInc,
14798                                                 Opc == UO_PreInc ||
14799                                                 Opc == UO_PreDec);
14800     CanOverflow = isOverflowingIntegerType(Context, resultType);
14801     break;
14802   case UO_AddrOf:
14803     resultType = CheckAddressOfOperand(Input, OpLoc);
14804     CheckAddressOfNoDeref(InputExpr);
14805     RecordModifiableNonNullParam(*this, InputExpr);
14806     break;
14807   case UO_Deref: {
14808     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14809     if (Input.isInvalid()) return ExprError();
14810     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14811     break;
14812   }
14813   case UO_Plus:
14814   case UO_Minus:
14815     CanOverflow = Opc == UO_Minus &&
14816                   isOverflowingIntegerType(Context, Input.get()->getType());
14817     Input = UsualUnaryConversions(Input.get());
14818     if (Input.isInvalid()) return ExprError();
14819     // Unary plus and minus require promoting an operand of half vector to a
14820     // float vector and truncating the result back to a half vector. For now, we
14821     // do this only when HalfArgsAndReturns is set (that is, when the target is
14822     // arm or arm64).
14823     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14824 
14825     // If the operand is a half vector, promote it to a float vector.
14826     if (ConvertHalfVec)
14827       Input = convertVector(Input.get(), Context.FloatTy, *this);
14828     resultType = Input.get()->getType();
14829     if (resultType->isDependentType())
14830       break;
14831     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14832       break;
14833     else if (resultType->isVectorType() &&
14834              // The z vector extensions don't allow + or - with bool vectors.
14835              (!Context.getLangOpts().ZVector ||
14836               resultType->castAs<VectorType>()->getVectorKind() !=
14837               VectorType::AltiVecBool))
14838       break;
14839     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14840              Opc == UO_Plus &&
14841              resultType->isPointerType())
14842       break;
14843 
14844     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14845       << resultType << Input.get()->getSourceRange());
14846 
14847   case UO_Not: // bitwise complement
14848     Input = UsualUnaryConversions(Input.get());
14849     if (Input.isInvalid())
14850       return ExprError();
14851     resultType = Input.get()->getType();
14852     if (resultType->isDependentType())
14853       break;
14854     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14855     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14856       // C99 does not support '~' for complex conjugation.
14857       Diag(OpLoc, diag::ext_integer_complement_complex)
14858           << resultType << Input.get()->getSourceRange();
14859     else if (resultType->hasIntegerRepresentation())
14860       break;
14861     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14862       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14863       // on vector float types.
14864       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14865       if (!T->isIntegerType())
14866         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14867                           << resultType << Input.get()->getSourceRange());
14868     } else {
14869       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14870                        << resultType << Input.get()->getSourceRange());
14871     }
14872     break;
14873 
14874   case UO_LNot: // logical negation
14875     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14876     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14877     if (Input.isInvalid()) return ExprError();
14878     resultType = Input.get()->getType();
14879 
14880     // Though we still have to promote half FP to float...
14881     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14882       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14883       resultType = Context.FloatTy;
14884     }
14885 
14886     if (resultType->isDependentType())
14887       break;
14888     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14889       // C99 6.5.3.3p1: ok, fallthrough;
14890       if (Context.getLangOpts().CPlusPlus) {
14891         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14892         // operand contextually converted to bool.
14893         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14894                                   ScalarTypeToBooleanCastKind(resultType));
14895       } else if (Context.getLangOpts().OpenCL &&
14896                  Context.getLangOpts().OpenCLVersion < 120) {
14897         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14898         // operate on scalar float types.
14899         if (!resultType->isIntegerType() && !resultType->isPointerType())
14900           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14901                            << resultType << Input.get()->getSourceRange());
14902       }
14903     } else if (resultType->isExtVectorType()) {
14904       if (Context.getLangOpts().OpenCL &&
14905           Context.getLangOpts().OpenCLVersion < 120 &&
14906           !Context.getLangOpts().OpenCLCPlusPlus) {
14907         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14908         // operate on vector float types.
14909         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14910         if (!T->isIntegerType())
14911           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14912                            << resultType << Input.get()->getSourceRange());
14913       }
14914       // Vector logical not returns the signed variant of the operand type.
14915       resultType = GetSignedVectorType(resultType);
14916       break;
14917     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14918       const VectorType *VTy = resultType->castAs<VectorType>();
14919       if (VTy->getVectorKind() != VectorType::GenericVector)
14920         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14921                          << resultType << Input.get()->getSourceRange());
14922 
14923       // Vector logical not returns the signed variant of the operand type.
14924       resultType = GetSignedVectorType(resultType);
14925       break;
14926     } else {
14927       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14928         << resultType << Input.get()->getSourceRange());
14929     }
14930 
14931     // LNot always has type int. C99 6.5.3.3p5.
14932     // In C++, it's bool. C++ 5.3.1p8
14933     resultType = Context.getLogicalOperationType();
14934     break;
14935   case UO_Real:
14936   case UO_Imag:
14937     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14938     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14939     // complex l-values to ordinary l-values and all other values to r-values.
14940     if (Input.isInvalid()) return ExprError();
14941     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14942       if (Input.get()->isGLValue() &&
14943           Input.get()->getObjectKind() == OK_Ordinary)
14944         VK = Input.get()->getValueKind();
14945     } else if (!getLangOpts().CPlusPlus) {
14946       // In C, a volatile scalar is read by __imag. In C++, it is not.
14947       Input = DefaultLvalueConversion(Input.get());
14948     }
14949     break;
14950   case UO_Extension:
14951     resultType = Input.get()->getType();
14952     VK = Input.get()->getValueKind();
14953     OK = Input.get()->getObjectKind();
14954     break;
14955   case UO_Coawait:
14956     // It's unnecessary to represent the pass-through operator co_await in the
14957     // AST; just return the input expression instead.
14958     assert(!Input.get()->getType()->isDependentType() &&
14959                    "the co_await expression must be non-dependant before "
14960                    "building operator co_await");
14961     return Input;
14962   }
14963   if (resultType.isNull() || Input.isInvalid())
14964     return ExprError();
14965 
14966   // Check for array bounds violations in the operand of the UnaryOperator,
14967   // except for the '*' and '&' operators that have to be handled specially
14968   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14969   // that are explicitly defined as valid by the standard).
14970   if (Opc != UO_AddrOf && Opc != UO_Deref)
14971     CheckArrayAccess(Input.get());
14972 
14973   auto *UO =
14974       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14975                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14976 
14977   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14978       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14979       !isUnevaluatedContext())
14980     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14981 
14982   // Convert the result back to a half vector.
14983   if (ConvertHalfVec)
14984     return convertVector(UO, Context.HalfTy, *this);
14985   return UO;
14986 }
14987 
14988 /// Determine whether the given expression is a qualified member
14989 /// access expression, of a form that could be turned into a pointer to member
14990 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)14991 bool Sema::isQualifiedMemberAccess(Expr *E) {
14992   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14993     if (!DRE->getQualifier())
14994       return false;
14995 
14996     ValueDecl *VD = DRE->getDecl();
14997     if (!VD->isCXXClassMember())
14998       return false;
14999 
15000     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15001       return true;
15002     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15003       return Method->isInstance();
15004 
15005     return false;
15006   }
15007 
15008   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15009     if (!ULE->getQualifier())
15010       return false;
15011 
15012     for (NamedDecl *D : ULE->decls()) {
15013       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15014         if (Method->isInstance())
15015           return true;
15016       } else {
15017         // Overload set does not contain methods.
15018         break;
15019       }
15020     }
15021 
15022     return false;
15023   }
15024 
15025   return false;
15026 }
15027 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)15028 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15029                               UnaryOperatorKind Opc, Expr *Input) {
15030   // First things first: handle placeholders so that the
15031   // overloaded-operator check considers the right type.
15032   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15033     // Increment and decrement of pseudo-object references.
15034     if (pty->getKind() == BuiltinType::PseudoObject &&
15035         UnaryOperator::isIncrementDecrementOp(Opc))
15036       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15037 
15038     // extension is always a builtin operator.
15039     if (Opc == UO_Extension)
15040       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15041 
15042     // & gets special logic for several kinds of placeholder.
15043     // The builtin code knows what to do.
15044     if (Opc == UO_AddrOf &&
15045         (pty->getKind() == BuiltinType::Overload ||
15046          pty->getKind() == BuiltinType::UnknownAny ||
15047          pty->getKind() == BuiltinType::BoundMember))
15048       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15049 
15050     // Anything else needs to be handled now.
15051     ExprResult Result = CheckPlaceholderExpr(Input);
15052     if (Result.isInvalid()) return ExprError();
15053     Input = Result.get();
15054   }
15055 
15056   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15057       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15058       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15059     // Find all of the overloaded operators visible from this point.
15060     UnresolvedSet<16> Functions;
15061     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15062     if (S && OverOp != OO_None)
15063       LookupOverloadedOperatorName(OverOp, S, Functions);
15064 
15065     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15066   }
15067 
15068   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15069 }
15070 
15071 // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)15072 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15073                               tok::TokenKind Op, Expr *Input) {
15074   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15075 }
15076 
15077 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)15078 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15079                                 LabelDecl *TheDecl) {
15080   TheDecl->markUsed(Context);
15081   // Create the AST node.  The address of a label always has type 'void*'.
15082   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15083                                      Context.getPointerType(Context.VoidTy));
15084 }
15085 
ActOnStartStmtExpr()15086 void Sema::ActOnStartStmtExpr() {
15087   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15088 }
15089 
ActOnStmtExprError()15090 void Sema::ActOnStmtExprError() {
15091   // Note that function is also called by TreeTransform when leaving a
15092   // StmtExpr scope without rebuilding anything.
15093 
15094   DiscardCleanupsInEvaluationContext();
15095   PopExpressionEvaluationContext();
15096 }
15097 
ActOnStmtExpr(Scope * S,SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)15098 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15099                                SourceLocation RPLoc) {
15100   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15101 }
15102 
BuildStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc,unsigned TemplateDepth)15103 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15104                                SourceLocation RPLoc, unsigned TemplateDepth) {
15105   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15106   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15107 
15108   if (hasAnyUnrecoverableErrorsInThisFunction())
15109     DiscardCleanupsInEvaluationContext();
15110   assert(!Cleanup.exprNeedsCleanups() &&
15111          "cleanups within StmtExpr not correctly bound!");
15112   PopExpressionEvaluationContext();
15113 
15114   // FIXME: there are a variety of strange constraints to enforce here, for
15115   // example, it is not possible to goto into a stmt expression apparently.
15116   // More semantic analysis is needed.
15117 
15118   // If there are sub-stmts in the compound stmt, take the type of the last one
15119   // as the type of the stmtexpr.
15120   QualType Ty = Context.VoidTy;
15121   bool StmtExprMayBindToTemp = false;
15122   if (!Compound->body_empty()) {
15123     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15124     if (const auto *LastStmt =
15125             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15126       if (const Expr *Value = LastStmt->getExprStmt()) {
15127         StmtExprMayBindToTemp = true;
15128         Ty = Value->getType();
15129       }
15130     }
15131   }
15132 
15133   // FIXME: Check that expression type is complete/non-abstract; statement
15134   // expressions are not lvalues.
15135   Expr *ResStmtExpr =
15136       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15137   if (StmtExprMayBindToTemp)
15138     return MaybeBindToTemporary(ResStmtExpr);
15139   return ResStmtExpr;
15140 }
15141 
ActOnStmtExprResult(ExprResult ER)15142 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15143   if (ER.isInvalid())
15144     return ExprError();
15145 
15146   // Do function/array conversion on the last expression, but not
15147   // lvalue-to-rvalue.  However, initialize an unqualified type.
15148   ER = DefaultFunctionArrayConversion(ER.get());
15149   if (ER.isInvalid())
15150     return ExprError();
15151   Expr *E = ER.get();
15152 
15153   if (E->isTypeDependent())
15154     return E;
15155 
15156   // In ARC, if the final expression ends in a consume, splice
15157   // the consume out and bind it later.  In the alternate case
15158   // (when dealing with a retainable type), the result
15159   // initialization will create a produce.  In both cases the
15160   // result will be +1, and we'll need to balance that out with
15161   // a bind.
15162   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15163   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15164     return Cast->getSubExpr();
15165 
15166   // FIXME: Provide a better location for the initialization.
15167   return PerformCopyInitialization(
15168       InitializedEntity::InitializeStmtExprResult(
15169           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15170       SourceLocation(), E);
15171 }
15172 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15173 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15174                                       TypeSourceInfo *TInfo,
15175                                       ArrayRef<OffsetOfComponent> Components,
15176                                       SourceLocation RParenLoc) {
15177   QualType ArgTy = TInfo->getType();
15178   bool Dependent = ArgTy->isDependentType();
15179   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15180 
15181   // We must have at least one component that refers to the type, and the first
15182   // one is known to be a field designator.  Verify that the ArgTy represents
15183   // a struct/union/class.
15184   if (!Dependent && !ArgTy->isRecordType())
15185     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15186                        << ArgTy << TypeRange);
15187 
15188   // Type must be complete per C99 7.17p3 because a declaring a variable
15189   // with an incomplete type would be ill-formed.
15190   if (!Dependent
15191       && RequireCompleteType(BuiltinLoc, ArgTy,
15192                              diag::err_offsetof_incomplete_type, TypeRange))
15193     return ExprError();
15194 
15195   bool DidWarnAboutNonPOD = false;
15196   QualType CurrentType = ArgTy;
15197   SmallVector<OffsetOfNode, 4> Comps;
15198   SmallVector<Expr*, 4> Exprs;
15199   for (const OffsetOfComponent &OC : Components) {
15200     if (OC.isBrackets) {
15201       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15202       if (!CurrentType->isDependentType()) {
15203         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15204         if(!AT)
15205           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15206                            << CurrentType);
15207         CurrentType = AT->getElementType();
15208       } else
15209         CurrentType = Context.DependentTy;
15210 
15211       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15212       if (IdxRval.isInvalid())
15213         return ExprError();
15214       Expr *Idx = IdxRval.get();
15215 
15216       // The expression must be an integral expression.
15217       // FIXME: An integral constant expression?
15218       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15219           !Idx->getType()->isIntegerType())
15220         return ExprError(
15221             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15222             << Idx->getSourceRange());
15223 
15224       // Record this array index.
15225       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15226       Exprs.push_back(Idx);
15227       continue;
15228     }
15229 
15230     // Offset of a field.
15231     if (CurrentType->isDependentType()) {
15232       // We have the offset of a field, but we can't look into the dependent
15233       // type. Just record the identifier of the field.
15234       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15235       CurrentType = Context.DependentTy;
15236       continue;
15237     }
15238 
15239     // We need to have a complete type to look into.
15240     if (RequireCompleteType(OC.LocStart, CurrentType,
15241                             diag::err_offsetof_incomplete_type))
15242       return ExprError();
15243 
15244     // Look for the designated field.
15245     const RecordType *RC = CurrentType->getAs<RecordType>();
15246     if (!RC)
15247       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15248                        << CurrentType);
15249     RecordDecl *RD = RC->getDecl();
15250 
15251     // C++ [lib.support.types]p5:
15252     //   The macro offsetof accepts a restricted set of type arguments in this
15253     //   International Standard. type shall be a POD structure or a POD union
15254     //   (clause 9).
15255     // C++11 [support.types]p4:
15256     //   If type is not a standard-layout class (Clause 9), the results are
15257     //   undefined.
15258     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15259       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15260       unsigned DiagID =
15261         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15262                             : diag::ext_offsetof_non_pod_type;
15263 
15264       if (!IsSafe && !DidWarnAboutNonPOD &&
15265           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15266                               PDiag(DiagID)
15267                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15268                               << CurrentType))
15269         DidWarnAboutNonPOD = true;
15270     }
15271 
15272     // Look for the field.
15273     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15274     LookupQualifiedName(R, RD);
15275     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15276     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15277     if (!MemberDecl) {
15278       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15279         MemberDecl = IndirectMemberDecl->getAnonField();
15280     }
15281 
15282     if (!MemberDecl)
15283       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15284                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15285                                                               OC.LocEnd));
15286 
15287     // C99 7.17p3:
15288     //   (If the specified member is a bit-field, the behavior is undefined.)
15289     //
15290     // We diagnose this as an error.
15291     if (MemberDecl->isBitField()) {
15292       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15293         << MemberDecl->getDeclName()
15294         << SourceRange(BuiltinLoc, RParenLoc);
15295       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15296       return ExprError();
15297     }
15298 
15299     RecordDecl *Parent = MemberDecl->getParent();
15300     if (IndirectMemberDecl)
15301       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15302 
15303     // If the member was found in a base class, introduce OffsetOfNodes for
15304     // the base class indirections.
15305     CXXBasePaths Paths;
15306     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15307                       Paths)) {
15308       if (Paths.getDetectedVirtual()) {
15309         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15310           << MemberDecl->getDeclName()
15311           << SourceRange(BuiltinLoc, RParenLoc);
15312         return ExprError();
15313       }
15314 
15315       CXXBasePath &Path = Paths.front();
15316       for (const CXXBasePathElement &B : Path)
15317         Comps.push_back(OffsetOfNode(B.Base));
15318     }
15319 
15320     if (IndirectMemberDecl) {
15321       for (auto *FI : IndirectMemberDecl->chain()) {
15322         assert(isa<FieldDecl>(FI));
15323         Comps.push_back(OffsetOfNode(OC.LocStart,
15324                                      cast<FieldDecl>(FI), OC.LocEnd));
15325       }
15326     } else
15327       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15328 
15329     CurrentType = MemberDecl->getType().getNonReferenceType();
15330   }
15331 
15332   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15333                               Comps, Exprs, RParenLoc);
15334 }
15335 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15336 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15337                                       SourceLocation BuiltinLoc,
15338                                       SourceLocation TypeLoc,
15339                                       ParsedType ParsedArgTy,
15340                                       ArrayRef<OffsetOfComponent> Components,
15341                                       SourceLocation RParenLoc) {
15342 
15343   TypeSourceInfo *ArgTInfo;
15344   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15345   if (ArgTy.isNull())
15346     return ExprError();
15347 
15348   if (!ArgTInfo)
15349     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15350 
15351   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15352 }
15353 
15354 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)15355 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15356                                  Expr *CondExpr,
15357                                  Expr *LHSExpr, Expr *RHSExpr,
15358                                  SourceLocation RPLoc) {
15359   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15360 
15361   ExprValueKind VK = VK_PRValue;
15362   ExprObjectKind OK = OK_Ordinary;
15363   QualType resType;
15364   bool CondIsTrue = false;
15365   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15366     resType = Context.DependentTy;
15367   } else {
15368     // The conditional expression is required to be a constant expression.
15369     llvm::APSInt condEval(32);
15370     ExprResult CondICE = VerifyIntegerConstantExpression(
15371         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15372     if (CondICE.isInvalid())
15373       return ExprError();
15374     CondExpr = CondICE.get();
15375     CondIsTrue = condEval.getZExtValue();
15376 
15377     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15378     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15379 
15380     resType = ActiveExpr->getType();
15381     VK = ActiveExpr->getValueKind();
15382     OK = ActiveExpr->getObjectKind();
15383   }
15384 
15385   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15386                                   resType, VK, OK, RPLoc, CondIsTrue);
15387 }
15388 
15389 //===----------------------------------------------------------------------===//
15390 // Clang Extensions.
15391 //===----------------------------------------------------------------------===//
15392 
15393 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)15394 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15395   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15396 
15397   if (LangOpts.CPlusPlus) {
15398     MangleNumberingContext *MCtx;
15399     Decl *ManglingContextDecl;
15400     std::tie(MCtx, ManglingContextDecl) =
15401         getCurrentMangleNumberContext(Block->getDeclContext());
15402     if (MCtx) {
15403       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15404       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15405     }
15406   }
15407 
15408   PushBlockScope(CurScope, Block);
15409   CurContext->addDecl(Block);
15410   if (CurScope)
15411     PushDeclContext(CurScope, Block);
15412   else
15413     CurContext = Block;
15414 
15415   getCurBlock()->HasImplicitReturnType = true;
15416 
15417   // Enter a new evaluation context to insulate the block from any
15418   // cleanups from the enclosing full-expression.
15419   PushExpressionEvaluationContext(
15420       ExpressionEvaluationContext::PotentiallyEvaluated);
15421 }
15422 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)15423 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15424                                Scope *CurScope) {
15425   assert(ParamInfo.getIdentifier() == nullptr &&
15426          "block-id should have no identifier!");
15427   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15428   BlockScopeInfo *CurBlock = getCurBlock();
15429 
15430   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15431   QualType T = Sig->getType();
15432 
15433   // FIXME: We should allow unexpanded parameter packs here, but that would,
15434   // in turn, make the block expression contain unexpanded parameter packs.
15435   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15436     // Drop the parameters.
15437     FunctionProtoType::ExtProtoInfo EPI;
15438     EPI.HasTrailingReturn = false;
15439     EPI.TypeQuals.addConst();
15440     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15441     Sig = Context.getTrivialTypeSourceInfo(T);
15442   }
15443 
15444   // GetTypeForDeclarator always produces a function type for a block
15445   // literal signature.  Furthermore, it is always a FunctionProtoType
15446   // unless the function was written with a typedef.
15447   assert(T->isFunctionType() &&
15448          "GetTypeForDeclarator made a non-function block signature");
15449 
15450   // Look for an explicit signature in that function type.
15451   FunctionProtoTypeLoc ExplicitSignature;
15452 
15453   if ((ExplicitSignature = Sig->getTypeLoc()
15454                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15455 
15456     // Check whether that explicit signature was synthesized by
15457     // GetTypeForDeclarator.  If so, don't save that as part of the
15458     // written signature.
15459     if (ExplicitSignature.getLocalRangeBegin() ==
15460         ExplicitSignature.getLocalRangeEnd()) {
15461       // This would be much cheaper if we stored TypeLocs instead of
15462       // TypeSourceInfos.
15463       TypeLoc Result = ExplicitSignature.getReturnLoc();
15464       unsigned Size = Result.getFullDataSize();
15465       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15466       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15467 
15468       ExplicitSignature = FunctionProtoTypeLoc();
15469     }
15470   }
15471 
15472   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15473   CurBlock->FunctionType = T;
15474 
15475   const auto *Fn = T->castAs<FunctionType>();
15476   QualType RetTy = Fn->getReturnType();
15477   bool isVariadic =
15478       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15479 
15480   CurBlock->TheDecl->setIsVariadic(isVariadic);
15481 
15482   // Context.DependentTy is used as a placeholder for a missing block
15483   // return type.  TODO:  what should we do with declarators like:
15484   //   ^ * { ... }
15485   // If the answer is "apply template argument deduction"....
15486   if (RetTy != Context.DependentTy) {
15487     CurBlock->ReturnType = RetTy;
15488     CurBlock->TheDecl->setBlockMissingReturnType(false);
15489     CurBlock->HasImplicitReturnType = false;
15490   }
15491 
15492   // Push block parameters from the declarator if we had them.
15493   SmallVector<ParmVarDecl*, 8> Params;
15494   if (ExplicitSignature) {
15495     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15496       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15497       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15498           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15499         // Diagnose this as an extension in C17 and earlier.
15500         if (!getLangOpts().C2x)
15501           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15502       }
15503       Params.push_back(Param);
15504     }
15505 
15506   // Fake up parameter variables if we have a typedef, like
15507   //   ^ fntype { ... }
15508   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15509     for (const auto &I : Fn->param_types()) {
15510       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15511           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15512       Params.push_back(Param);
15513     }
15514   }
15515 
15516   // Set the parameters on the block decl.
15517   if (!Params.empty()) {
15518     CurBlock->TheDecl->setParams(Params);
15519     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15520                              /*CheckParameterNames=*/false);
15521   }
15522 
15523   // Finally we can process decl attributes.
15524   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15525 
15526   // Put the parameter variables in scope.
15527   for (auto AI : CurBlock->TheDecl->parameters()) {
15528     AI->setOwningFunction(CurBlock->TheDecl);
15529 
15530     // If this has an identifier, add it to the scope stack.
15531     if (AI->getIdentifier()) {
15532       CheckShadow(CurBlock->TheScope, AI);
15533 
15534       PushOnScopeChains(AI, CurBlock->TheScope);
15535     }
15536   }
15537 }
15538 
15539 /// ActOnBlockError - If there is an error parsing a block, this callback
15540 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)15541 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15542   // Leave the expression-evaluation context.
15543   DiscardCleanupsInEvaluationContext();
15544   PopExpressionEvaluationContext();
15545 
15546   // Pop off CurBlock, handle nested blocks.
15547   PopDeclContext();
15548   PopFunctionScopeInfo();
15549 }
15550 
15551 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15552 /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)15553 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15554                                     Stmt *Body, Scope *CurScope) {
15555   // If blocks are disabled, emit an error.
15556   if (!LangOpts.Blocks)
15557     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15558 
15559   // Leave the expression-evaluation context.
15560   if (hasAnyUnrecoverableErrorsInThisFunction())
15561     DiscardCleanupsInEvaluationContext();
15562   assert(!Cleanup.exprNeedsCleanups() &&
15563          "cleanups within block not correctly bound!");
15564   PopExpressionEvaluationContext();
15565 
15566   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15567   BlockDecl *BD = BSI->TheDecl;
15568 
15569   if (BSI->HasImplicitReturnType)
15570     deduceClosureReturnType(*BSI);
15571 
15572   QualType RetTy = Context.VoidTy;
15573   if (!BSI->ReturnType.isNull())
15574     RetTy = BSI->ReturnType;
15575 
15576   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15577   QualType BlockTy;
15578 
15579   // If the user wrote a function type in some form, try to use that.
15580   if (!BSI->FunctionType.isNull()) {
15581     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15582 
15583     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15584     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15585 
15586     // Turn protoless block types into nullary block types.
15587     if (isa<FunctionNoProtoType>(FTy)) {
15588       FunctionProtoType::ExtProtoInfo EPI;
15589       EPI.ExtInfo = Ext;
15590       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15591 
15592     // Otherwise, if we don't need to change anything about the function type,
15593     // preserve its sugar structure.
15594     } else if (FTy->getReturnType() == RetTy &&
15595                (!NoReturn || FTy->getNoReturnAttr())) {
15596       BlockTy = BSI->FunctionType;
15597 
15598     // Otherwise, make the minimal modifications to the function type.
15599     } else {
15600       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15601       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15602       EPI.TypeQuals = Qualifiers();
15603       EPI.ExtInfo = Ext;
15604       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15605     }
15606 
15607   // If we don't have a function type, just build one from nothing.
15608   } else {
15609     FunctionProtoType::ExtProtoInfo EPI;
15610     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15611     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15612   }
15613 
15614   DiagnoseUnusedParameters(BD->parameters());
15615   BlockTy = Context.getBlockPointerType(BlockTy);
15616 
15617   // If needed, diagnose invalid gotos and switches in the block.
15618   if (getCurFunction()->NeedsScopeChecking() &&
15619       !PP.isCodeCompletionEnabled())
15620     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15621 
15622   BD->setBody(cast<CompoundStmt>(Body));
15623 
15624   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15625     DiagnoseUnguardedAvailabilityViolations(BD);
15626 
15627   // Try to apply the named return value optimization. We have to check again
15628   // if we can do this, though, because blocks keep return statements around
15629   // to deduce an implicit return type.
15630   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15631       !BD->isDependentContext())
15632     computeNRVO(Body, BSI);
15633 
15634   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15635       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15636     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15637                           NTCUK_Destruct|NTCUK_Copy);
15638 
15639   PopDeclContext();
15640 
15641   // Set the captured variables on the block.
15642   SmallVector<BlockDecl::Capture, 4> Captures;
15643   for (Capture &Cap : BSI->Captures) {
15644     if (Cap.isInvalid() || Cap.isThisCapture())
15645       continue;
15646 
15647     VarDecl *Var = Cap.getVariable();
15648     Expr *CopyExpr = nullptr;
15649     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15650       if (const RecordType *Record =
15651               Cap.getCaptureType()->getAs<RecordType>()) {
15652         // The capture logic needs the destructor, so make sure we mark it.
15653         // Usually this is unnecessary because most local variables have
15654         // their destructors marked at declaration time, but parameters are
15655         // an exception because it's technically only the call site that
15656         // actually requires the destructor.
15657         if (isa<ParmVarDecl>(Var))
15658           FinalizeVarWithDestructor(Var, Record);
15659 
15660         // Enter a separate potentially-evaluated context while building block
15661         // initializers to isolate their cleanups from those of the block
15662         // itself.
15663         // FIXME: Is this appropriate even when the block itself occurs in an
15664         // unevaluated operand?
15665         EnterExpressionEvaluationContext EvalContext(
15666             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15667 
15668         SourceLocation Loc = Cap.getLocation();
15669 
15670         ExprResult Result = BuildDeclarationNameExpr(
15671             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15672 
15673         // According to the blocks spec, the capture of a variable from
15674         // the stack requires a const copy constructor.  This is not true
15675         // of the copy/move done to move a __block variable to the heap.
15676         if (!Result.isInvalid() &&
15677             !Result.get()->getType().isConstQualified()) {
15678           Result = ImpCastExprToType(Result.get(),
15679                                      Result.get()->getType().withConst(),
15680                                      CK_NoOp, VK_LValue);
15681         }
15682 
15683         if (!Result.isInvalid()) {
15684           Result = PerformCopyInitialization(
15685               InitializedEntity::InitializeBlock(Var->getLocation(),
15686                                                  Cap.getCaptureType()),
15687               Loc, Result.get());
15688         }
15689 
15690         // Build a full-expression copy expression if initialization
15691         // succeeded and used a non-trivial constructor.  Recover from
15692         // errors by pretending that the copy isn't necessary.
15693         if (!Result.isInvalid() &&
15694             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15695                 ->isTrivial()) {
15696           Result = MaybeCreateExprWithCleanups(Result);
15697           CopyExpr = Result.get();
15698         }
15699       }
15700     }
15701 
15702     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15703                               CopyExpr);
15704     Captures.push_back(NewCap);
15705   }
15706   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15707 
15708   // Pop the block scope now but keep it alive to the end of this function.
15709   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15710   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15711 
15712   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15713 
15714   // If the block isn't obviously global, i.e. it captures anything at
15715   // all, then we need to do a few things in the surrounding context:
15716   if (Result->getBlockDecl()->hasCaptures()) {
15717     // First, this expression has a new cleanup object.
15718     ExprCleanupObjects.push_back(Result->getBlockDecl());
15719     Cleanup.setExprNeedsCleanups(true);
15720 
15721     // It also gets a branch-protected scope if any of the captured
15722     // variables needs destruction.
15723     for (const auto &CI : Result->getBlockDecl()->captures()) {
15724       const VarDecl *var = CI.getVariable();
15725       if (var->getType().isDestructedType() != QualType::DK_none) {
15726         setFunctionHasBranchProtectedScope();
15727         break;
15728       }
15729     }
15730   }
15731 
15732   if (getCurFunction())
15733     getCurFunction()->addBlock(BD);
15734 
15735   return Result;
15736 }
15737 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)15738 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15739                             SourceLocation RPLoc) {
15740   TypeSourceInfo *TInfo;
15741   GetTypeFromParser(Ty, &TInfo);
15742   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15743 }
15744 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)15745 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15746                                 Expr *E, TypeSourceInfo *TInfo,
15747                                 SourceLocation RPLoc) {
15748   Expr *OrigExpr = E;
15749   bool IsMS = false;
15750 
15751   // CUDA device code does not support varargs.
15752   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15753     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15754       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15755       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15756         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15757     }
15758   }
15759 
15760   // NVPTX does not support va_arg expression.
15761   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15762       Context.getTargetInfo().getTriple().isNVPTX())
15763     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15764 
15765   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15766   // as Microsoft ABI on an actual Microsoft platform, where
15767   // __builtin_ms_va_list and __builtin_va_list are the same.)
15768   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15769       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15770     QualType MSVaListType = Context.getBuiltinMSVaListType();
15771     if (Context.hasSameType(MSVaListType, E->getType())) {
15772       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15773         return ExprError();
15774       IsMS = true;
15775     }
15776   }
15777 
15778   // Get the va_list type
15779   QualType VaListType = Context.getBuiltinVaListType();
15780   if (!IsMS) {
15781     if (VaListType->isArrayType()) {
15782       // Deal with implicit array decay; for example, on x86-64,
15783       // va_list is an array, but it's supposed to decay to
15784       // a pointer for va_arg.
15785       VaListType = Context.getArrayDecayedType(VaListType);
15786       // Make sure the input expression also decays appropriately.
15787       ExprResult Result = UsualUnaryConversions(E);
15788       if (Result.isInvalid())
15789         return ExprError();
15790       E = Result.get();
15791     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15792       // If va_list is a record type and we are compiling in C++ mode,
15793       // check the argument using reference binding.
15794       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15795           Context, Context.getLValueReferenceType(VaListType), false);
15796       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15797       if (Init.isInvalid())
15798         return ExprError();
15799       E = Init.getAs<Expr>();
15800     } else {
15801       // Otherwise, the va_list argument must be an l-value because
15802       // it is modified by va_arg.
15803       if (!E->isTypeDependent() &&
15804           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15805         return ExprError();
15806     }
15807   }
15808 
15809   if (!IsMS && !E->isTypeDependent() &&
15810       !Context.hasSameType(VaListType, E->getType()))
15811     return ExprError(
15812         Diag(E->getBeginLoc(),
15813              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15814         << OrigExpr->getType() << E->getSourceRange());
15815 
15816   if (!TInfo->getType()->isDependentType()) {
15817     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15818                             diag::err_second_parameter_to_va_arg_incomplete,
15819                             TInfo->getTypeLoc()))
15820       return ExprError();
15821 
15822     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15823                                TInfo->getType(),
15824                                diag::err_second_parameter_to_va_arg_abstract,
15825                                TInfo->getTypeLoc()))
15826       return ExprError();
15827 
15828     if (!TInfo->getType().isPODType(Context)) {
15829       Diag(TInfo->getTypeLoc().getBeginLoc(),
15830            TInfo->getType()->isObjCLifetimeType()
15831              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15832              : diag::warn_second_parameter_to_va_arg_not_pod)
15833         << TInfo->getType()
15834         << TInfo->getTypeLoc().getSourceRange();
15835     }
15836 
15837     // Check for va_arg where arguments of the given type will be promoted
15838     // (i.e. this va_arg is guaranteed to have undefined behavior).
15839     QualType PromoteType;
15840     if (TInfo->getType()->isPromotableIntegerType()) {
15841       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15842       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
15843       // and C2x 7.16.1.1p2 says, in part:
15844       //   If type is not compatible with the type of the actual next argument
15845       //   (as promoted according to the default argument promotions), the
15846       //   behavior is undefined, except for the following cases:
15847       //     - both types are pointers to qualified or unqualified versions of
15848       //       compatible types;
15849       //     - one type is a signed integer type, the other type is the
15850       //       corresponding unsigned integer type, and the value is
15851       //       representable in both types;
15852       //     - one type is pointer to qualified or unqualified void and the
15853       //       other is a pointer to a qualified or unqualified character type.
15854       // Given that type compatibility is the primary requirement (ignoring
15855       // qualifications), you would think we could call typesAreCompatible()
15856       // directly to test this. However, in C++, that checks for *same type*,
15857       // which causes false positives when passing an enumeration type to
15858       // va_arg. Instead, get the underlying type of the enumeration and pass
15859       // that.
15860       QualType UnderlyingType = TInfo->getType();
15861       if (const auto *ET = UnderlyingType->getAs<EnumType>())
15862         UnderlyingType = ET->getDecl()->getIntegerType();
15863       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15864                                      /*CompareUnqualified*/ true))
15865         PromoteType = QualType();
15866 
15867       // If the types are still not compatible, we need to test whether the
15868       // promoted type and the underlying type are the same except for
15869       // signedness. Ask the AST for the correctly corresponding type and see
15870       // if that's compatible.
15871       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
15872           PromoteType->isUnsignedIntegerType() !=
15873               UnderlyingType->isUnsignedIntegerType()) {
15874         UnderlyingType =
15875             UnderlyingType->isUnsignedIntegerType()
15876                 ? Context.getCorrespondingSignedType(UnderlyingType)
15877                 : Context.getCorrespondingUnsignedType(UnderlyingType);
15878         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
15879                                        /*CompareUnqualified*/ true))
15880           PromoteType = QualType();
15881       }
15882     }
15883     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15884       PromoteType = Context.DoubleTy;
15885     if (!PromoteType.isNull())
15886       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15887                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15888                           << TInfo->getType()
15889                           << PromoteType
15890                           << TInfo->getTypeLoc().getSourceRange());
15891   }
15892 
15893   QualType T = TInfo->getType().getNonLValueExprType(Context);
15894   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15895 }
15896 
ActOnGNUNullExpr(SourceLocation TokenLoc)15897 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15898   // The type of __null will be int or long, depending on the size of
15899   // pointers on the target.
15900   QualType Ty;
15901   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15902   if (pw == Context.getTargetInfo().getIntWidth())
15903     Ty = Context.IntTy;
15904   else if (pw == Context.getTargetInfo().getLongWidth())
15905     Ty = Context.LongTy;
15906   else if (pw == Context.getTargetInfo().getLongLongWidth())
15907     Ty = Context.LongLongTy;
15908   else {
15909     llvm_unreachable("I don't know size of pointer!");
15910   }
15911 
15912   return new (Context) GNUNullExpr(Ty, TokenLoc);
15913 }
15914 
ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc)15915 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15916                                     SourceLocation BuiltinLoc,
15917                                     SourceLocation RPLoc) {
15918   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15919 }
15920 
BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc,DeclContext * ParentContext)15921 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15922                                     SourceLocation BuiltinLoc,
15923                                     SourceLocation RPLoc,
15924                                     DeclContext *ParentContext) {
15925   return new (Context)
15926       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15927 }
15928 
CheckConversionToObjCLiteral(QualType DstType,Expr * & Exp,bool Diagnose)15929 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15930                                         bool Diagnose) {
15931   if (!getLangOpts().ObjC)
15932     return false;
15933 
15934   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15935   if (!PT)
15936     return false;
15937   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15938 
15939   // Ignore any parens, implicit casts (should only be
15940   // array-to-pointer decays), and not-so-opaque values.  The last is
15941   // important for making this trigger for property assignments.
15942   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15943   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15944     if (OV->getSourceExpr())
15945       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15946 
15947   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15948     if (!PT->isObjCIdType() &&
15949         !(ID && ID->getIdentifier()->isStr("NSString")))
15950       return false;
15951     if (!SL->isAscii())
15952       return false;
15953 
15954     if (Diagnose) {
15955       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15956           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15957       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15958     }
15959     return true;
15960   }
15961 
15962   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15963       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15964       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15965       !SrcExpr->isNullPointerConstant(
15966           getASTContext(), Expr::NPC_NeverValueDependent)) {
15967     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15968       return false;
15969     if (Diagnose) {
15970       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15971           << /*number*/1
15972           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15973       Expr *NumLit =
15974           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15975       if (NumLit)
15976         Exp = NumLit;
15977     }
15978     return true;
15979   }
15980 
15981   return false;
15982 }
15983 
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)15984 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15985                                               const Expr *SrcExpr) {
15986   if (!DstType->isFunctionPointerType() ||
15987       !SrcExpr->getType()->isFunctionType())
15988     return false;
15989 
15990   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15991   if (!DRE)
15992     return false;
15993 
15994   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15995   if (!FD)
15996     return false;
15997 
15998   return !S.checkAddressOfFunctionIsAvailable(FD,
15999                                               /*Complain=*/true,
16000                                               SrcExpr->getBeginLoc());
16001 }
16002 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)16003 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16004                                     SourceLocation Loc,
16005                                     QualType DstType, QualType SrcType,
16006                                     Expr *SrcExpr, AssignmentAction Action,
16007                                     bool *Complained) {
16008   if (Complained)
16009     *Complained = false;
16010 
16011   // Decode the result (notice that AST's are still created for extensions).
16012   bool CheckInferredResultType = false;
16013   bool isInvalid = false;
16014   unsigned DiagKind = 0;
16015   ConversionFixItGenerator ConvHints;
16016   bool MayHaveConvFixit = false;
16017   bool MayHaveFunctionDiff = false;
16018   const ObjCInterfaceDecl *IFace = nullptr;
16019   const ObjCProtocolDecl *PDecl = nullptr;
16020 
16021   switch (ConvTy) {
16022   case Compatible:
16023       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16024       return false;
16025 
16026   case PointerToInt:
16027     if (getLangOpts().CPlusPlus) {
16028       DiagKind = diag::err_typecheck_convert_pointer_int;
16029       isInvalid = true;
16030     } else {
16031       DiagKind = diag::ext_typecheck_convert_pointer_int;
16032     }
16033     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16034     MayHaveConvFixit = true;
16035     break;
16036   case IntToPointer:
16037     if (getLangOpts().CPlusPlus) {
16038       DiagKind = diag::err_typecheck_convert_int_pointer;
16039       isInvalid = true;
16040     } else {
16041       DiagKind = diag::ext_typecheck_convert_int_pointer;
16042     }
16043     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16044     MayHaveConvFixit = true;
16045     break;
16046   case IncompatibleFunctionPointer:
16047     if (getLangOpts().CPlusPlus) {
16048       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16049       isInvalid = true;
16050     } else {
16051       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16052     }
16053     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16054     MayHaveConvFixit = true;
16055     break;
16056   case IncompatiblePointer:
16057     if (Action == AA_Passing_CFAudited) {
16058       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16059     } else if (getLangOpts().CPlusPlus) {
16060       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16061       isInvalid = true;
16062     } else {
16063       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16064     }
16065     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16066       SrcType->isObjCObjectPointerType();
16067     if (!CheckInferredResultType) {
16068       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16069     } else if (CheckInferredResultType) {
16070       SrcType = SrcType.getUnqualifiedType();
16071       DstType = DstType.getUnqualifiedType();
16072     }
16073     MayHaveConvFixit = true;
16074     break;
16075   case IncompatiblePointerSign:
16076     if (getLangOpts().CPlusPlus) {
16077       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16078       isInvalid = true;
16079     } else {
16080       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16081     }
16082     break;
16083   case FunctionVoidPointer:
16084     if (getLangOpts().CPlusPlus) {
16085       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16086       isInvalid = true;
16087     } else {
16088       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16089     }
16090     break;
16091   case IncompatiblePointerDiscardsQualifiers: {
16092     // Perform array-to-pointer decay if necessary.
16093     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16094 
16095     isInvalid = true;
16096 
16097     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16098     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16099     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16100       DiagKind = diag::err_typecheck_incompatible_address_space;
16101       break;
16102 
16103     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16104       DiagKind = diag::err_typecheck_incompatible_ownership;
16105       break;
16106     }
16107 
16108     llvm_unreachable("unknown error case for discarding qualifiers!");
16109     // fallthrough
16110   }
16111   case CompatiblePointerDiscardsQualifiers:
16112     // If the qualifiers lost were because we were applying the
16113     // (deprecated) C++ conversion from a string literal to a char*
16114     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16115     // Ideally, this check would be performed in
16116     // checkPointerTypesForAssignment. However, that would require a
16117     // bit of refactoring (so that the second argument is an
16118     // expression, rather than a type), which should be done as part
16119     // of a larger effort to fix checkPointerTypesForAssignment for
16120     // C++ semantics.
16121     if (getLangOpts().CPlusPlus &&
16122         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16123       return false;
16124     if (getLangOpts().CPlusPlus) {
16125       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16126       isInvalid = true;
16127     } else {
16128       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16129     }
16130 
16131     break;
16132   case IncompatibleNestedPointerQualifiers:
16133     if (getLangOpts().CPlusPlus) {
16134       isInvalid = true;
16135       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16136     } else {
16137       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16138     }
16139     break;
16140   case IncompatibleNestedPointerAddressSpaceMismatch:
16141     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16142     isInvalid = true;
16143     break;
16144   case IntToBlockPointer:
16145     DiagKind = diag::err_int_to_block_pointer;
16146     isInvalid = true;
16147     break;
16148   case IncompatibleBlockPointer:
16149     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16150     isInvalid = true;
16151     break;
16152   case IncompatibleObjCQualifiedId: {
16153     if (SrcType->isObjCQualifiedIdType()) {
16154       const ObjCObjectPointerType *srcOPT =
16155                 SrcType->castAs<ObjCObjectPointerType>();
16156       for (auto *srcProto : srcOPT->quals()) {
16157         PDecl = srcProto;
16158         break;
16159       }
16160       if (const ObjCInterfaceType *IFaceT =
16161             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16162         IFace = IFaceT->getDecl();
16163     }
16164     else if (DstType->isObjCQualifiedIdType()) {
16165       const ObjCObjectPointerType *dstOPT =
16166         DstType->castAs<ObjCObjectPointerType>();
16167       for (auto *dstProto : dstOPT->quals()) {
16168         PDecl = dstProto;
16169         break;
16170       }
16171       if (const ObjCInterfaceType *IFaceT =
16172             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16173         IFace = IFaceT->getDecl();
16174     }
16175     if (getLangOpts().CPlusPlus) {
16176       DiagKind = diag::err_incompatible_qualified_id;
16177       isInvalid = true;
16178     } else {
16179       DiagKind = diag::warn_incompatible_qualified_id;
16180     }
16181     break;
16182   }
16183   case IncompatibleVectors:
16184     if (getLangOpts().CPlusPlus) {
16185       DiagKind = diag::err_incompatible_vectors;
16186       isInvalid = true;
16187     } else {
16188       DiagKind = diag::warn_incompatible_vectors;
16189     }
16190     break;
16191   case IncompatibleObjCWeakRef:
16192     DiagKind = diag::err_arc_weak_unavailable_assign;
16193     isInvalid = true;
16194     break;
16195   case Incompatible:
16196     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16197       if (Complained)
16198         *Complained = true;
16199       return true;
16200     }
16201 
16202     DiagKind = diag::err_typecheck_convert_incompatible;
16203     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16204     MayHaveConvFixit = true;
16205     isInvalid = true;
16206     MayHaveFunctionDiff = true;
16207     break;
16208   }
16209 
16210   QualType FirstType, SecondType;
16211   switch (Action) {
16212   case AA_Assigning:
16213   case AA_Initializing:
16214     // The destination type comes first.
16215     FirstType = DstType;
16216     SecondType = SrcType;
16217     break;
16218 
16219   case AA_Returning:
16220   case AA_Passing:
16221   case AA_Passing_CFAudited:
16222   case AA_Converting:
16223   case AA_Sending:
16224   case AA_Casting:
16225     // The source type comes first.
16226     FirstType = SrcType;
16227     SecondType = DstType;
16228     break;
16229   }
16230 
16231   PartialDiagnostic FDiag = PDiag(DiagKind);
16232   if (Action == AA_Passing_CFAudited)
16233     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16234   else
16235     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16236 
16237   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16238       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16239     auto isPlainChar = [](const clang::Type *Type) {
16240       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16241              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16242     };
16243     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16244               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16245   }
16246 
16247   // If we can fix the conversion, suggest the FixIts.
16248   if (!ConvHints.isNull()) {
16249     for (FixItHint &H : ConvHints.Hints)
16250       FDiag << H;
16251   }
16252 
16253   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16254 
16255   if (MayHaveFunctionDiff)
16256     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16257 
16258   Diag(Loc, FDiag);
16259   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16260        DiagKind == diag::err_incompatible_qualified_id) &&
16261       PDecl && IFace && !IFace->hasDefinition())
16262     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16263         << IFace << PDecl;
16264 
16265   if (SecondType == Context.OverloadTy)
16266     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16267                               FirstType, /*TakingAddress=*/true);
16268 
16269   if (CheckInferredResultType)
16270     EmitRelatedResultTypeNote(SrcExpr);
16271 
16272   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16273     EmitRelatedResultTypeNoteForReturn(DstType);
16274 
16275   if (Complained)
16276     *Complained = true;
16277   return isInvalid;
16278 }
16279 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,AllowFoldKind CanFold)16280 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16281                                                  llvm::APSInt *Result,
16282                                                  AllowFoldKind CanFold) {
16283   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16284   public:
16285     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16286                                              QualType T) override {
16287       return S.Diag(Loc, diag::err_ice_not_integral)
16288              << T << S.LangOpts.CPlusPlus;
16289     }
16290     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16291       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16292     }
16293   } Diagnoser;
16294 
16295   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16296 }
16297 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,AllowFoldKind CanFold)16298 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16299                                                  llvm::APSInt *Result,
16300                                                  unsigned DiagID,
16301                                                  AllowFoldKind CanFold) {
16302   class IDDiagnoser : public VerifyICEDiagnoser {
16303     unsigned DiagID;
16304 
16305   public:
16306     IDDiagnoser(unsigned DiagID)
16307       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16308 
16309     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16310       return S.Diag(Loc, DiagID);
16311     }
16312   } Diagnoser(DiagID);
16313 
16314   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16315 }
16316 
16317 Sema::SemaDiagnosticBuilder
diagnoseNotICEType(Sema & S,SourceLocation Loc,QualType T)16318 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16319                                              QualType T) {
16320   return diagnoseNotICE(S, Loc);
16321 }
16322 
16323 Sema::SemaDiagnosticBuilder
diagnoseFold(Sema & S,SourceLocation Loc)16324 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16325   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16326 }
16327 
16328 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,AllowFoldKind CanFold)16329 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16330                                       VerifyICEDiagnoser &Diagnoser,
16331                                       AllowFoldKind CanFold) {
16332   SourceLocation DiagLoc = E->getBeginLoc();
16333 
16334   if (getLangOpts().CPlusPlus11) {
16335     // C++11 [expr.const]p5:
16336     //   If an expression of literal class type is used in a context where an
16337     //   integral constant expression is required, then that class type shall
16338     //   have a single non-explicit conversion function to an integral or
16339     //   unscoped enumeration type
16340     ExprResult Converted;
16341     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16342       VerifyICEDiagnoser &BaseDiagnoser;
16343     public:
16344       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16345           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16346                                 BaseDiagnoser.Suppress, true),
16347             BaseDiagnoser(BaseDiagnoser) {}
16348 
16349       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16350                                            QualType T) override {
16351         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16352       }
16353 
16354       SemaDiagnosticBuilder diagnoseIncomplete(
16355           Sema &S, SourceLocation Loc, QualType T) override {
16356         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16357       }
16358 
16359       SemaDiagnosticBuilder diagnoseExplicitConv(
16360           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16361         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16362       }
16363 
16364       SemaDiagnosticBuilder noteExplicitConv(
16365           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16366         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16367                  << ConvTy->isEnumeralType() << ConvTy;
16368       }
16369 
16370       SemaDiagnosticBuilder diagnoseAmbiguous(
16371           Sema &S, SourceLocation Loc, QualType T) override {
16372         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16373       }
16374 
16375       SemaDiagnosticBuilder noteAmbiguous(
16376           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16377         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16378                  << ConvTy->isEnumeralType() << ConvTy;
16379       }
16380 
16381       SemaDiagnosticBuilder diagnoseConversion(
16382           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16383         llvm_unreachable("conversion functions are permitted");
16384       }
16385     } ConvertDiagnoser(Diagnoser);
16386 
16387     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16388                                                     ConvertDiagnoser);
16389     if (Converted.isInvalid())
16390       return Converted;
16391     E = Converted.get();
16392     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16393       return ExprError();
16394   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16395     // An ICE must be of integral or unscoped enumeration type.
16396     if (!Diagnoser.Suppress)
16397       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16398           << E->getSourceRange();
16399     return ExprError();
16400   }
16401 
16402   ExprResult RValueExpr = DefaultLvalueConversion(E);
16403   if (RValueExpr.isInvalid())
16404     return ExprError();
16405 
16406   E = RValueExpr.get();
16407 
16408   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16409   // in the non-ICE case.
16410   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16411     if (Result)
16412       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16413     if (!isa<ConstantExpr>(E))
16414       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16415                  : ConstantExpr::Create(Context, E);
16416     return E;
16417   }
16418 
16419   Expr::EvalResult EvalResult;
16420   SmallVector<PartialDiagnosticAt, 8> Notes;
16421   EvalResult.Diag = &Notes;
16422 
16423   // Try to evaluate the expression, and produce diagnostics explaining why it's
16424   // not a constant expression as a side-effect.
16425   bool Folded =
16426       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16427       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16428 
16429   if (!isa<ConstantExpr>(E))
16430     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16431 
16432   // In C++11, we can rely on diagnostics being produced for any expression
16433   // which is not a constant expression. If no diagnostics were produced, then
16434   // this is a constant expression.
16435   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16436     if (Result)
16437       *Result = EvalResult.Val.getInt();
16438     return E;
16439   }
16440 
16441   // If our only note is the usual "invalid subexpression" note, just point
16442   // the caret at its location rather than producing an essentially
16443   // redundant note.
16444   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16445         diag::note_invalid_subexpr_in_const_expr) {
16446     DiagLoc = Notes[0].first;
16447     Notes.clear();
16448   }
16449 
16450   if (!Folded || !CanFold) {
16451     if (!Diagnoser.Suppress) {
16452       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16453       for (const PartialDiagnosticAt &Note : Notes)
16454         Diag(Note.first, Note.second);
16455     }
16456 
16457     return ExprError();
16458   }
16459 
16460   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16461   for (const PartialDiagnosticAt &Note : Notes)
16462     Diag(Note.first, Note.second);
16463 
16464   if (Result)
16465     *Result = EvalResult.Val.getInt();
16466   return E;
16467 }
16468 
16469 namespace {
16470   // Handle the case where we conclude a expression which we speculatively
16471   // considered to be unevaluated is actually evaluated.
16472   class TransformToPE : public TreeTransform<TransformToPE> {
16473     typedef TreeTransform<TransformToPE> BaseTransform;
16474 
16475   public:
TransformToPE(Sema & SemaRef)16476     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16477 
16478     // Make sure we redo semantic analysis
AlwaysRebuild()16479     bool AlwaysRebuild() { return true; }
ReplacingOriginal()16480     bool ReplacingOriginal() { return true; }
16481 
16482     // We need to special-case DeclRefExprs referring to FieldDecls which
16483     // are not part of a member pointer formation; normal TreeTransforming
16484     // doesn't catch this case because of the way we represent them in the AST.
16485     // FIXME: This is a bit ugly; is it really the best way to handle this
16486     // case?
16487     //
16488     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)16489     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16490       if (isa<FieldDecl>(E->getDecl()) &&
16491           !SemaRef.isUnevaluatedContext())
16492         return SemaRef.Diag(E->getLocation(),
16493                             diag::err_invalid_non_static_member_use)
16494             << E->getDecl() << E->getSourceRange();
16495 
16496       return BaseTransform::TransformDeclRefExpr(E);
16497     }
16498 
16499     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)16500     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16501       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16502         return E;
16503 
16504       return BaseTransform::TransformUnaryOperator(E);
16505     }
16506 
16507     // The body of a lambda-expression is in a separate expression evaluation
16508     // context so never needs to be transformed.
16509     // FIXME: Ideally we wouldn't transform the closure type either, and would
16510     // just recreate the capture expressions and lambda expression.
TransformLambdaBody(LambdaExpr * E,Stmt * Body)16511     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16512       return SkipLambdaBody(E, Body);
16513     }
16514   };
16515 }
16516 
TransformToPotentiallyEvaluated(Expr * E)16517 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16518   assert(isUnevaluatedContext() &&
16519          "Should only transform unevaluated expressions");
16520   ExprEvalContexts.back().Context =
16521       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16522   if (isUnevaluatedContext())
16523     return E;
16524   return TransformToPE(*this).TransformExpr(E);
16525 }
16526 
16527 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16528 Sema::PushExpressionEvaluationContext(
16529     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16530     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16531   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16532                                 LambdaContextDecl, ExprContext);
16533   Cleanup.reset();
16534   if (!MaybeODRUseExprs.empty())
16535     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16536 }
16537 
16538 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16539 Sema::PushExpressionEvaluationContext(
16540     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16541     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16542   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16543   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16544 }
16545 
16546 namespace {
16547 
CheckPossibleDeref(Sema & S,const Expr * PossibleDeref)16548 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16549   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16550   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16551     if (E->getOpcode() == UO_Deref)
16552       return CheckPossibleDeref(S, E->getSubExpr());
16553   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16554     return CheckPossibleDeref(S, E->getBase());
16555   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16556     return CheckPossibleDeref(S, E->getBase());
16557   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16558     QualType Inner;
16559     QualType Ty = E->getType();
16560     if (const auto *Ptr = Ty->getAs<PointerType>())
16561       Inner = Ptr->getPointeeType();
16562     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16563       Inner = Arr->getElementType();
16564     else
16565       return nullptr;
16566 
16567     if (Inner->hasAttr(attr::NoDeref))
16568       return E;
16569   }
16570   return nullptr;
16571 }
16572 
16573 } // namespace
16574 
WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord & Rec)16575 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16576   for (const Expr *E : Rec.PossibleDerefs) {
16577     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16578     if (DeclRef) {
16579       const ValueDecl *Decl = DeclRef->getDecl();
16580       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16581           << Decl->getName() << E->getSourceRange();
16582       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16583     } else {
16584       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16585           << E->getSourceRange();
16586     }
16587   }
16588   Rec.PossibleDerefs.clear();
16589 }
16590 
16591 /// Check whether E, which is either a discarded-value expression or an
16592 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16593 /// and if so, remove it from the list of volatile-qualified assignments that
16594 /// we are going to warn are deprecated.
CheckUnusedVolatileAssignment(Expr * E)16595 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16596   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16597     return;
16598 
16599   // Note: ignoring parens here is not justified by the standard rules, but
16600   // ignoring parentheses seems like a more reasonable approach, and this only
16601   // drives a deprecation warning so doesn't affect conformance.
16602   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16603     if (BO->getOpcode() == BO_Assign) {
16604       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16605       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16606                  LHSs.end());
16607     }
16608   }
16609 }
16610 
CheckForImmediateInvocation(ExprResult E,FunctionDecl * Decl)16611 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16612   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16613       RebuildingImmediateInvocation)
16614     return E;
16615 
16616   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16617   /// It's OK if this fails; we'll also remove this in
16618   /// HandleImmediateInvocations, but catching it here allows us to avoid
16619   /// walking the AST looking for it in simple cases.
16620   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16621     if (auto *DeclRef =
16622             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16623       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16624 
16625   E = MaybeCreateExprWithCleanups(E);
16626 
16627   ConstantExpr *Res = ConstantExpr::Create(
16628       getASTContext(), E.get(),
16629       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16630                                    getASTContext()),
16631       /*IsImmediateInvocation*/ true);
16632   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16633   return Res;
16634 }
16635 
EvaluateAndDiagnoseImmediateInvocation(Sema & SemaRef,Sema::ImmediateInvocationCandidate Candidate)16636 static void EvaluateAndDiagnoseImmediateInvocation(
16637     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16638   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16639   Expr::EvalResult Eval;
16640   Eval.Diag = &Notes;
16641   ConstantExpr *CE = Candidate.getPointer();
16642   bool Result = CE->EvaluateAsConstantExpr(
16643       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16644   if (!Result || !Notes.empty()) {
16645     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16646     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16647       InnerExpr = FunctionalCast->getSubExpr();
16648     FunctionDecl *FD = nullptr;
16649     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16650       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16651     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16652       FD = Call->getConstructor();
16653     else
16654       llvm_unreachable("unhandled decl kind");
16655     assert(FD->isConsteval());
16656     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16657     for (auto &Note : Notes)
16658       SemaRef.Diag(Note.first, Note.second);
16659     return;
16660   }
16661   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16662 }
16663 
RemoveNestedImmediateInvocation(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec,SmallVector<Sema::ImmediateInvocationCandidate,4>::reverse_iterator It)16664 static void RemoveNestedImmediateInvocation(
16665     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16666     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16667   struct ComplexRemove : TreeTransform<ComplexRemove> {
16668     using Base = TreeTransform<ComplexRemove>;
16669     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16670     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16671     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16672         CurrentII;
16673     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16674                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16675                   SmallVector<Sema::ImmediateInvocationCandidate,
16676                               4>::reverse_iterator Current)
16677         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16678     void RemoveImmediateInvocation(ConstantExpr* E) {
16679       auto It = std::find_if(CurrentII, IISet.rend(),
16680                              [E](Sema::ImmediateInvocationCandidate Elem) {
16681                                return Elem.getPointer() == E;
16682                              });
16683       assert(It != IISet.rend() &&
16684              "ConstantExpr marked IsImmediateInvocation should "
16685              "be present");
16686       It->setInt(1); // Mark as deleted
16687     }
16688     ExprResult TransformConstantExpr(ConstantExpr *E) {
16689       if (!E->isImmediateInvocation())
16690         return Base::TransformConstantExpr(E);
16691       RemoveImmediateInvocation(E);
16692       return Base::TransformExpr(E->getSubExpr());
16693     }
16694     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16695     /// we need to remove its DeclRefExpr from the DRSet.
16696     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16697       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16698       return Base::TransformCXXOperatorCallExpr(E);
16699     }
16700     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16701     /// here.
16702     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16703       if (!Init)
16704         return Init;
16705       /// ConstantExpr are the first layer of implicit node to be removed so if
16706       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16707       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16708         if (CE->isImmediateInvocation())
16709           RemoveImmediateInvocation(CE);
16710       return Base::TransformInitializer(Init, NotCopyInit);
16711     }
16712     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16713       DRSet.erase(E);
16714       return E;
16715     }
16716     bool AlwaysRebuild() { return false; }
16717     bool ReplacingOriginal() { return true; }
16718     bool AllowSkippingCXXConstructExpr() {
16719       bool Res = AllowSkippingFirstCXXConstructExpr;
16720       AllowSkippingFirstCXXConstructExpr = true;
16721       return Res;
16722     }
16723     bool AllowSkippingFirstCXXConstructExpr = true;
16724   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16725                 Rec.ImmediateInvocationCandidates, It);
16726 
16727   /// CXXConstructExpr with a single argument are getting skipped by
16728   /// TreeTransform in some situtation because they could be implicit. This
16729   /// can only occur for the top-level CXXConstructExpr because it is used
16730   /// nowhere in the expression being transformed therefore will not be rebuilt.
16731   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16732   /// skipping the first CXXConstructExpr.
16733   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16734     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16735 
16736   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16737   assert(Res.isUsable());
16738   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16739   It->getPointer()->setSubExpr(Res.get());
16740 }
16741 
16742 static void
HandleImmediateInvocations(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec)16743 HandleImmediateInvocations(Sema &SemaRef,
16744                            Sema::ExpressionEvaluationContextRecord &Rec) {
16745   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16746        Rec.ReferenceToConsteval.size() == 0) ||
16747       SemaRef.RebuildingImmediateInvocation)
16748     return;
16749 
16750   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16751   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16752   /// need to remove ReferenceToConsteval in the immediate invocation.
16753   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16754 
16755     /// Prevent sema calls during the tree transform from adding pointers that
16756     /// are already in the sets.
16757     llvm::SaveAndRestore<bool> DisableIITracking(
16758         SemaRef.RebuildingImmediateInvocation, true);
16759 
16760     /// Prevent diagnostic during tree transfrom as they are duplicates
16761     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16762 
16763     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16764          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16765       if (!It->getInt())
16766         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16767   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16768              Rec.ReferenceToConsteval.size()) {
16769     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16770       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16771       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16772       bool VisitDeclRefExpr(DeclRefExpr *E) {
16773         DRSet.erase(E);
16774         return DRSet.size();
16775       }
16776     } Visitor(Rec.ReferenceToConsteval);
16777     Visitor.TraverseStmt(
16778         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16779   }
16780   for (auto CE : Rec.ImmediateInvocationCandidates)
16781     if (!CE.getInt())
16782       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16783   for (auto DR : Rec.ReferenceToConsteval) {
16784     auto *FD = cast<FunctionDecl>(DR->getDecl());
16785     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16786         << FD;
16787     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16788   }
16789 }
16790 
PopExpressionEvaluationContext()16791 void Sema::PopExpressionEvaluationContext() {
16792   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16793   unsigned NumTypos = Rec.NumTypos;
16794 
16795   if (!Rec.Lambdas.empty()) {
16796     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16797     if (!getLangOpts().CPlusPlus20 &&
16798         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
16799          Rec.isUnevaluated() ||
16800          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
16801       unsigned D;
16802       if (Rec.isUnevaluated()) {
16803         // C++11 [expr.prim.lambda]p2:
16804         //   A lambda-expression shall not appear in an unevaluated operand
16805         //   (Clause 5).
16806         D = diag::err_lambda_unevaluated_operand;
16807       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16808         // C++1y [expr.const]p2:
16809         //   A conditional-expression e is a core constant expression unless the
16810         //   evaluation of e, following the rules of the abstract machine, would
16811         //   evaluate [...] a lambda-expression.
16812         D = diag::err_lambda_in_constant_expression;
16813       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16814         // C++17 [expr.prim.lamda]p2:
16815         // A lambda-expression shall not appear [...] in a template-argument.
16816         D = diag::err_lambda_in_invalid_context;
16817       } else
16818         llvm_unreachable("Couldn't infer lambda error message.");
16819 
16820       for (const auto *L : Rec.Lambdas)
16821         Diag(L->getBeginLoc(), D);
16822     }
16823   }
16824 
16825   WarnOnPendingNoDerefs(Rec);
16826   HandleImmediateInvocations(*this, Rec);
16827 
16828   // Warn on any volatile-qualified simple-assignments that are not discarded-
16829   // value expressions nor unevaluated operands (those cases get removed from
16830   // this list by CheckUnusedVolatileAssignment).
16831   for (auto *BO : Rec.VolatileAssignmentLHSs)
16832     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16833         << BO->getType();
16834 
16835   // When are coming out of an unevaluated context, clear out any
16836   // temporaries that we may have created as part of the evaluation of
16837   // the expression in that context: they aren't relevant because they
16838   // will never be constructed.
16839   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16840     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16841                              ExprCleanupObjects.end());
16842     Cleanup = Rec.ParentCleanup;
16843     CleanupVarDeclMarking();
16844     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16845   // Otherwise, merge the contexts together.
16846   } else {
16847     Cleanup.mergeFrom(Rec.ParentCleanup);
16848     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16849                             Rec.SavedMaybeODRUseExprs.end());
16850   }
16851 
16852   // Pop the current expression evaluation context off the stack.
16853   ExprEvalContexts.pop_back();
16854 
16855   // The global expression evaluation context record is never popped.
16856   ExprEvalContexts.back().NumTypos += NumTypos;
16857 }
16858 
DiscardCleanupsInEvaluationContext()16859 void Sema::DiscardCleanupsInEvaluationContext() {
16860   ExprCleanupObjects.erase(
16861          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16862          ExprCleanupObjects.end());
16863   Cleanup.reset();
16864   MaybeODRUseExprs.clear();
16865 }
16866 
HandleExprEvaluationContextForTypeof(Expr * E)16867 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16868   ExprResult Result = CheckPlaceholderExpr(E);
16869   if (Result.isInvalid())
16870     return ExprError();
16871   E = Result.get();
16872   if (!E->getType()->isVariablyModifiedType())
16873     return E;
16874   return TransformToPotentiallyEvaluated(E);
16875 }
16876 
16877 /// Are we in a context that is potentially constant evaluated per C++20
16878 /// [expr.const]p12?
isPotentiallyConstantEvaluatedContext(Sema & SemaRef)16879 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16880   /// C++2a [expr.const]p12:
16881   //   An expression or conversion is potentially constant evaluated if it is
16882   switch (SemaRef.ExprEvalContexts.back().Context) {
16883     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16884       // -- a manifestly constant-evaluated expression,
16885     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16886     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16887     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16888       // -- a potentially-evaluated expression,
16889     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16890       // -- an immediate subexpression of a braced-init-list,
16891 
16892       // -- [FIXME] an expression of the form & cast-expression that occurs
16893       //    within a templated entity
16894       // -- a subexpression of one of the above that is not a subexpression of
16895       // a nested unevaluated operand.
16896       return true;
16897 
16898     case Sema::ExpressionEvaluationContext::Unevaluated:
16899     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16900       // Expressions in this context are never evaluated.
16901       return false;
16902   }
16903   llvm_unreachable("Invalid context");
16904 }
16905 
16906 /// Return true if this function has a calling convention that requires mangling
16907 /// in the size of the parameter pack.
funcHasParameterSizeMangling(Sema & S,FunctionDecl * FD)16908 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16909   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16910   // we don't need parameter type sizes.
16911   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16912   if (!TT.isOSWindows() || !TT.isX86())
16913     return false;
16914 
16915   // If this is C++ and this isn't an extern "C" function, parameters do not
16916   // need to be complete. In this case, C++ mangling will apply, which doesn't
16917   // use the size of the parameters.
16918   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16919     return false;
16920 
16921   // Stdcall, fastcall, and vectorcall need this special treatment.
16922   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16923   switch (CC) {
16924   case CC_X86StdCall:
16925   case CC_X86FastCall:
16926   case CC_X86VectorCall:
16927     return true;
16928   default:
16929     break;
16930   }
16931   return false;
16932 }
16933 
16934 /// Require that all of the parameter types of function be complete. Normally,
16935 /// parameter types are only required to be complete when a function is called
16936 /// or defined, but to mangle functions with certain calling conventions, the
16937 /// mangler needs to know the size of the parameter list. In this situation,
16938 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16939 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16940 /// result in a linker error. Clang doesn't implement this behavior, and instead
16941 /// attempts to error at compile time.
CheckCompleteParameterTypesForMangler(Sema & S,FunctionDecl * FD,SourceLocation Loc)16942 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16943                                                   SourceLocation Loc) {
16944   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16945     FunctionDecl *FD;
16946     ParmVarDecl *Param;
16947 
16948   public:
16949     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16950         : FD(FD), Param(Param) {}
16951 
16952     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16953       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16954       StringRef CCName;
16955       switch (CC) {
16956       case CC_X86StdCall:
16957         CCName = "stdcall";
16958         break;
16959       case CC_X86FastCall:
16960         CCName = "fastcall";
16961         break;
16962       case CC_X86VectorCall:
16963         CCName = "vectorcall";
16964         break;
16965       default:
16966         llvm_unreachable("CC does not need mangling");
16967       }
16968 
16969       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16970           << Param->getDeclName() << FD->getDeclName() << CCName;
16971     }
16972   };
16973 
16974   for (ParmVarDecl *Param : FD->parameters()) {
16975     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16976     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16977   }
16978 }
16979 
16980 namespace {
16981 enum class OdrUseContext {
16982   /// Declarations in this context are not odr-used.
16983   None,
16984   /// Declarations in this context are formally odr-used, but this is a
16985   /// dependent context.
16986   Dependent,
16987   /// Declarations in this context are odr-used but not actually used (yet).
16988   FormallyOdrUsed,
16989   /// Declarations in this context are used.
16990   Used
16991 };
16992 }
16993 
16994 /// Are we within a context in which references to resolved functions or to
16995 /// variables result in odr-use?
isOdrUseContext(Sema & SemaRef)16996 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16997   OdrUseContext Result;
16998 
16999   switch (SemaRef.ExprEvalContexts.back().Context) {
17000     case Sema::ExpressionEvaluationContext::Unevaluated:
17001     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17002     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17003       return OdrUseContext::None;
17004 
17005     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17006     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17007       Result = OdrUseContext::Used;
17008       break;
17009 
17010     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17011       Result = OdrUseContext::FormallyOdrUsed;
17012       break;
17013 
17014     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17015       // A default argument formally results in odr-use, but doesn't actually
17016       // result in a use in any real sense until it itself is used.
17017       Result = OdrUseContext::FormallyOdrUsed;
17018       break;
17019   }
17020 
17021   if (SemaRef.CurContext->isDependentContext())
17022     return OdrUseContext::Dependent;
17023 
17024   return Result;
17025 }
17026 
isImplicitlyDefinableConstexprFunction(FunctionDecl * Func)17027 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17028   if (!Func->isConstexpr())
17029     return false;
17030 
17031   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17032     return true;
17033   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17034   return CCD && CCD->getInheritedConstructor();
17035 }
17036 
17037 /// Mark a function referenced, and check whether it is odr-used
17038 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)17039 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17040                                   bool MightBeOdrUse) {
17041   assert(Func && "No function?");
17042 
17043   Func->setReferenced();
17044 
17045   // Recursive functions aren't really used until they're used from some other
17046   // context.
17047   bool IsRecursiveCall = CurContext == Func;
17048 
17049   // C++11 [basic.def.odr]p3:
17050   //   A function whose name appears as a potentially-evaluated expression is
17051   //   odr-used if it is the unique lookup result or the selected member of a
17052   //   set of overloaded functions [...].
17053   //
17054   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17055   // can just check that here.
17056   OdrUseContext OdrUse =
17057       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17058   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17059     OdrUse = OdrUseContext::FormallyOdrUsed;
17060 
17061   // Trivial default constructors and destructors are never actually used.
17062   // FIXME: What about other special members?
17063   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17064       OdrUse == OdrUseContext::Used) {
17065     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17066       if (Constructor->isDefaultConstructor())
17067         OdrUse = OdrUseContext::FormallyOdrUsed;
17068     if (isa<CXXDestructorDecl>(Func))
17069       OdrUse = OdrUseContext::FormallyOdrUsed;
17070   }
17071 
17072   // C++20 [expr.const]p12:
17073   //   A function [...] is needed for constant evaluation if it is [...] a
17074   //   constexpr function that is named by an expression that is potentially
17075   //   constant evaluated
17076   bool NeededForConstantEvaluation =
17077       isPotentiallyConstantEvaluatedContext(*this) &&
17078       isImplicitlyDefinableConstexprFunction(Func);
17079 
17080   // Determine whether we require a function definition to exist, per
17081   // C++11 [temp.inst]p3:
17082   //   Unless a function template specialization has been explicitly
17083   //   instantiated or explicitly specialized, the function template
17084   //   specialization is implicitly instantiated when the specialization is
17085   //   referenced in a context that requires a function definition to exist.
17086   // C++20 [temp.inst]p7:
17087   //   The existence of a definition of a [...] function is considered to
17088   //   affect the semantics of the program if the [...] function is needed for
17089   //   constant evaluation by an expression
17090   // C++20 [basic.def.odr]p10:
17091   //   Every program shall contain exactly one definition of every non-inline
17092   //   function or variable that is odr-used in that program outside of a
17093   //   discarded statement
17094   // C++20 [special]p1:
17095   //   The implementation will implicitly define [defaulted special members]
17096   //   if they are odr-used or needed for constant evaluation.
17097   //
17098   // Note that we skip the implicit instantiation of templates that are only
17099   // used in unused default arguments or by recursive calls to themselves.
17100   // This is formally non-conforming, but seems reasonable in practice.
17101   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17102                                              NeededForConstantEvaluation);
17103 
17104   // C++14 [temp.expl.spec]p6:
17105   //   If a template [...] is explicitly specialized then that specialization
17106   //   shall be declared before the first use of that specialization that would
17107   //   cause an implicit instantiation to take place, in every translation unit
17108   //   in which such a use occurs
17109   if (NeedDefinition &&
17110       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17111        Func->getMemberSpecializationInfo()))
17112     checkSpecializationVisibility(Loc, Func);
17113 
17114   if (getLangOpts().CUDA)
17115     CheckCUDACall(Loc, Func);
17116 
17117   if (getLangOpts().SYCLIsDevice)
17118     checkSYCLDeviceFunction(Loc, Func);
17119 
17120   // If we need a definition, try to create one.
17121   if (NeedDefinition && !Func->getBody()) {
17122     runWithSufficientStackSpace(Loc, [&] {
17123       if (CXXConstructorDecl *Constructor =
17124               dyn_cast<CXXConstructorDecl>(Func)) {
17125         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17126         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17127           if (Constructor->isDefaultConstructor()) {
17128             if (Constructor->isTrivial() &&
17129                 !Constructor->hasAttr<DLLExportAttr>())
17130               return;
17131             DefineImplicitDefaultConstructor(Loc, Constructor);
17132           } else if (Constructor->isCopyConstructor()) {
17133             DefineImplicitCopyConstructor(Loc, Constructor);
17134           } else if (Constructor->isMoveConstructor()) {
17135             DefineImplicitMoveConstructor(Loc, Constructor);
17136           }
17137         } else if (Constructor->getInheritedConstructor()) {
17138           DefineInheritingConstructor(Loc, Constructor);
17139         }
17140       } else if (CXXDestructorDecl *Destructor =
17141                      dyn_cast<CXXDestructorDecl>(Func)) {
17142         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17143         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17144           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17145             return;
17146           DefineImplicitDestructor(Loc, Destructor);
17147         }
17148         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17149           MarkVTableUsed(Loc, Destructor->getParent());
17150       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17151         if (MethodDecl->isOverloadedOperator() &&
17152             MethodDecl->getOverloadedOperator() == OO_Equal) {
17153           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17154           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17155             if (MethodDecl->isCopyAssignmentOperator())
17156               DefineImplicitCopyAssignment(Loc, MethodDecl);
17157             else if (MethodDecl->isMoveAssignmentOperator())
17158               DefineImplicitMoveAssignment(Loc, MethodDecl);
17159           }
17160         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17161                    MethodDecl->getParent()->isLambda()) {
17162           CXXConversionDecl *Conversion =
17163               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17164           if (Conversion->isLambdaToBlockPointerConversion())
17165             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17166           else
17167             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17168         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17169           MarkVTableUsed(Loc, MethodDecl->getParent());
17170       }
17171 
17172       if (Func->isDefaulted() && !Func->isDeleted()) {
17173         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17174         if (DCK != DefaultedComparisonKind::None)
17175           DefineDefaultedComparison(Loc, Func, DCK);
17176       }
17177 
17178       // Implicit instantiation of function templates and member functions of
17179       // class templates.
17180       if (Func->isImplicitlyInstantiable()) {
17181         TemplateSpecializationKind TSK =
17182             Func->getTemplateSpecializationKindForInstantiation();
17183         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17184         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17185         if (FirstInstantiation) {
17186           PointOfInstantiation = Loc;
17187           if (auto *MSI = Func->getMemberSpecializationInfo())
17188             MSI->setPointOfInstantiation(Loc);
17189             // FIXME: Notify listener.
17190           else
17191             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17192         } else if (TSK != TSK_ImplicitInstantiation) {
17193           // Use the point of use as the point of instantiation, instead of the
17194           // point of explicit instantiation (which we track as the actual point
17195           // of instantiation). This gives better backtraces in diagnostics.
17196           PointOfInstantiation = Loc;
17197         }
17198 
17199         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17200             Func->isConstexpr()) {
17201           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17202               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17203               CodeSynthesisContexts.size())
17204             PendingLocalImplicitInstantiations.push_back(
17205                 std::make_pair(Func, PointOfInstantiation));
17206           else if (Func->isConstexpr())
17207             // Do not defer instantiations of constexpr functions, to avoid the
17208             // expression evaluator needing to call back into Sema if it sees a
17209             // call to such a function.
17210             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17211           else {
17212             Func->setInstantiationIsPending(true);
17213             PendingInstantiations.push_back(
17214                 std::make_pair(Func, PointOfInstantiation));
17215             // Notify the consumer that a function was implicitly instantiated.
17216             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17217           }
17218         }
17219       } else {
17220         // Walk redefinitions, as some of them may be instantiable.
17221         for (auto i : Func->redecls()) {
17222           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17223             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17224         }
17225       }
17226     });
17227   }
17228 
17229   // C++14 [except.spec]p17:
17230   //   An exception-specification is considered to be needed when:
17231   //   - the function is odr-used or, if it appears in an unevaluated operand,
17232   //     would be odr-used if the expression were potentially-evaluated;
17233   //
17234   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17235   // function is a pure virtual function we're calling, and in that case the
17236   // function was selected by overload resolution and we need to resolve its
17237   // exception specification for a different reason.
17238   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17239   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17240     ResolveExceptionSpec(Loc, FPT);
17241 
17242   // If this is the first "real" use, act on that.
17243   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17244     // Keep track of used but undefined functions.
17245     if (!Func->isDefined()) {
17246       if (mightHaveNonExternalLinkage(Func))
17247         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17248       else if (Func->getMostRecentDecl()->isInlined() &&
17249                !LangOpts.GNUInline &&
17250                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17251         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17252       else if (isExternalWithNoLinkageType(Func))
17253         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17254     }
17255 
17256     // Some x86 Windows calling conventions mangle the size of the parameter
17257     // pack into the name. Computing the size of the parameters requires the
17258     // parameter types to be complete. Check that now.
17259     if (funcHasParameterSizeMangling(*this, Func))
17260       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17261 
17262     // In the MS C++ ABI, the compiler emits destructor variants where they are
17263     // used. If the destructor is used here but defined elsewhere, mark the
17264     // virtual base destructors referenced. If those virtual base destructors
17265     // are inline, this will ensure they are defined when emitting the complete
17266     // destructor variant. This checking may be redundant if the destructor is
17267     // provided later in this TU.
17268     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17269       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17270         CXXRecordDecl *Parent = Dtor->getParent();
17271         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17272           CheckCompleteDestructorVariant(Loc, Dtor);
17273       }
17274     }
17275 
17276     Func->markUsed(Context);
17277   }
17278 }
17279 
17280 /// Directly mark a variable odr-used. Given a choice, prefer to use
17281 /// MarkVariableReferenced since it does additional checks and then
17282 /// calls MarkVarDeclODRUsed.
17283 /// If the variable must be captured:
17284 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17285 ///  - else capture it in the DeclContext that maps to the
17286 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17287 static void
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt=nullptr)17288 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17289                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17290   // Keep track of used but undefined variables.
17291   // FIXME: We shouldn't suppress this warning for static data members.
17292   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17293       (!Var->isExternallyVisible() || Var->isInline() ||
17294        SemaRef.isExternalWithNoLinkageType(Var)) &&
17295       !(Var->isStaticDataMember() && Var->hasInit())) {
17296     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17297     if (old.isInvalid())
17298       old = Loc;
17299   }
17300   QualType CaptureType, DeclRefType;
17301   if (SemaRef.LangOpts.OpenMP)
17302     SemaRef.tryCaptureOpenMPLambdas(Var);
17303   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17304     /*EllipsisLoc*/ SourceLocation(),
17305     /*BuildAndDiagnose*/ true,
17306     CaptureType, DeclRefType,
17307     FunctionScopeIndexToStopAt);
17308 
17309   if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17310     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17311     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17312     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17313     if (VarTarget == Sema::CVT_Host &&
17314         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17315          UserTarget == Sema::CFT_Global)) {
17316       // Diagnose ODR-use of host global variables in device functions.
17317       // Reference of device global variables in host functions is allowed
17318       // through shadow variables therefore it is not diagnosed.
17319       if (SemaRef.LangOpts.CUDAIsDevice) {
17320         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17321             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17322         SemaRef.targetDiag(Var->getLocation(),
17323                            Var->getType().isConstQualified()
17324                                ? diag::note_cuda_const_var_unpromoted
17325                                : diag::note_cuda_host_var);
17326       }
17327     } else if (VarTarget == Sema::CVT_Device &&
17328                (UserTarget == Sema::CFT_Host ||
17329                 UserTarget == Sema::CFT_HostDevice) &&
17330                !Var->hasExternalStorage()) {
17331       // Record a CUDA/HIP device side variable if it is ODR-used
17332       // by host code. This is done conservatively, when the variable is
17333       // referenced in any of the following contexts:
17334       //   - a non-function context
17335       //   - a host function
17336       //   - a host device function
17337       // This makes the ODR-use of the device side variable by host code to
17338       // be visible in the device compilation for the compiler to be able to
17339       // emit template variables instantiated by host code only and to
17340       // externalize the static device side variable ODR-used by host code.
17341       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17342     }
17343   }
17344 
17345   Var->markUsed(SemaRef.Context);
17346 }
17347 
MarkCaptureUsedInEnclosingContext(VarDecl * Capture,SourceLocation Loc,unsigned CapturingScopeIndex)17348 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17349                                              SourceLocation Loc,
17350                                              unsigned CapturingScopeIndex) {
17351   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17352 }
17353 
17354 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,ValueDecl * var,DeclContext * DC)17355 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17356                                    ValueDecl *var, DeclContext *DC) {
17357   DeclContext *VarDC = var->getDeclContext();
17358 
17359   //  If the parameter still belongs to the translation unit, then
17360   //  we're actually just using one parameter in the declaration of
17361   //  the next.
17362   if (isa<ParmVarDecl>(var) &&
17363       isa<TranslationUnitDecl>(VarDC))
17364     return;
17365 
17366   // For C code, don't diagnose about capture if we're not actually in code
17367   // right now; it's impossible to write a non-constant expression outside of
17368   // function context, so we'll get other (more useful) diagnostics later.
17369   //
17370   // For C++, things get a bit more nasty... it would be nice to suppress this
17371   // diagnostic for certain cases like using a local variable in an array bound
17372   // for a member of a local class, but the correct predicate is not obvious.
17373   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17374     return;
17375 
17376   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17377   unsigned ContextKind = 3; // unknown
17378   if (isa<CXXMethodDecl>(VarDC) &&
17379       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17380     ContextKind = 2;
17381   } else if (isa<FunctionDecl>(VarDC)) {
17382     ContextKind = 0;
17383   } else if (isa<BlockDecl>(VarDC)) {
17384     ContextKind = 1;
17385   }
17386 
17387   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17388     << var << ValueKind << ContextKind << VarDC;
17389   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17390       << var;
17391 
17392   // FIXME: Add additional diagnostic info about class etc. which prevents
17393   // capture.
17394 }
17395 
17396 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)17397 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17398                                       bool &SubCapturesAreNested,
17399                                       QualType &CaptureType,
17400                                       QualType &DeclRefType) {
17401    // Check whether we've already captured it.
17402   if (CSI->CaptureMap.count(Var)) {
17403     // If we found a capture, any subcaptures are nested.
17404     SubCapturesAreNested = true;
17405 
17406     // Retrieve the capture type for this variable.
17407     CaptureType = CSI->getCapture(Var).getCaptureType();
17408 
17409     // Compute the type of an expression that refers to this variable.
17410     DeclRefType = CaptureType.getNonReferenceType();
17411 
17412     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17413     // are mutable in the sense that user can change their value - they are
17414     // private instances of the captured declarations.
17415     const Capture &Cap = CSI->getCapture(Var);
17416     if (Cap.isCopyCapture() &&
17417         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17418         !(isa<CapturedRegionScopeInfo>(CSI) &&
17419           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17420       DeclRefType.addConst();
17421     return true;
17422   }
17423   return false;
17424 }
17425 
17426 // Only block literals, captured statements, and lambda expressions can
17427 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17428 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17429                                  SourceLocation Loc,
17430                                  const bool Diagnose, Sema &S) {
17431   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17432     return getLambdaAwareParentOfDeclContext(DC);
17433   else if (Var->hasLocalStorage()) {
17434     if (Diagnose)
17435        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17436   }
17437   return nullptr;
17438 }
17439 
17440 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17441 // certain types of variables (unnamed, variably modified types etc.)
17442 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17443 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17444                                  SourceLocation Loc,
17445                                  const bool Diagnose, Sema &S) {
17446 
17447   bool IsBlock = isa<BlockScopeInfo>(CSI);
17448   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17449 
17450   // Lambdas are not allowed to capture unnamed variables
17451   // (e.g. anonymous unions).
17452   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17453   // assuming that's the intent.
17454   if (IsLambda && !Var->getDeclName()) {
17455     if (Diagnose) {
17456       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17457       S.Diag(Var->getLocation(), diag::note_declared_at);
17458     }
17459     return false;
17460   }
17461 
17462   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17463   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17464     if (Diagnose) {
17465       S.Diag(Loc, diag::err_ref_vm_type);
17466       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17467     }
17468     return false;
17469   }
17470   // Prohibit structs with flexible array members too.
17471   // We cannot capture what is in the tail end of the struct.
17472   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17473     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17474       if (Diagnose) {
17475         if (IsBlock)
17476           S.Diag(Loc, diag::err_ref_flexarray_type);
17477         else
17478           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17479         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17480       }
17481       return false;
17482     }
17483   }
17484   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17485   // Lambdas and captured statements are not allowed to capture __block
17486   // variables; they don't support the expected semantics.
17487   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17488     if (Diagnose) {
17489       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17490       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17491     }
17492     return false;
17493   }
17494   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17495   if (S.getLangOpts().OpenCL && IsBlock &&
17496       Var->getType()->isBlockPointerType()) {
17497     if (Diagnose)
17498       S.Diag(Loc, diag::err_opencl_block_ref_block);
17499     return false;
17500   }
17501 
17502   return true;
17503 }
17504 
17505 // Returns true if the capture by block was successful.
captureInBlock(BlockScopeInfo * BSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool Nested,Sema & S,bool Invalid)17506 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17507                                  SourceLocation Loc,
17508                                  const bool BuildAndDiagnose,
17509                                  QualType &CaptureType,
17510                                  QualType &DeclRefType,
17511                                  const bool Nested,
17512                                  Sema &S, bool Invalid) {
17513   bool ByRef = false;
17514 
17515   // Blocks are not allowed to capture arrays, excepting OpenCL.
17516   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17517   // (decayed to pointers).
17518   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17519     if (BuildAndDiagnose) {
17520       S.Diag(Loc, diag::err_ref_array_type);
17521       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17522       Invalid = true;
17523     } else {
17524       return false;
17525     }
17526   }
17527 
17528   // Forbid the block-capture of autoreleasing variables.
17529   if (!Invalid &&
17530       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17531     if (BuildAndDiagnose) {
17532       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17533         << /*block*/ 0;
17534       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17535       Invalid = true;
17536     } else {
17537       return false;
17538     }
17539   }
17540 
17541   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17542   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17543     QualType PointeeTy = PT->getPointeeType();
17544 
17545     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17546         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17547         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17548       if (BuildAndDiagnose) {
17549         SourceLocation VarLoc = Var->getLocation();
17550         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17551         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17552       }
17553     }
17554   }
17555 
17556   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17557   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17558       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17559     // Block capture by reference does not change the capture or
17560     // declaration reference types.
17561     ByRef = true;
17562   } else {
17563     // Block capture by copy introduces 'const'.
17564     CaptureType = CaptureType.getNonReferenceType().withConst();
17565     DeclRefType = CaptureType;
17566   }
17567 
17568   // Actually capture the variable.
17569   if (BuildAndDiagnose)
17570     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17571                     CaptureType, Invalid);
17572 
17573   return !Invalid;
17574 }
17575 
17576 
17577 /// Capture the given variable in the captured region.
captureInCapturedRegion(CapturedRegionScopeInfo * RSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,Sema::TryCaptureKind Kind,bool IsTopScope,Sema & S,bool Invalid)17578 static bool captureInCapturedRegion(
17579     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17580     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17581     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17582     bool IsTopScope, Sema &S, bool Invalid) {
17583   // By default, capture variables by reference.
17584   bool ByRef = true;
17585   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17586     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17587   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17588     // Using an LValue reference type is consistent with Lambdas (see below).
17589     if (S.isOpenMPCapturedDecl(Var)) {
17590       bool HasConst = DeclRefType.isConstQualified();
17591       DeclRefType = DeclRefType.getUnqualifiedType();
17592       // Don't lose diagnostics about assignments to const.
17593       if (HasConst)
17594         DeclRefType.addConst();
17595     }
17596     // Do not capture firstprivates in tasks.
17597     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17598         OMPC_unknown)
17599       return true;
17600     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17601                                     RSI->OpenMPCaptureLevel);
17602   }
17603 
17604   if (ByRef)
17605     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17606   else
17607     CaptureType = DeclRefType;
17608 
17609   // Actually capture the variable.
17610   if (BuildAndDiagnose)
17611     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17612                     Loc, SourceLocation(), CaptureType, Invalid);
17613 
17614   return !Invalid;
17615 }
17616 
17617 /// Capture the given variable in the lambda.
captureInLambda(LambdaScopeInfo * LSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,const Sema::TryCaptureKind Kind,SourceLocation EllipsisLoc,const bool IsTopScope,Sema & S,bool Invalid)17618 static bool captureInLambda(LambdaScopeInfo *LSI,
17619                             VarDecl *Var,
17620                             SourceLocation Loc,
17621                             const bool BuildAndDiagnose,
17622                             QualType &CaptureType,
17623                             QualType &DeclRefType,
17624                             const bool RefersToCapturedVariable,
17625                             const Sema::TryCaptureKind Kind,
17626                             SourceLocation EllipsisLoc,
17627                             const bool IsTopScope,
17628                             Sema &S, bool Invalid) {
17629   // Determine whether we are capturing by reference or by value.
17630   bool ByRef = false;
17631   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17632     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17633   } else {
17634     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17635   }
17636 
17637   // Compute the type of the field that will capture this variable.
17638   if (ByRef) {
17639     // C++11 [expr.prim.lambda]p15:
17640     //   An entity is captured by reference if it is implicitly or
17641     //   explicitly captured but not captured by copy. It is
17642     //   unspecified whether additional unnamed non-static data
17643     //   members are declared in the closure type for entities
17644     //   captured by reference.
17645     //
17646     // FIXME: It is not clear whether we want to build an lvalue reference
17647     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17648     // to do the former, while EDG does the latter. Core issue 1249 will
17649     // clarify, but for now we follow GCC because it's a more permissive and
17650     // easily defensible position.
17651     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17652   } else {
17653     // C++11 [expr.prim.lambda]p14:
17654     //   For each entity captured by copy, an unnamed non-static
17655     //   data member is declared in the closure type. The
17656     //   declaration order of these members is unspecified. The type
17657     //   of such a data member is the type of the corresponding
17658     //   captured entity if the entity is not a reference to an
17659     //   object, or the referenced type otherwise. [Note: If the
17660     //   captured entity is a reference to a function, the
17661     //   corresponding data member is also a reference to a
17662     //   function. - end note ]
17663     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17664       if (!RefType->getPointeeType()->isFunctionType())
17665         CaptureType = RefType->getPointeeType();
17666     }
17667 
17668     // Forbid the lambda copy-capture of autoreleasing variables.
17669     if (!Invalid &&
17670         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17671       if (BuildAndDiagnose) {
17672         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17673         S.Diag(Var->getLocation(), diag::note_previous_decl)
17674           << Var->getDeclName();
17675         Invalid = true;
17676       } else {
17677         return false;
17678       }
17679     }
17680 
17681     // Make sure that by-copy captures are of a complete and non-abstract type.
17682     if (!Invalid && BuildAndDiagnose) {
17683       if (!CaptureType->isDependentType() &&
17684           S.RequireCompleteSizedType(
17685               Loc, CaptureType,
17686               diag::err_capture_of_incomplete_or_sizeless_type,
17687               Var->getDeclName()))
17688         Invalid = true;
17689       else if (S.RequireNonAbstractType(Loc, CaptureType,
17690                                         diag::err_capture_of_abstract_type))
17691         Invalid = true;
17692     }
17693   }
17694 
17695   // Compute the type of a reference to this captured variable.
17696   if (ByRef)
17697     DeclRefType = CaptureType.getNonReferenceType();
17698   else {
17699     // C++ [expr.prim.lambda]p5:
17700     //   The closure type for a lambda-expression has a public inline
17701     //   function call operator [...]. This function call operator is
17702     //   declared const (9.3.1) if and only if the lambda-expression's
17703     //   parameter-declaration-clause is not followed by mutable.
17704     DeclRefType = CaptureType.getNonReferenceType();
17705     if (!LSI->Mutable && !CaptureType->isReferenceType())
17706       DeclRefType.addConst();
17707   }
17708 
17709   // Add the capture.
17710   if (BuildAndDiagnose)
17711     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17712                     Loc, EllipsisLoc, CaptureType, Invalid);
17713 
17714   return !Invalid;
17715 }
17716 
canCaptureVariableByCopy(VarDecl * Var,const ASTContext & Context)17717 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17718   // Offer a Copy fix even if the type is dependent.
17719   if (Var->getType()->isDependentType())
17720     return true;
17721   QualType T = Var->getType().getNonReferenceType();
17722   if (T.isTriviallyCopyableType(Context))
17723     return true;
17724   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17725 
17726     if (!(RD = RD->getDefinition()))
17727       return false;
17728     if (RD->hasSimpleCopyConstructor())
17729       return true;
17730     if (RD->hasUserDeclaredCopyConstructor())
17731       for (CXXConstructorDecl *Ctor : RD->ctors())
17732         if (Ctor->isCopyConstructor())
17733           return !Ctor->isDeleted();
17734   }
17735   return false;
17736 }
17737 
17738 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17739 /// default capture. Fixes may be omitted if they aren't allowed by the
17740 /// standard, for example we can't emit a default copy capture fix-it if we
17741 /// already explicitly copy capture capture another variable.
buildLambdaCaptureFixit(Sema & Sema,LambdaScopeInfo * LSI,VarDecl * Var)17742 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17743                                     VarDecl *Var) {
17744   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17745   // Don't offer Capture by copy of default capture by copy fixes if Var is
17746   // known not to be copy constructible.
17747   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17748 
17749   SmallString<32> FixBuffer;
17750   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17751   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17752     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17753     if (ShouldOfferCopyFix) {
17754       // Offer fixes to insert an explicit capture for the variable.
17755       // [] -> [VarName]
17756       // [OtherCapture] -> [OtherCapture, VarName]
17757       FixBuffer.assign({Separator, Var->getName()});
17758       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17759           << Var << /*value*/ 0
17760           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17761     }
17762     // As above but capture by reference.
17763     FixBuffer.assign({Separator, "&", Var->getName()});
17764     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17765         << Var << /*reference*/ 1
17766         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17767   }
17768 
17769   // Only try to offer default capture if there are no captures excluding this
17770   // and init captures.
17771   // [this]: OK.
17772   // [X = Y]: OK.
17773   // [&A, &B]: Don't offer.
17774   // [A, B]: Don't offer.
17775   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17776         return !C.isThisCapture() && !C.isInitCapture();
17777       }))
17778     return;
17779 
17780   // The default capture specifiers, '=' or '&', must appear first in the
17781   // capture body.
17782   SourceLocation DefaultInsertLoc =
17783       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17784 
17785   if (ShouldOfferCopyFix) {
17786     bool CanDefaultCopyCapture = true;
17787     // [=, *this] OK since c++17
17788     // [=, this] OK since c++20
17789     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17790       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17791                                   ? LSI->getCXXThisCapture().isCopyCapture()
17792                                   : false;
17793     // We can't use default capture by copy if any captures already specified
17794     // capture by copy.
17795     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17796           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17797         })) {
17798       FixBuffer.assign({"=", Separator});
17799       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17800           << /*value*/ 0
17801           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17802     }
17803   }
17804 
17805   // We can't use default capture by reference if any captures already specified
17806   // capture by reference.
17807   if (llvm::none_of(LSI->Captures, [](Capture &C) {
17808         return !C.isInitCapture() && C.isReferenceCapture() &&
17809                !C.isThisCapture();
17810       })) {
17811     FixBuffer.assign({"&", Separator});
17812     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17813         << /*reference*/ 1
17814         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17815   }
17816 }
17817 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)17818 bool Sema::tryCaptureVariable(
17819     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17820     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17821     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17822   // An init-capture is notionally from the context surrounding its
17823   // declaration, but its parent DC is the lambda class.
17824   DeclContext *VarDC = Var->getDeclContext();
17825   if (Var->isInitCapture())
17826     VarDC = VarDC->getParent();
17827 
17828   DeclContext *DC = CurContext;
17829   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17830       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17831   // We need to sync up the Declaration Context with the
17832   // FunctionScopeIndexToStopAt
17833   if (FunctionScopeIndexToStopAt) {
17834     unsigned FSIndex = FunctionScopes.size() - 1;
17835     while (FSIndex != MaxFunctionScopesIndex) {
17836       DC = getLambdaAwareParentOfDeclContext(DC);
17837       --FSIndex;
17838     }
17839   }
17840 
17841 
17842   // If the variable is declared in the current context, there is no need to
17843   // capture it.
17844   if (VarDC == DC) return true;
17845 
17846   // Capture global variables if it is required to use private copy of this
17847   // variable.
17848   bool IsGlobal = !Var->hasLocalStorage();
17849   if (IsGlobal &&
17850       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17851                                                 MaxFunctionScopesIndex)))
17852     return true;
17853   Var = Var->getCanonicalDecl();
17854 
17855   // Walk up the stack to determine whether we can capture the variable,
17856   // performing the "simple" checks that don't depend on type. We stop when
17857   // we've either hit the declared scope of the variable or find an existing
17858   // capture of that variable.  We start from the innermost capturing-entity
17859   // (the DC) and ensure that all intervening capturing-entities
17860   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17861   // declcontext can either capture the variable or have already captured
17862   // the variable.
17863   CaptureType = Var->getType();
17864   DeclRefType = CaptureType.getNonReferenceType();
17865   bool Nested = false;
17866   bool Explicit = (Kind != TryCapture_Implicit);
17867   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17868   do {
17869     // Only block literals, captured statements, and lambda expressions can
17870     // capture; other scopes don't work.
17871     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17872                                                               ExprLoc,
17873                                                               BuildAndDiagnose,
17874                                                               *this);
17875     // We need to check for the parent *first* because, if we *have*
17876     // private-captured a global variable, we need to recursively capture it in
17877     // intermediate blocks, lambdas, etc.
17878     if (!ParentDC) {
17879       if (IsGlobal) {
17880         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17881         break;
17882       }
17883       return true;
17884     }
17885 
17886     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17887     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17888 
17889 
17890     // Check whether we've already captured it.
17891     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17892                                              DeclRefType)) {
17893       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17894       break;
17895     }
17896     // If we are instantiating a generic lambda call operator body,
17897     // we do not want to capture new variables.  What was captured
17898     // during either a lambdas transformation or initial parsing
17899     // should be used.
17900     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17901       if (BuildAndDiagnose) {
17902         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17903         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17904           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17905           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17906           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17907           buildLambdaCaptureFixit(*this, LSI, Var);
17908         } else
17909           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17910       }
17911       return true;
17912     }
17913 
17914     // Try to capture variable-length arrays types.
17915     if (Var->getType()->isVariablyModifiedType()) {
17916       // We're going to walk down into the type and look for VLA
17917       // expressions.
17918       QualType QTy = Var->getType();
17919       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17920         QTy = PVD->getOriginalType();
17921       captureVariablyModifiedType(Context, QTy, CSI);
17922     }
17923 
17924     if (getLangOpts().OpenMP) {
17925       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17926         // OpenMP private variables should not be captured in outer scope, so
17927         // just break here. Similarly, global variables that are captured in a
17928         // target region should not be captured outside the scope of the region.
17929         if (RSI->CapRegionKind == CR_OpenMP) {
17930           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17931               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17932           // If the variable is private (i.e. not captured) and has variably
17933           // modified type, we still need to capture the type for correct
17934           // codegen in all regions, associated with the construct. Currently,
17935           // it is captured in the innermost captured region only.
17936           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17937               Var->getType()->isVariablyModifiedType()) {
17938             QualType QTy = Var->getType();
17939             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17940               QTy = PVD->getOriginalType();
17941             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17942                  I < E; ++I) {
17943               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17944                   FunctionScopes[FunctionScopesIndex - I]);
17945               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17946                      "Wrong number of captured regions associated with the "
17947                      "OpenMP construct.");
17948               captureVariablyModifiedType(Context, QTy, OuterRSI);
17949             }
17950           }
17951           bool IsTargetCap =
17952               IsOpenMPPrivateDecl != OMPC_private &&
17953               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17954                                          RSI->OpenMPCaptureLevel);
17955           // Do not capture global if it is not privatized in outer regions.
17956           bool IsGlobalCap =
17957               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17958                                                      RSI->OpenMPCaptureLevel);
17959 
17960           // When we detect target captures we are looking from inside the
17961           // target region, therefore we need to propagate the capture from the
17962           // enclosing region. Therefore, the capture is not initially nested.
17963           if (IsTargetCap)
17964             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17965 
17966           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17967               (IsGlobal && !IsGlobalCap)) {
17968             Nested = !IsTargetCap;
17969             bool HasConst = DeclRefType.isConstQualified();
17970             DeclRefType = DeclRefType.getUnqualifiedType();
17971             // Don't lose diagnostics about assignments to const.
17972             if (HasConst)
17973               DeclRefType.addConst();
17974             CaptureType = Context.getLValueReferenceType(DeclRefType);
17975             break;
17976           }
17977         }
17978       }
17979     }
17980     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17981       // No capture-default, and this is not an explicit capture
17982       // so cannot capture this variable.
17983       if (BuildAndDiagnose) {
17984         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17985         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17986         auto *LSI = cast<LambdaScopeInfo>(CSI);
17987         if (LSI->Lambda) {
17988           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17989           buildLambdaCaptureFixit(*this, LSI, Var);
17990         }
17991         // FIXME: If we error out because an outer lambda can not implicitly
17992         // capture a variable that an inner lambda explicitly captures, we
17993         // should have the inner lambda do the explicit capture - because
17994         // it makes for cleaner diagnostics later.  This would purely be done
17995         // so that the diagnostic does not misleadingly claim that a variable
17996         // can not be captured by a lambda implicitly even though it is captured
17997         // explicitly.  Suggestion:
17998         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17999         //    at the function head
18000         //  - cache the StartingDeclContext - this must be a lambda
18001         //  - captureInLambda in the innermost lambda the variable.
18002       }
18003       return true;
18004     }
18005 
18006     FunctionScopesIndex--;
18007     DC = ParentDC;
18008     Explicit = false;
18009   } while (!VarDC->Equals(DC));
18010 
18011   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18012   // computing the type of the capture at each step, checking type-specific
18013   // requirements, and adding captures if requested.
18014   // If the variable had already been captured previously, we start capturing
18015   // at the lambda nested within that one.
18016   bool Invalid = false;
18017   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18018        ++I) {
18019     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18020 
18021     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18022     // certain types of variables (unnamed, variably modified types etc.)
18023     // so check for eligibility.
18024     if (!Invalid)
18025       Invalid =
18026           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18027 
18028     // After encountering an error, if we're actually supposed to capture, keep
18029     // capturing in nested contexts to suppress any follow-on diagnostics.
18030     if (Invalid && !BuildAndDiagnose)
18031       return true;
18032 
18033     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18034       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18035                                DeclRefType, Nested, *this, Invalid);
18036       Nested = true;
18037     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18038       Invalid = !captureInCapturedRegion(
18039           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18040           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18041       Nested = true;
18042     } else {
18043       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18044       Invalid =
18045           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18046                            DeclRefType, Nested, Kind, EllipsisLoc,
18047                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18048       Nested = true;
18049     }
18050 
18051     if (Invalid && !BuildAndDiagnose)
18052       return true;
18053   }
18054   return Invalid;
18055 }
18056 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)18057 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18058                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18059   QualType CaptureType;
18060   QualType DeclRefType;
18061   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18062                             /*BuildAndDiagnose=*/true, CaptureType,
18063                             DeclRefType, nullptr);
18064 }
18065 
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)18066 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18067   QualType CaptureType;
18068   QualType DeclRefType;
18069   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18070                              /*BuildAndDiagnose=*/false, CaptureType,
18071                              DeclRefType, nullptr);
18072 }
18073 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)18074 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18075   QualType CaptureType;
18076   QualType DeclRefType;
18077 
18078   // Determine whether we can capture this variable.
18079   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18080                          /*BuildAndDiagnose=*/false, CaptureType,
18081                          DeclRefType, nullptr))
18082     return QualType();
18083 
18084   return DeclRefType;
18085 }
18086 
18087 namespace {
18088 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18089 // The produced TemplateArgumentListInfo* points to data stored within this
18090 // object, so should only be used in contexts where the pointer will not be
18091 // used after the CopiedTemplateArgs object is destroyed.
18092 class CopiedTemplateArgs {
18093   bool HasArgs;
18094   TemplateArgumentListInfo TemplateArgStorage;
18095 public:
18096   template<typename RefExpr>
CopiedTemplateArgs(RefExpr * E)18097   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18098     if (HasArgs)
18099       E->copyTemplateArgumentsInto(TemplateArgStorage);
18100   }
operator TemplateArgumentListInfo*()18101   operator TemplateArgumentListInfo*()
18102 #ifdef __has_cpp_attribute
18103 #if __has_cpp_attribute(clang::lifetimebound)
18104   [[clang::lifetimebound]]
18105 #endif
18106 #endif
18107   {
18108     return HasArgs ? &TemplateArgStorage : nullptr;
18109   }
18110 };
18111 }
18112 
18113 /// Walk the set of potential results of an expression and mark them all as
18114 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18115 ///
18116 /// \return A new expression if we found any potential results, ExprEmpty() if
18117 ///         not, and ExprError() if we diagnosed an error.
rebuildPotentialResultsAsNonOdrUsed(Sema & S,Expr * E,NonOdrUseReason NOUR)18118 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18119                                                       NonOdrUseReason NOUR) {
18120   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18121   // an object that satisfies the requirements for appearing in a
18122   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18123   // is immediately applied."  This function handles the lvalue-to-rvalue
18124   // conversion part.
18125   //
18126   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18127   // transform it into the relevant kind of non-odr-use node and rebuild the
18128   // tree of nodes leading to it.
18129   //
18130   // This is a mini-TreeTransform that only transforms a restricted subset of
18131   // nodes (and only certain operands of them).
18132 
18133   // Rebuild a subexpression.
18134   auto Rebuild = [&](Expr *Sub) {
18135     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18136   };
18137 
18138   // Check whether a potential result satisfies the requirements of NOUR.
18139   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18140     // Any entity other than a VarDecl is always odr-used whenever it's named
18141     // in a potentially-evaluated expression.
18142     auto *VD = dyn_cast<VarDecl>(D);
18143     if (!VD)
18144       return true;
18145 
18146     // C++2a [basic.def.odr]p4:
18147     //   A variable x whose name appears as a potentially-evalauted expression
18148     //   e is odr-used by e unless
18149     //   -- x is a reference that is usable in constant expressions, or
18150     //   -- x is a variable of non-reference type that is usable in constant
18151     //      expressions and has no mutable subobjects, and e is an element of
18152     //      the set of potential results of an expression of
18153     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18154     //      conversion is applied, or
18155     //   -- x is a variable of non-reference type, and e is an element of the
18156     //      set of potential results of a discarded-value expression to which
18157     //      the lvalue-to-rvalue conversion is not applied
18158     //
18159     // We check the first bullet and the "potentially-evaluated" condition in
18160     // BuildDeclRefExpr. We check the type requirements in the second bullet
18161     // in CheckLValueToRValueConversionOperand below.
18162     switch (NOUR) {
18163     case NOUR_None:
18164     case NOUR_Unevaluated:
18165       llvm_unreachable("unexpected non-odr-use-reason");
18166 
18167     case NOUR_Constant:
18168       // Constant references were handled when they were built.
18169       if (VD->getType()->isReferenceType())
18170         return true;
18171       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18172         if (RD->hasMutableFields())
18173           return true;
18174       if (!VD->isUsableInConstantExpressions(S.Context))
18175         return true;
18176       break;
18177 
18178     case NOUR_Discarded:
18179       if (VD->getType()->isReferenceType())
18180         return true;
18181       break;
18182     }
18183     return false;
18184   };
18185 
18186   // Mark that this expression does not constitute an odr-use.
18187   auto MarkNotOdrUsed = [&] {
18188     S.MaybeODRUseExprs.remove(E);
18189     if (LambdaScopeInfo *LSI = S.getCurLambda())
18190       LSI->markVariableExprAsNonODRUsed(E);
18191   };
18192 
18193   // C++2a [basic.def.odr]p2:
18194   //   The set of potential results of an expression e is defined as follows:
18195   switch (E->getStmtClass()) {
18196   //   -- If e is an id-expression, ...
18197   case Expr::DeclRefExprClass: {
18198     auto *DRE = cast<DeclRefExpr>(E);
18199     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18200       break;
18201 
18202     // Rebuild as a non-odr-use DeclRefExpr.
18203     MarkNotOdrUsed();
18204     return DeclRefExpr::Create(
18205         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18206         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18207         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18208         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18209   }
18210 
18211   case Expr::FunctionParmPackExprClass: {
18212     auto *FPPE = cast<FunctionParmPackExpr>(E);
18213     // If any of the declarations in the pack is odr-used, then the expression
18214     // as a whole constitutes an odr-use.
18215     for (VarDecl *D : *FPPE)
18216       if (IsPotentialResultOdrUsed(D))
18217         return ExprEmpty();
18218 
18219     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18220     // nothing cares about whether we marked this as an odr-use, but it might
18221     // be useful for non-compiler tools.
18222     MarkNotOdrUsed();
18223     break;
18224   }
18225 
18226   //   -- If e is a subscripting operation with an array operand...
18227   case Expr::ArraySubscriptExprClass: {
18228     auto *ASE = cast<ArraySubscriptExpr>(E);
18229     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18230     if (!OldBase->getType()->isArrayType())
18231       break;
18232     ExprResult Base = Rebuild(OldBase);
18233     if (!Base.isUsable())
18234       return Base;
18235     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18236     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18237     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18238     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18239                                      ASE->getRBracketLoc());
18240   }
18241 
18242   case Expr::MemberExprClass: {
18243     auto *ME = cast<MemberExpr>(E);
18244     // -- If e is a class member access expression [...] naming a non-static
18245     //    data member...
18246     if (isa<FieldDecl>(ME->getMemberDecl())) {
18247       ExprResult Base = Rebuild(ME->getBase());
18248       if (!Base.isUsable())
18249         return Base;
18250       return MemberExpr::Create(
18251           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18252           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18253           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18254           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18255           ME->getObjectKind(), ME->isNonOdrUse());
18256     }
18257 
18258     if (ME->getMemberDecl()->isCXXInstanceMember())
18259       break;
18260 
18261     // -- If e is a class member access expression naming a static data member,
18262     //    ...
18263     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18264       break;
18265 
18266     // Rebuild as a non-odr-use MemberExpr.
18267     MarkNotOdrUsed();
18268     return MemberExpr::Create(
18269         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18270         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18271         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18272         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18273     return ExprEmpty();
18274   }
18275 
18276   case Expr::BinaryOperatorClass: {
18277     auto *BO = cast<BinaryOperator>(E);
18278     Expr *LHS = BO->getLHS();
18279     Expr *RHS = BO->getRHS();
18280     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18281     if (BO->getOpcode() == BO_PtrMemD) {
18282       ExprResult Sub = Rebuild(LHS);
18283       if (!Sub.isUsable())
18284         return Sub;
18285       LHS = Sub.get();
18286     //   -- If e is a comma expression, ...
18287     } else if (BO->getOpcode() == BO_Comma) {
18288       ExprResult Sub = Rebuild(RHS);
18289       if (!Sub.isUsable())
18290         return Sub;
18291       RHS = Sub.get();
18292     } else {
18293       break;
18294     }
18295     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18296                         LHS, RHS);
18297   }
18298 
18299   //   -- If e has the form (e1)...
18300   case Expr::ParenExprClass: {
18301     auto *PE = cast<ParenExpr>(E);
18302     ExprResult Sub = Rebuild(PE->getSubExpr());
18303     if (!Sub.isUsable())
18304       return Sub;
18305     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18306   }
18307 
18308   //   -- If e is a glvalue conditional expression, ...
18309   // We don't apply this to a binary conditional operator. FIXME: Should we?
18310   case Expr::ConditionalOperatorClass: {
18311     auto *CO = cast<ConditionalOperator>(E);
18312     ExprResult LHS = Rebuild(CO->getLHS());
18313     if (LHS.isInvalid())
18314       return ExprError();
18315     ExprResult RHS = Rebuild(CO->getRHS());
18316     if (RHS.isInvalid())
18317       return ExprError();
18318     if (!LHS.isUsable() && !RHS.isUsable())
18319       return ExprEmpty();
18320     if (!LHS.isUsable())
18321       LHS = CO->getLHS();
18322     if (!RHS.isUsable())
18323       RHS = CO->getRHS();
18324     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18325                                 CO->getCond(), LHS.get(), RHS.get());
18326   }
18327 
18328   // [Clang extension]
18329   //   -- If e has the form __extension__ e1...
18330   case Expr::UnaryOperatorClass: {
18331     auto *UO = cast<UnaryOperator>(E);
18332     if (UO->getOpcode() != UO_Extension)
18333       break;
18334     ExprResult Sub = Rebuild(UO->getSubExpr());
18335     if (!Sub.isUsable())
18336       return Sub;
18337     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18338                           Sub.get());
18339   }
18340 
18341   // [Clang extension]
18342   //   -- If e has the form _Generic(...), the set of potential results is the
18343   //      union of the sets of potential results of the associated expressions.
18344   case Expr::GenericSelectionExprClass: {
18345     auto *GSE = cast<GenericSelectionExpr>(E);
18346 
18347     SmallVector<Expr *, 4> AssocExprs;
18348     bool AnyChanged = false;
18349     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18350       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18351       if (AssocExpr.isInvalid())
18352         return ExprError();
18353       if (AssocExpr.isUsable()) {
18354         AssocExprs.push_back(AssocExpr.get());
18355         AnyChanged = true;
18356       } else {
18357         AssocExprs.push_back(OrigAssocExpr);
18358       }
18359     }
18360 
18361     return AnyChanged ? S.CreateGenericSelectionExpr(
18362                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18363                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18364                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18365                       : ExprEmpty();
18366   }
18367 
18368   // [Clang extension]
18369   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18370   //      results is the union of the sets of potential results of the
18371   //      second and third subexpressions.
18372   case Expr::ChooseExprClass: {
18373     auto *CE = cast<ChooseExpr>(E);
18374 
18375     ExprResult LHS = Rebuild(CE->getLHS());
18376     if (LHS.isInvalid())
18377       return ExprError();
18378 
18379     ExprResult RHS = Rebuild(CE->getLHS());
18380     if (RHS.isInvalid())
18381       return ExprError();
18382 
18383     if (!LHS.get() && !RHS.get())
18384       return ExprEmpty();
18385     if (!LHS.isUsable())
18386       LHS = CE->getLHS();
18387     if (!RHS.isUsable())
18388       RHS = CE->getRHS();
18389 
18390     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18391                              RHS.get(), CE->getRParenLoc());
18392   }
18393 
18394   // Step through non-syntactic nodes.
18395   case Expr::ConstantExprClass: {
18396     auto *CE = cast<ConstantExpr>(E);
18397     ExprResult Sub = Rebuild(CE->getSubExpr());
18398     if (!Sub.isUsable())
18399       return Sub;
18400     return ConstantExpr::Create(S.Context, Sub.get());
18401   }
18402 
18403   // We could mostly rely on the recursive rebuilding to rebuild implicit
18404   // casts, but not at the top level, so rebuild them here.
18405   case Expr::ImplicitCastExprClass: {
18406     auto *ICE = cast<ImplicitCastExpr>(E);
18407     // Only step through the narrow set of cast kinds we expect to encounter.
18408     // Anything else suggests we've left the region in which potential results
18409     // can be found.
18410     switch (ICE->getCastKind()) {
18411     case CK_NoOp:
18412     case CK_DerivedToBase:
18413     case CK_UncheckedDerivedToBase: {
18414       ExprResult Sub = Rebuild(ICE->getSubExpr());
18415       if (!Sub.isUsable())
18416         return Sub;
18417       CXXCastPath Path(ICE->path());
18418       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18419                                  ICE->getValueKind(), &Path);
18420     }
18421 
18422     default:
18423       break;
18424     }
18425     break;
18426   }
18427 
18428   default:
18429     break;
18430   }
18431 
18432   // Can't traverse through this node. Nothing to do.
18433   return ExprEmpty();
18434 }
18435 
CheckLValueToRValueConversionOperand(Expr * E)18436 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18437   // Check whether the operand is or contains an object of non-trivial C union
18438   // type.
18439   if (E->getType().isVolatileQualified() &&
18440       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18441        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18442     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18443                           Sema::NTCUC_LValueToRValueVolatile,
18444                           NTCUK_Destruct|NTCUK_Copy);
18445 
18446   // C++2a [basic.def.odr]p4:
18447   //   [...] an expression of non-volatile-qualified non-class type to which
18448   //   the lvalue-to-rvalue conversion is applied [...]
18449   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18450     return E;
18451 
18452   ExprResult Result =
18453       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18454   if (Result.isInvalid())
18455     return ExprError();
18456   return Result.get() ? Result : E;
18457 }
18458 
ActOnConstantExpression(ExprResult Res)18459 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18460   Res = CorrectDelayedTyposInExpr(Res);
18461 
18462   if (!Res.isUsable())
18463     return Res;
18464 
18465   // If a constant-expression is a reference to a variable where we delay
18466   // deciding whether it is an odr-use, just assume we will apply the
18467   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18468   // (a non-type template argument), we have special handling anyway.
18469   return CheckLValueToRValueConversionOperand(Res.get());
18470 }
18471 
CleanupVarDeclMarking()18472 void Sema::CleanupVarDeclMarking() {
18473   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18474   // call.
18475   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18476   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18477 
18478   for (Expr *E : LocalMaybeODRUseExprs) {
18479     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18480       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18481                          DRE->getLocation(), *this);
18482     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18483       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18484                          *this);
18485     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18486       for (VarDecl *VD : *FP)
18487         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18488     } else {
18489       llvm_unreachable("Unexpected expression");
18490     }
18491   }
18492 
18493   assert(MaybeODRUseExprs.empty() &&
18494          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18495 }
18496 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E,llvm::DenseMap<const VarDecl *,int> & RefsMinusAssignments)18497 static void DoMarkVarDeclReferenced(
18498     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18499     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18500   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18501           isa<FunctionParmPackExpr>(E)) &&
18502          "Invalid Expr argument to DoMarkVarDeclReferenced");
18503   Var->setReferenced();
18504 
18505   if (Var->isInvalidDecl())
18506     return;
18507 
18508   auto *MSI = Var->getMemberSpecializationInfo();
18509   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18510                                        : Var->getTemplateSpecializationKind();
18511 
18512   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18513   bool UsableInConstantExpr =
18514       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18515 
18516   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18517     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18518   }
18519 
18520   // C++20 [expr.const]p12:
18521   //   A variable [...] is needed for constant evaluation if it is [...] a
18522   //   variable whose name appears as a potentially constant evaluated
18523   //   expression that is either a contexpr variable or is of non-volatile
18524   //   const-qualified integral type or of reference type
18525   bool NeededForConstantEvaluation =
18526       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18527 
18528   bool NeedDefinition =
18529       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18530 
18531   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18532          "Can't instantiate a partial template specialization.");
18533 
18534   // If this might be a member specialization of a static data member, check
18535   // the specialization is visible. We already did the checks for variable
18536   // template specializations when we created them.
18537   if (NeedDefinition && TSK != TSK_Undeclared &&
18538       !isa<VarTemplateSpecializationDecl>(Var))
18539     SemaRef.checkSpecializationVisibility(Loc, Var);
18540 
18541   // Perform implicit instantiation of static data members, static data member
18542   // templates of class templates, and variable template specializations. Delay
18543   // instantiations of variable templates, except for those that could be used
18544   // in a constant expression.
18545   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18546     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18547     // instantiation declaration if a variable is usable in a constant
18548     // expression (among other cases).
18549     bool TryInstantiating =
18550         TSK == TSK_ImplicitInstantiation ||
18551         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18552 
18553     if (TryInstantiating) {
18554       SourceLocation PointOfInstantiation =
18555           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18556       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18557       if (FirstInstantiation) {
18558         PointOfInstantiation = Loc;
18559         if (MSI)
18560           MSI->setPointOfInstantiation(PointOfInstantiation);
18561           // FIXME: Notify listener.
18562         else
18563           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18564       }
18565 
18566       if (UsableInConstantExpr) {
18567         // Do not defer instantiations of variables that could be used in a
18568         // constant expression.
18569         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18570           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18571         });
18572 
18573         // Re-set the member to trigger a recomputation of the dependence bits
18574         // for the expression.
18575         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18576           DRE->setDecl(DRE->getDecl());
18577         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18578           ME->setMemberDecl(ME->getMemberDecl());
18579       } else if (FirstInstantiation ||
18580                  isa<VarTemplateSpecializationDecl>(Var)) {
18581         // FIXME: For a specialization of a variable template, we don't
18582         // distinguish between "declaration and type implicitly instantiated"
18583         // and "implicit instantiation of definition requested", so we have
18584         // no direct way to avoid enqueueing the pending instantiation
18585         // multiple times.
18586         SemaRef.PendingInstantiations
18587             .push_back(std::make_pair(Var, PointOfInstantiation));
18588       }
18589     }
18590   }
18591 
18592   // C++2a [basic.def.odr]p4:
18593   //   A variable x whose name appears as a potentially-evaluated expression e
18594   //   is odr-used by e unless
18595   //   -- x is a reference that is usable in constant expressions
18596   //   -- x is a variable of non-reference type that is usable in constant
18597   //      expressions and has no mutable subobjects [FIXME], and e is an
18598   //      element of the set of potential results of an expression of
18599   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18600   //      conversion is applied
18601   //   -- x is a variable of non-reference type, and e is an element of the set
18602   //      of potential results of a discarded-value expression to which the
18603   //      lvalue-to-rvalue conversion is not applied [FIXME]
18604   //
18605   // We check the first part of the second bullet here, and
18606   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18607   // FIXME: To get the third bullet right, we need to delay this even for
18608   // variables that are not usable in constant expressions.
18609 
18610   // If we already know this isn't an odr-use, there's nothing more to do.
18611   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18612     if (DRE->isNonOdrUse())
18613       return;
18614   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18615     if (ME->isNonOdrUse())
18616       return;
18617 
18618   switch (OdrUse) {
18619   case OdrUseContext::None:
18620     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18621            "missing non-odr-use marking for unevaluated decl ref");
18622     break;
18623 
18624   case OdrUseContext::FormallyOdrUsed:
18625     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18626     // behavior.
18627     break;
18628 
18629   case OdrUseContext::Used:
18630     // If we might later find that this expression isn't actually an odr-use,
18631     // delay the marking.
18632     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18633       SemaRef.MaybeODRUseExprs.insert(E);
18634     else
18635       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18636     break;
18637 
18638   case OdrUseContext::Dependent:
18639     // If this is a dependent context, we don't need to mark variables as
18640     // odr-used, but we may still need to track them for lambda capture.
18641     // FIXME: Do we also need to do this inside dependent typeid expressions
18642     // (which are modeled as unevaluated at this point)?
18643     const bool RefersToEnclosingScope =
18644         (SemaRef.CurContext != Var->getDeclContext() &&
18645          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18646     if (RefersToEnclosingScope) {
18647       LambdaScopeInfo *const LSI =
18648           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18649       if (LSI && (!LSI->CallOperator ||
18650                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18651         // If a variable could potentially be odr-used, defer marking it so
18652         // until we finish analyzing the full expression for any
18653         // lvalue-to-rvalue
18654         // or discarded value conversions that would obviate odr-use.
18655         // Add it to the list of potential captures that will be analyzed
18656         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18657         // unless the variable is a reference that was initialized by a constant
18658         // expression (this will never need to be captured or odr-used).
18659         //
18660         // FIXME: We can simplify this a lot after implementing P0588R1.
18661         assert(E && "Capture variable should be used in an expression.");
18662         if (!Var->getType()->isReferenceType() ||
18663             !Var->isUsableInConstantExpressions(SemaRef.Context))
18664           LSI->addPotentialCapture(E->IgnoreParens());
18665       }
18666     }
18667     break;
18668   }
18669 }
18670 
18671 /// Mark a variable referenced, and check whether it is odr-used
18672 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18673 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)18674 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18675   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18676 }
18677 
18678 static void
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse,llvm::DenseMap<const VarDecl *,int> & RefsMinusAssignments)18679 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18680                    bool MightBeOdrUse,
18681                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18682   if (SemaRef.isInOpenMPDeclareTargetContext())
18683     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18684 
18685   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18686     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18687     return;
18688   }
18689 
18690   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18691 
18692   // If this is a call to a method via a cast, also mark the method in the
18693   // derived class used in case codegen can devirtualize the call.
18694   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18695   if (!ME)
18696     return;
18697   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18698   if (!MD)
18699     return;
18700   // Only attempt to devirtualize if this is truly a virtual call.
18701   bool IsVirtualCall = MD->isVirtual() &&
18702                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18703   if (!IsVirtualCall)
18704     return;
18705 
18706   // If it's possible to devirtualize the call, mark the called function
18707   // referenced.
18708   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18709       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18710   if (DM)
18711     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18712 }
18713 
18714 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18715 ///
18716 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18717 /// handled with care if the DeclRefExpr is not newly-created.
MarkDeclRefReferenced(DeclRefExpr * E,const Expr * Base)18718 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18719   // TODO: update this with DR# once a defect report is filed.
18720   // C++11 defect. The address of a pure member should not be an ODR use, even
18721   // if it's a qualified reference.
18722   bool OdrUse = true;
18723   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18724     if (Method->isVirtual() &&
18725         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18726       OdrUse = false;
18727 
18728   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18729     if (!isConstantEvaluated() && FD->isConsteval() &&
18730         !RebuildingImmediateInvocation)
18731       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18732   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18733                      RefsMinusAssignments);
18734 }
18735 
18736 /// Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)18737 void Sema::MarkMemberReferenced(MemberExpr *E) {
18738   // C++11 [basic.def.odr]p2:
18739   //   A non-overloaded function whose name appears as a potentially-evaluated
18740   //   expression or a member of a set of candidate functions, if selected by
18741   //   overload resolution when referred to from a potentially-evaluated
18742   //   expression, is odr-used, unless it is a pure virtual function and its
18743   //   name is not explicitly qualified.
18744   bool MightBeOdrUse = true;
18745   if (E->performsVirtualDispatch(getLangOpts())) {
18746     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18747       if (Method->isPure())
18748         MightBeOdrUse = false;
18749   }
18750   SourceLocation Loc =
18751       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18752   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
18753                      RefsMinusAssignments);
18754 }
18755 
18756 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
MarkFunctionParmPackReferenced(FunctionParmPackExpr * E)18757 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18758   for (VarDecl *VD : *E)
18759     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
18760                        RefsMinusAssignments);
18761 }
18762 
18763 /// Perform marking for a reference to an arbitrary declaration.  It
18764 /// marks the declaration referenced, and performs odr-use checking for
18765 /// functions and variables. This method should not be used when building a
18766 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)18767 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18768                                  bool MightBeOdrUse) {
18769   if (MightBeOdrUse) {
18770     if (auto *VD = dyn_cast<VarDecl>(D)) {
18771       MarkVariableReferenced(Loc, VD);
18772       return;
18773     }
18774   }
18775   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18776     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18777     return;
18778   }
18779   D->setReferenced();
18780 }
18781 
18782 namespace {
18783   // Mark all of the declarations used by a type as referenced.
18784   // FIXME: Not fully implemented yet! We need to have a better understanding
18785   // of when we're entering a context we should not recurse into.
18786   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18787   // TreeTransforms rebuilding the type in a new context. Rather than
18788   // duplicating the TreeTransform logic, we should consider reusing it here.
18789   // Currently that causes problems when rebuilding LambdaExprs.
18790   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18791     Sema &S;
18792     SourceLocation Loc;
18793 
18794   public:
18795     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18796 
MarkReferencedDecls(Sema & S,SourceLocation Loc)18797     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18798 
18799     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18800   };
18801 }
18802 
TraverseTemplateArgument(const TemplateArgument & Arg)18803 bool MarkReferencedDecls::TraverseTemplateArgument(
18804     const TemplateArgument &Arg) {
18805   {
18806     // A non-type template argument is a constant-evaluated context.
18807     EnterExpressionEvaluationContext Evaluated(
18808         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18809     if (Arg.getKind() == TemplateArgument::Declaration) {
18810       if (Decl *D = Arg.getAsDecl())
18811         S.MarkAnyDeclReferenced(Loc, D, true);
18812     } else if (Arg.getKind() == TemplateArgument::Expression) {
18813       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18814     }
18815   }
18816 
18817   return Inherited::TraverseTemplateArgument(Arg);
18818 }
18819 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)18820 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18821   MarkReferencedDecls Marker(*this, Loc);
18822   Marker.TraverseType(T);
18823 }
18824 
18825 namespace {
18826 /// Helper class that marks all of the declarations referenced by
18827 /// potentially-evaluated subexpressions as "referenced".
18828 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18829 public:
18830   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18831   bool SkipLocalVariables;
18832 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)18833   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18834       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18835 
visitUsedDecl(SourceLocation Loc,Decl * D)18836   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18837     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18838   }
18839 
VisitDeclRefExpr(DeclRefExpr * E)18840   void VisitDeclRefExpr(DeclRefExpr *E) {
18841     // If we were asked not to visit local variables, don't.
18842     if (SkipLocalVariables) {
18843       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18844         if (VD->hasLocalStorage())
18845           return;
18846     }
18847 
18848     // FIXME: This can trigger the instantiation of the initializer of a
18849     // variable, which can cause the expression to become value-dependent
18850     // or error-dependent. Do we need to propagate the new dependence bits?
18851     S.MarkDeclRefReferenced(E);
18852   }
18853 
VisitMemberExpr(MemberExpr * E)18854   void VisitMemberExpr(MemberExpr *E) {
18855     S.MarkMemberReferenced(E);
18856     Visit(E->getBase());
18857   }
18858 };
18859 } // namespace
18860 
18861 /// Mark any declarations that appear within this expression or any
18862 /// potentially-evaluated subexpressions as "referenced".
18863 ///
18864 /// \param SkipLocalVariables If true, don't mark local variables as
18865 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)18866 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18867                                             bool SkipLocalVariables) {
18868   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18869 }
18870 
18871 /// Emit a diagnostic that describes an effect on the run-time behavior
18872 /// of the program being compiled.
18873 ///
18874 /// This routine emits the given diagnostic when the code currently being
18875 /// type-checked is "potentially evaluated", meaning that there is a
18876 /// possibility that the code will actually be executable. Code in sizeof()
18877 /// expressions, code used only during overload resolution, etc., are not
18878 /// potentially evaluated. This routine will suppress such diagnostics or,
18879 /// in the absolutely nutty case of potentially potentially evaluated
18880 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18881 /// later.
18882 ///
18883 /// This routine should be used for all diagnostics that describe the run-time
18884 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18885 /// Failure to do so will likely result in spurious diagnostics or failures
18886 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,ArrayRef<const Stmt * > Stmts,const PartialDiagnostic & PD)18887 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18888                                const PartialDiagnostic &PD) {
18889   switch (ExprEvalContexts.back().Context) {
18890   case ExpressionEvaluationContext::Unevaluated:
18891   case ExpressionEvaluationContext::UnevaluatedList:
18892   case ExpressionEvaluationContext::UnevaluatedAbstract:
18893   case ExpressionEvaluationContext::DiscardedStatement:
18894     // The argument will never be evaluated, so don't complain.
18895     break;
18896 
18897   case ExpressionEvaluationContext::ConstantEvaluated:
18898     // Relevant diagnostics should be produced by constant evaluation.
18899     break;
18900 
18901   case ExpressionEvaluationContext::PotentiallyEvaluated:
18902   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18903     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18904       FunctionScopes.back()->PossiblyUnreachableDiags.
18905         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18906       return true;
18907     }
18908 
18909     // The initializer of a constexpr variable or of the first declaration of a
18910     // static data member is not syntactically a constant evaluated constant,
18911     // but nonetheless is always required to be a constant expression, so we
18912     // can skip diagnosing.
18913     // FIXME: Using the mangling context here is a hack.
18914     if (auto *VD = dyn_cast_or_null<VarDecl>(
18915             ExprEvalContexts.back().ManglingContextDecl)) {
18916       if (VD->isConstexpr() ||
18917           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18918         break;
18919       // FIXME: For any other kind of variable, we should build a CFG for its
18920       // initializer and check whether the context in question is reachable.
18921     }
18922 
18923     Diag(Loc, PD);
18924     return true;
18925   }
18926 
18927   return false;
18928 }
18929 
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)18930 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18931                                const PartialDiagnostic &PD) {
18932   return DiagRuntimeBehavior(
18933       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18934 }
18935 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)18936 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18937                                CallExpr *CE, FunctionDecl *FD) {
18938   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18939     return false;
18940 
18941   // If we're inside a decltype's expression, don't check for a valid return
18942   // type or construct temporaries until we know whether this is the last call.
18943   if (ExprEvalContexts.back().ExprContext ==
18944       ExpressionEvaluationContextRecord::EK_Decltype) {
18945     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18946     return false;
18947   }
18948 
18949   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18950     FunctionDecl *FD;
18951     CallExpr *CE;
18952 
18953   public:
18954     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18955       : FD(FD), CE(CE) { }
18956 
18957     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18958       if (!FD) {
18959         S.Diag(Loc, diag::err_call_incomplete_return)
18960           << T << CE->getSourceRange();
18961         return;
18962       }
18963 
18964       S.Diag(Loc, diag::err_call_function_incomplete_return)
18965           << CE->getSourceRange() << FD << T;
18966       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18967           << FD->getDeclName();
18968     }
18969   } Diagnoser(FD, CE);
18970 
18971   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18972     return true;
18973 
18974   return false;
18975 }
18976 
18977 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18978 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)18979 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18980   SourceLocation Loc;
18981 
18982   unsigned diagnostic = diag::warn_condition_is_assignment;
18983   bool IsOrAssign = false;
18984 
18985   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18986     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18987       return;
18988 
18989     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18990 
18991     // Greylist some idioms by putting them into a warning subcategory.
18992     if (ObjCMessageExpr *ME
18993           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18994       Selector Sel = ME->getSelector();
18995 
18996       // self = [<foo> init...]
18997       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18998         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18999 
19000       // <foo> = [<bar> nextObject]
19001       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19002         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19003     }
19004 
19005     Loc = Op->getOperatorLoc();
19006   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19007     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19008       return;
19009 
19010     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19011     Loc = Op->getOperatorLoc();
19012   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19013     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19014   else {
19015     // Not an assignment.
19016     return;
19017   }
19018 
19019   Diag(Loc, diagnostic) << E->getSourceRange();
19020 
19021   SourceLocation Open = E->getBeginLoc();
19022   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19023   Diag(Loc, diag::note_condition_assign_silence)
19024         << FixItHint::CreateInsertion(Open, "(")
19025         << FixItHint::CreateInsertion(Close, ")");
19026 
19027   if (IsOrAssign)
19028     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19029       << FixItHint::CreateReplacement(Loc, "!=");
19030   else
19031     Diag(Loc, diag::note_condition_assign_to_comparison)
19032       << FixItHint::CreateReplacement(Loc, "==");
19033 }
19034 
19035 /// Redundant parentheses over an equality comparison can indicate
19036 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)19037 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19038   // Don't warn if the parens came from a macro.
19039   SourceLocation parenLoc = ParenE->getBeginLoc();
19040   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19041     return;
19042   // Don't warn for dependent expressions.
19043   if (ParenE->isTypeDependent())
19044     return;
19045 
19046   Expr *E = ParenE->IgnoreParens();
19047 
19048   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19049     if (opE->getOpcode() == BO_EQ &&
19050         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19051                                                            == Expr::MLV_Valid) {
19052       SourceLocation Loc = opE->getOperatorLoc();
19053 
19054       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19055       SourceRange ParenERange = ParenE->getSourceRange();
19056       Diag(Loc, diag::note_equality_comparison_silence)
19057         << FixItHint::CreateRemoval(ParenERange.getBegin())
19058         << FixItHint::CreateRemoval(ParenERange.getEnd());
19059       Diag(Loc, diag::note_equality_comparison_to_assign)
19060         << FixItHint::CreateReplacement(Loc, "=");
19061     }
19062 }
19063 
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)19064 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19065                                        bool IsConstexpr) {
19066   DiagnoseAssignmentAsCondition(E);
19067   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19068     DiagnoseEqualityWithExtraParens(parenE);
19069 
19070   ExprResult result = CheckPlaceholderExpr(E);
19071   if (result.isInvalid()) return ExprError();
19072   E = result.get();
19073 
19074   if (!E->isTypeDependent()) {
19075     if (getLangOpts().CPlusPlus)
19076       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19077 
19078     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19079     if (ERes.isInvalid())
19080       return ExprError();
19081     E = ERes.get();
19082 
19083     QualType T = E->getType();
19084     if (!T->isScalarType()) { // C99 6.8.4.1p1
19085       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19086         << T << E->getSourceRange();
19087       return ExprError();
19088     }
19089     CheckBoolLikeConversion(E, Loc);
19090   }
19091 
19092   return E;
19093 }
19094 
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)19095 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19096                                            Expr *SubExpr, ConditionKind CK) {
19097   // Empty conditions are valid in for-statements.
19098   if (!SubExpr)
19099     return ConditionResult();
19100 
19101   ExprResult Cond;
19102   switch (CK) {
19103   case ConditionKind::Boolean:
19104     Cond = CheckBooleanCondition(Loc, SubExpr);
19105     break;
19106 
19107   case ConditionKind::ConstexprIf:
19108     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19109     break;
19110 
19111   case ConditionKind::Switch:
19112     Cond = CheckSwitchCondition(Loc, SubExpr);
19113     break;
19114   }
19115   if (Cond.isInvalid()) {
19116     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19117                               {SubExpr});
19118     if (!Cond.get())
19119       return ConditionError();
19120   }
19121   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19122   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19123   if (!FullExpr.get())
19124     return ConditionError();
19125 
19126   return ConditionResult(*this, nullptr, FullExpr,
19127                          CK == ConditionKind::ConstexprIf);
19128 }
19129 
19130 namespace {
19131   /// A visitor for rebuilding a call to an __unknown_any expression
19132   /// to have an appropriate type.
19133   struct RebuildUnknownAnyFunction
19134     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19135 
19136     Sema &S;
19137 
RebuildUnknownAnyFunction__anon446c58fa2811::RebuildUnknownAnyFunction19138     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19139 
VisitStmt__anon446c58fa2811::RebuildUnknownAnyFunction19140     ExprResult VisitStmt(Stmt *S) {
19141       llvm_unreachable("unexpected statement!");
19142     }
19143 
VisitExpr__anon446c58fa2811::RebuildUnknownAnyFunction19144     ExprResult VisitExpr(Expr *E) {
19145       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19146         << E->getSourceRange();
19147       return ExprError();
19148     }
19149 
19150     /// Rebuild an expression which simply semantically wraps another
19151     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon446c58fa2811::RebuildUnknownAnyFunction19152     template <class T> ExprResult rebuildSugarExpr(T *E) {
19153       ExprResult SubResult = Visit(E->getSubExpr());
19154       if (SubResult.isInvalid()) return ExprError();
19155 
19156       Expr *SubExpr = SubResult.get();
19157       E->setSubExpr(SubExpr);
19158       E->setType(SubExpr->getType());
19159       E->setValueKind(SubExpr->getValueKind());
19160       assert(E->getObjectKind() == OK_Ordinary);
19161       return E;
19162     }
19163 
VisitParenExpr__anon446c58fa2811::RebuildUnknownAnyFunction19164     ExprResult VisitParenExpr(ParenExpr *E) {
19165       return rebuildSugarExpr(E);
19166     }
19167 
VisitUnaryExtension__anon446c58fa2811::RebuildUnknownAnyFunction19168     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19169       return rebuildSugarExpr(E);
19170     }
19171 
VisitUnaryAddrOf__anon446c58fa2811::RebuildUnknownAnyFunction19172     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19173       ExprResult SubResult = Visit(E->getSubExpr());
19174       if (SubResult.isInvalid()) return ExprError();
19175 
19176       Expr *SubExpr = SubResult.get();
19177       E->setSubExpr(SubExpr);
19178       E->setType(S.Context.getPointerType(SubExpr->getType()));
19179       assert(E->isPRValue());
19180       assert(E->getObjectKind() == OK_Ordinary);
19181       return E;
19182     }
19183 
resolveDecl__anon446c58fa2811::RebuildUnknownAnyFunction19184     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19185       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19186 
19187       E->setType(VD->getType());
19188 
19189       assert(E->isPRValue());
19190       if (S.getLangOpts().CPlusPlus &&
19191           !(isa<CXXMethodDecl>(VD) &&
19192             cast<CXXMethodDecl>(VD)->isInstance()))
19193         E->setValueKind(VK_LValue);
19194 
19195       return E;
19196     }
19197 
VisitMemberExpr__anon446c58fa2811::RebuildUnknownAnyFunction19198     ExprResult VisitMemberExpr(MemberExpr *E) {
19199       return resolveDecl(E, E->getMemberDecl());
19200     }
19201 
VisitDeclRefExpr__anon446c58fa2811::RebuildUnknownAnyFunction19202     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19203       return resolveDecl(E, E->getDecl());
19204     }
19205   };
19206 }
19207 
19208 /// Given a function expression of unknown-any type, try to rebuild it
19209 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)19210 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19211   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19212   if (Result.isInvalid()) return ExprError();
19213   return S.DefaultFunctionArrayConversion(Result.get());
19214 }
19215 
19216 namespace {
19217   /// A visitor for rebuilding an expression of type __unknown_anytype
19218   /// into one which resolves the type directly on the referring
19219   /// expression.  Strict preservation of the original source
19220   /// structure is not a goal.
19221   struct RebuildUnknownAnyExpr
19222     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19223 
19224     Sema &S;
19225 
19226     /// The current destination type.
19227     QualType DestType;
19228 
RebuildUnknownAnyExpr__anon446c58fa2911::RebuildUnknownAnyExpr19229     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19230       : S(S), DestType(CastType) {}
19231 
VisitStmt__anon446c58fa2911::RebuildUnknownAnyExpr19232     ExprResult VisitStmt(Stmt *S) {
19233       llvm_unreachable("unexpected statement!");
19234     }
19235 
VisitExpr__anon446c58fa2911::RebuildUnknownAnyExpr19236     ExprResult VisitExpr(Expr *E) {
19237       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19238         << E->getSourceRange();
19239       return ExprError();
19240     }
19241 
19242     ExprResult VisitCallExpr(CallExpr *E);
19243     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19244 
19245     /// Rebuild an expression which simply semantically wraps another
19246     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon446c58fa2911::RebuildUnknownAnyExpr19247     template <class T> ExprResult rebuildSugarExpr(T *E) {
19248       ExprResult SubResult = Visit(E->getSubExpr());
19249       if (SubResult.isInvalid()) return ExprError();
19250       Expr *SubExpr = SubResult.get();
19251       E->setSubExpr(SubExpr);
19252       E->setType(SubExpr->getType());
19253       E->setValueKind(SubExpr->getValueKind());
19254       assert(E->getObjectKind() == OK_Ordinary);
19255       return E;
19256     }
19257 
VisitParenExpr__anon446c58fa2911::RebuildUnknownAnyExpr19258     ExprResult VisitParenExpr(ParenExpr *E) {
19259       return rebuildSugarExpr(E);
19260     }
19261 
VisitUnaryExtension__anon446c58fa2911::RebuildUnknownAnyExpr19262     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19263       return rebuildSugarExpr(E);
19264     }
19265 
VisitUnaryAddrOf__anon446c58fa2911::RebuildUnknownAnyExpr19266     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19267       const PointerType *Ptr = DestType->getAs<PointerType>();
19268       if (!Ptr) {
19269         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19270           << E->getSourceRange();
19271         return ExprError();
19272       }
19273 
19274       if (isa<CallExpr>(E->getSubExpr())) {
19275         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19276           << E->getSourceRange();
19277         return ExprError();
19278       }
19279 
19280       assert(E->isPRValue());
19281       assert(E->getObjectKind() == OK_Ordinary);
19282       E->setType(DestType);
19283 
19284       // Build the sub-expression as if it were an object of the pointee type.
19285       DestType = Ptr->getPointeeType();
19286       ExprResult SubResult = Visit(E->getSubExpr());
19287       if (SubResult.isInvalid()) return ExprError();
19288       E->setSubExpr(SubResult.get());
19289       return E;
19290     }
19291 
19292     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19293 
19294     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19295 
VisitMemberExpr__anon446c58fa2911::RebuildUnknownAnyExpr19296     ExprResult VisitMemberExpr(MemberExpr *E) {
19297       return resolveDecl(E, E->getMemberDecl());
19298     }
19299 
VisitDeclRefExpr__anon446c58fa2911::RebuildUnknownAnyExpr19300     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19301       return resolveDecl(E, E->getDecl());
19302     }
19303   };
19304 }
19305 
19306 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)19307 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19308   Expr *CalleeExpr = E->getCallee();
19309 
19310   enum FnKind {
19311     FK_MemberFunction,
19312     FK_FunctionPointer,
19313     FK_BlockPointer
19314   };
19315 
19316   FnKind Kind;
19317   QualType CalleeType = CalleeExpr->getType();
19318   if (CalleeType == S.Context.BoundMemberTy) {
19319     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19320     Kind = FK_MemberFunction;
19321     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19322   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19323     CalleeType = Ptr->getPointeeType();
19324     Kind = FK_FunctionPointer;
19325   } else {
19326     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19327     Kind = FK_BlockPointer;
19328   }
19329   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19330 
19331   // Verify that this is a legal result type of a function.
19332   if (DestType->isArrayType() || DestType->isFunctionType()) {
19333     unsigned diagID = diag::err_func_returning_array_function;
19334     if (Kind == FK_BlockPointer)
19335       diagID = diag::err_block_returning_array_function;
19336 
19337     S.Diag(E->getExprLoc(), diagID)
19338       << DestType->isFunctionType() << DestType;
19339     return ExprError();
19340   }
19341 
19342   // Otherwise, go ahead and set DestType as the call's result.
19343   E->setType(DestType.getNonLValueExprType(S.Context));
19344   E->setValueKind(Expr::getValueKindForType(DestType));
19345   assert(E->getObjectKind() == OK_Ordinary);
19346 
19347   // Rebuild the function type, replacing the result type with DestType.
19348   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19349   if (Proto) {
19350     // __unknown_anytype(...) is a special case used by the debugger when
19351     // it has no idea what a function's signature is.
19352     //
19353     // We want to build this call essentially under the K&R
19354     // unprototyped rules, but making a FunctionNoProtoType in C++
19355     // would foul up all sorts of assumptions.  However, we cannot
19356     // simply pass all arguments as variadic arguments, nor can we
19357     // portably just call the function under a non-variadic type; see
19358     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19359     // However, it turns out that in practice it is generally safe to
19360     // call a function declared as "A foo(B,C,D);" under the prototype
19361     // "A foo(B,C,D,...);".  The only known exception is with the
19362     // Windows ABI, where any variadic function is implicitly cdecl
19363     // regardless of its normal CC.  Therefore we change the parameter
19364     // types to match the types of the arguments.
19365     //
19366     // This is a hack, but it is far superior to moving the
19367     // corresponding target-specific code from IR-gen to Sema/AST.
19368 
19369     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19370     SmallVector<QualType, 8> ArgTypes;
19371     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19372       ArgTypes.reserve(E->getNumArgs());
19373       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19374         Expr *Arg = E->getArg(i);
19375         QualType ArgType = Arg->getType();
19376         if (E->isLValue()) {
19377           ArgType = S.Context.getLValueReferenceType(ArgType);
19378         } else if (E->isXValue()) {
19379           ArgType = S.Context.getRValueReferenceType(ArgType);
19380         }
19381         ArgTypes.push_back(ArgType);
19382       }
19383       ParamTypes = ArgTypes;
19384     }
19385     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19386                                          Proto->getExtProtoInfo());
19387   } else {
19388     DestType = S.Context.getFunctionNoProtoType(DestType,
19389                                                 FnType->getExtInfo());
19390   }
19391 
19392   // Rebuild the appropriate pointer-to-function type.
19393   switch (Kind) {
19394   case FK_MemberFunction:
19395     // Nothing to do.
19396     break;
19397 
19398   case FK_FunctionPointer:
19399     DestType = S.Context.getPointerType(DestType);
19400     break;
19401 
19402   case FK_BlockPointer:
19403     DestType = S.Context.getBlockPointerType(DestType);
19404     break;
19405   }
19406 
19407   // Finally, we can recurse.
19408   ExprResult CalleeResult = Visit(CalleeExpr);
19409   if (!CalleeResult.isUsable()) return ExprError();
19410   E->setCallee(CalleeResult.get());
19411 
19412   // Bind a temporary if necessary.
19413   return S.MaybeBindToTemporary(E);
19414 }
19415 
VisitObjCMessageExpr(ObjCMessageExpr * E)19416 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19417   // Verify that this is a legal result type of a call.
19418   if (DestType->isArrayType() || DestType->isFunctionType()) {
19419     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19420       << DestType->isFunctionType() << DestType;
19421     return ExprError();
19422   }
19423 
19424   // Rewrite the method result type if available.
19425   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19426     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19427     Method->setReturnType(DestType);
19428   }
19429 
19430   // Change the type of the message.
19431   E->setType(DestType.getNonReferenceType());
19432   E->setValueKind(Expr::getValueKindForType(DestType));
19433 
19434   return S.MaybeBindToTemporary(E);
19435 }
19436 
VisitImplicitCastExpr(ImplicitCastExpr * E)19437 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19438   // The only case we should ever see here is a function-to-pointer decay.
19439   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19440     assert(E->isPRValue());
19441     assert(E->getObjectKind() == OK_Ordinary);
19442 
19443     E->setType(DestType);
19444 
19445     // Rebuild the sub-expression as the pointee (function) type.
19446     DestType = DestType->castAs<PointerType>()->getPointeeType();
19447 
19448     ExprResult Result = Visit(E->getSubExpr());
19449     if (!Result.isUsable()) return ExprError();
19450 
19451     E->setSubExpr(Result.get());
19452     return E;
19453   } else if (E->getCastKind() == CK_LValueToRValue) {
19454     assert(E->isPRValue());
19455     assert(E->getObjectKind() == OK_Ordinary);
19456 
19457     assert(isa<BlockPointerType>(E->getType()));
19458 
19459     E->setType(DestType);
19460 
19461     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19462     DestType = S.Context.getLValueReferenceType(DestType);
19463 
19464     ExprResult Result = Visit(E->getSubExpr());
19465     if (!Result.isUsable()) return ExprError();
19466 
19467     E->setSubExpr(Result.get());
19468     return E;
19469   } else {
19470     llvm_unreachable("Unhandled cast type!");
19471   }
19472 }
19473 
resolveDecl(Expr * E,ValueDecl * VD)19474 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19475   ExprValueKind ValueKind = VK_LValue;
19476   QualType Type = DestType;
19477 
19478   // We know how to make this work for certain kinds of decls:
19479 
19480   //  - functions
19481   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19482     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19483       DestType = Ptr->getPointeeType();
19484       ExprResult Result = resolveDecl(E, VD);
19485       if (Result.isInvalid()) return ExprError();
19486       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19487                                  VK_PRValue);
19488     }
19489 
19490     if (!Type->isFunctionType()) {
19491       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19492         << VD << E->getSourceRange();
19493       return ExprError();
19494     }
19495     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19496       // We must match the FunctionDecl's type to the hack introduced in
19497       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19498       // type. See the lengthy commentary in that routine.
19499       QualType FDT = FD->getType();
19500       const FunctionType *FnType = FDT->castAs<FunctionType>();
19501       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19502       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19503       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19504         SourceLocation Loc = FD->getLocation();
19505         FunctionDecl *NewFD = FunctionDecl::Create(
19506             S.Context, FD->getDeclContext(), Loc, Loc,
19507             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19508             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19509             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19510 
19511         if (FD->getQualifier())
19512           NewFD->setQualifierInfo(FD->getQualifierLoc());
19513 
19514         SmallVector<ParmVarDecl*, 16> Params;
19515         for (const auto &AI : FT->param_types()) {
19516           ParmVarDecl *Param =
19517             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19518           Param->setScopeInfo(0, Params.size());
19519           Params.push_back(Param);
19520         }
19521         NewFD->setParams(Params);
19522         DRE->setDecl(NewFD);
19523         VD = DRE->getDecl();
19524       }
19525     }
19526 
19527     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19528       if (MD->isInstance()) {
19529         ValueKind = VK_PRValue;
19530         Type = S.Context.BoundMemberTy;
19531       }
19532 
19533     // Function references aren't l-values in C.
19534     if (!S.getLangOpts().CPlusPlus)
19535       ValueKind = VK_PRValue;
19536 
19537   //  - variables
19538   } else if (isa<VarDecl>(VD)) {
19539     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19540       Type = RefTy->getPointeeType();
19541     } else if (Type->isFunctionType()) {
19542       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19543         << VD << E->getSourceRange();
19544       return ExprError();
19545     }
19546 
19547   //  - nothing else
19548   } else {
19549     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19550       << VD << E->getSourceRange();
19551     return ExprError();
19552   }
19553 
19554   // Modifying the declaration like this is friendly to IR-gen but
19555   // also really dangerous.
19556   VD->setType(DestType);
19557   E->setType(Type);
19558   E->setValueKind(ValueKind);
19559   return E;
19560 }
19561 
19562 /// Check a cast of an unknown-any type.  We intentionally only
19563 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)19564 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19565                                      Expr *CastExpr, CastKind &CastKind,
19566                                      ExprValueKind &VK, CXXCastPath &Path) {
19567   // The type we're casting to must be either void or complete.
19568   if (!CastType->isVoidType() &&
19569       RequireCompleteType(TypeRange.getBegin(), CastType,
19570                           diag::err_typecheck_cast_to_incomplete))
19571     return ExprError();
19572 
19573   // Rewrite the casted expression from scratch.
19574   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19575   if (!result.isUsable()) return ExprError();
19576 
19577   CastExpr = result.get();
19578   VK = CastExpr->getValueKind();
19579   CastKind = CK_NoOp;
19580 
19581   return CastExpr;
19582 }
19583 
forceUnknownAnyToType(Expr * E,QualType ToType)19584 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19585   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19586 }
19587 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)19588 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19589                                     Expr *arg, QualType &paramType) {
19590   // If the syntactic form of the argument is not an explicit cast of
19591   // any sort, just do default argument promotion.
19592   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19593   if (!castArg) {
19594     ExprResult result = DefaultArgumentPromotion(arg);
19595     if (result.isInvalid()) return ExprError();
19596     paramType = result.get()->getType();
19597     return result;
19598   }
19599 
19600   // Otherwise, use the type that was written in the explicit cast.
19601   assert(!arg->hasPlaceholderType());
19602   paramType = castArg->getTypeAsWritten();
19603 
19604   // Copy-initialize a parameter of that type.
19605   InitializedEntity entity =
19606     InitializedEntity::InitializeParameter(Context, paramType,
19607                                            /*consumed*/ false);
19608   return PerformCopyInitialization(entity, callLoc, arg);
19609 }
19610 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)19611 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19612   Expr *orig = E;
19613   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19614   while (true) {
19615     E = E->IgnoreParenImpCasts();
19616     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19617       E = call->getCallee();
19618       diagID = diag::err_uncasted_call_of_unknown_any;
19619     } else {
19620       break;
19621     }
19622   }
19623 
19624   SourceLocation loc;
19625   NamedDecl *d;
19626   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19627     loc = ref->getLocation();
19628     d = ref->getDecl();
19629   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19630     loc = mem->getMemberLoc();
19631     d = mem->getMemberDecl();
19632   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19633     diagID = diag::err_uncasted_call_of_unknown_any;
19634     loc = msg->getSelectorStartLoc();
19635     d = msg->getMethodDecl();
19636     if (!d) {
19637       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19638         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19639         << orig->getSourceRange();
19640       return ExprError();
19641     }
19642   } else {
19643     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19644       << E->getSourceRange();
19645     return ExprError();
19646   }
19647 
19648   S.Diag(loc, diagID) << d << orig->getSourceRange();
19649 
19650   // Never recoverable.
19651   return ExprError();
19652 }
19653 
19654 /// Check for operands with placeholder types and complain if found.
19655 /// Returns ExprError() if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)19656 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19657   if (!Context.isDependenceAllowed()) {
19658     // C cannot handle TypoExpr nodes on either side of a binop because it
19659     // doesn't handle dependent types properly, so make sure any TypoExprs have
19660     // been dealt with before checking the operands.
19661     ExprResult Result = CorrectDelayedTyposInExpr(E);
19662     if (!Result.isUsable()) return ExprError();
19663     E = Result.get();
19664   }
19665 
19666   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19667   if (!placeholderType) return E;
19668 
19669   switch (placeholderType->getKind()) {
19670 
19671   // Overloaded expressions.
19672   case BuiltinType::Overload: {
19673     // Try to resolve a single function template specialization.
19674     // This is obligatory.
19675     ExprResult Result = E;
19676     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19677       return Result;
19678 
19679     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19680     // leaves Result unchanged on failure.
19681     Result = E;
19682     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19683       return Result;
19684 
19685     // If that failed, try to recover with a call.
19686     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19687                          /*complain*/ true);
19688     return Result;
19689   }
19690 
19691   // Bound member functions.
19692   case BuiltinType::BoundMember: {
19693     ExprResult result = E;
19694     const Expr *BME = E->IgnoreParens();
19695     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19696     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19697     if (isa<CXXPseudoDestructorExpr>(BME)) {
19698       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19699     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19700       if (ME->getMemberNameInfo().getName().getNameKind() ==
19701           DeclarationName::CXXDestructorName)
19702         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19703     }
19704     tryToRecoverWithCall(result, PD,
19705                          /*complain*/ true);
19706     return result;
19707   }
19708 
19709   // ARC unbridged casts.
19710   case BuiltinType::ARCUnbridgedCast: {
19711     Expr *realCast = stripARCUnbridgedCast(E);
19712     diagnoseARCUnbridgedCast(realCast);
19713     return realCast;
19714   }
19715 
19716   // Expressions of unknown type.
19717   case BuiltinType::UnknownAny:
19718     return diagnoseUnknownAnyExpr(*this, E);
19719 
19720   // Pseudo-objects.
19721   case BuiltinType::PseudoObject:
19722     return checkPseudoObjectRValue(E);
19723 
19724   case BuiltinType::BuiltinFn: {
19725     // Accept __noop without parens by implicitly converting it to a call expr.
19726     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19727     if (DRE) {
19728       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19729       if (FD->getBuiltinID() == Builtin::BI__noop) {
19730         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19731                               CK_BuiltinFnToFnPtr)
19732                 .get();
19733         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19734                                 VK_PRValue, SourceLocation(),
19735                                 FPOptionsOverride());
19736       }
19737     }
19738 
19739     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19740     return ExprError();
19741   }
19742 
19743   case BuiltinType::IncompleteMatrixIdx:
19744     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19745              ->getRowIdx()
19746              ->getBeginLoc(),
19747          diag::err_matrix_incomplete_index);
19748     return ExprError();
19749 
19750   // Expressions of unknown type.
19751   case BuiltinType::OMPArraySection:
19752     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19753     return ExprError();
19754 
19755   // Expressions of unknown type.
19756   case BuiltinType::OMPArrayShaping:
19757     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19758 
19759   case BuiltinType::OMPIterator:
19760     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19761 
19762   // Everything else should be impossible.
19763 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19764   case BuiltinType::Id:
19765 #include "clang/Basic/OpenCLImageTypes.def"
19766 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19767   case BuiltinType::Id:
19768 #include "clang/Basic/OpenCLExtensionTypes.def"
19769 #define SVE_TYPE(Name, Id, SingletonId) \
19770   case BuiltinType::Id:
19771 #include "clang/Basic/AArch64SVEACLETypes.def"
19772 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19773   case BuiltinType::Id:
19774 #include "clang/Basic/PPCTypes.def"
19775 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19776 #include "clang/Basic/RISCVVTypes.def"
19777 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19778 #define PLACEHOLDER_TYPE(Id, SingletonId)
19779 #include "clang/AST/BuiltinTypes.def"
19780     break;
19781   }
19782 
19783   llvm_unreachable("invalid placeholder type!");
19784 }
19785 
CheckCaseExpression(Expr * E)19786 bool Sema::CheckCaseExpression(Expr *E) {
19787   if (E->isTypeDependent())
19788     return true;
19789   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19790     return E->getType()->isIntegralOrEnumerationType();
19791   return false;
19792 }
19793 
19794 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19795 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)19796 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19797   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19798          "Unknown Objective-C Boolean value!");
19799   QualType BoolT = Context.ObjCBuiltinBoolTy;
19800   if (!Context.getBOOLDecl()) {
19801     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19802                         Sema::LookupOrdinaryName);
19803     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19804       NamedDecl *ND = Result.getFoundDecl();
19805       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19806         Context.setBOOLDecl(TD);
19807     }
19808   }
19809   if (Context.getBOOLDecl())
19810     BoolT = Context.getBOOLType();
19811   return new (Context)
19812       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19813 }
19814 
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,SourceLocation AtLoc,SourceLocation RParen)19815 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19816     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19817     SourceLocation RParen) {
19818   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
19819     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19820       return Spec.getPlatform() == Platform;
19821     });
19822     // Transcribe the "ios" availability check to "maccatalyst" when compiling
19823     // for "maccatalyst" if "maccatalyst" is not specified.
19824     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
19825       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19826         return Spec.getPlatform() == "ios";
19827       });
19828     }
19829     if (Spec == AvailSpecs.end())
19830       return None;
19831     return Spec->getVersion();
19832   };
19833 
19834   VersionTuple Version;
19835   if (auto MaybeVersion =
19836           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
19837     Version = *MaybeVersion;
19838 
19839   // The use of `@available` in the enclosing context should be analyzed to
19840   // warn when it's used inappropriately (i.e. not if(@available)).
19841   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
19842     Context->HasPotentialAvailabilityViolations = true;
19843 
19844   return new (Context)
19845       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19846 }
19847 
CreateRecoveryExpr(SourceLocation Begin,SourceLocation End,ArrayRef<Expr * > SubExprs,QualType T)19848 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19849                                     ArrayRef<Expr *> SubExprs, QualType T) {
19850   if (!Context.getLangOpts().RecoveryAST)
19851     return ExprError();
19852 
19853   if (isSFINAEContext())
19854     return ExprError();
19855 
19856   if (T.isNull() || T->isUndeducedType() ||
19857       !Context.getLangOpts().RecoveryASTType)
19858     // We don't know the concrete type, fallback to dependent type.
19859     T = Context.DependentTy;
19860 
19861   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19862 }
19863