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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.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/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296 
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361 
362     if (!Context.getTargetInfo().isTLSSupported())
363       if (const auto *VD = dyn_cast<VarDecl>(D))
364         if (VD->getTLSKind() != VarDecl::TLS_None)
365           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366   }
367 
368   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369       !isUnevaluatedContext()) {
370     // C++ [expr.prim.req.nested] p3
371     //   A local parameter shall only appear as an unevaluated operand
372     //   (Clause 8) within the constraint-expression.
373     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374         << D;
375     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376     return true;
377   }
378 
379   return false;
380 }
381 
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
385 /// satisfied.
386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387                                  ArrayRef<Expr *> Args) {
388   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389   if (!attr)
390     return;
391 
392   // The number of formal parameters of the declaration.
393   unsigned numFormalParams;
394 
395   // The kind of declaration.  This is also an index into a %select in
396   // the diagnostic.
397   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398 
399   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400     numFormalParams = MD->param_size();
401     calleeType = CT_Method;
402   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403     numFormalParams = FD->param_size();
404     calleeType = CT_Function;
405   } else if (isa<VarDecl>(D)) {
406     QualType type = cast<ValueDecl>(D)->getType();
407     const FunctionType *fn = nullptr;
408     if (const PointerType *ptr = type->getAs<PointerType>()) {
409       fn = ptr->getPointeeType()->getAs<FunctionType>();
410       if (!fn) return;
411       calleeType = CT_Function;
412     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413       fn = ptr->getPointeeType()->castAs<FunctionType>();
414       calleeType = CT_Block;
415     } else {
416       return;
417     }
418 
419     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420       numFormalParams = proto->getNumParams();
421     } else {
422       numFormalParams = 0;
423     }
424   } else {
425     return;
426   }
427 
428   // "nullPos" is the number of formal parameters at the end which
429   // effectively count as part of the variadic arguments.  This is
430   // useful if you would prefer to not have *any* formal parameters,
431   // but the language forces you to have at least one.
432   unsigned nullPos = attr->getNullPos();
433   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435 
436   // The number of arguments which should follow the sentinel.
437   unsigned numArgsAfterSentinel = attr->getSentinel();
438 
439   // If there aren't enough arguments for all the formal parameters,
440   // the sentinel, and the args after the sentinel, complain.
441   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444     return;
445   }
446 
447   // Otherwise, find the sentinel expression.
448   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449   if (!sentinelExpr) return;
450   if (sentinelExpr->isValueDependent()) return;
451   if (Context.isSentinelNullExpr(sentinelExpr)) return;
452 
453   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
454   // or 'NULL' if those are actually defined in the context.  Only use
455   // 'nil' for ObjC methods, where it's much more likely that the
456   // variadic arguments form a list of object pointers.
457   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458   std::string NullValue;
459   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460     NullValue = "nil";
461   else if (getLangOpts().CPlusPlus11)
462     NullValue = "nullptr";
463   else if (PP.isMacroDefined("NULL"))
464     NullValue = "NULL";
465   else
466     NullValue = "(void*) 0";
467 
468   if (MissingNilLoc.isInvalid())
469     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470   else
471     Diag(MissingNilLoc, diag::warn_missing_sentinel)
472       << int(calleeType)
473       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475 }
476 
477 SourceRange Sema::getExprRange(Expr *E) const {
478   return E ? E->getSourceRange() : SourceRange();
479 }
480 
481 //===----------------------------------------------------------------------===//
482 //  Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
484 
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487   // Handle any placeholder expressions which made it here.
488   if (E->getType()->isPlaceholderType()) {
489     ExprResult result = CheckPlaceholderExpr(E);
490     if (result.isInvalid()) return ExprError();
491     E = result.get();
492   }
493 
494   QualType Ty = E->getType();
495   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
496 
497   if (Ty->isFunctionType()) {
498     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501           return ExprError();
502 
503     E = ImpCastExprToType(E, Context.getPointerType(Ty),
504                           CK_FunctionToPointerDecay).get();
505   } else if (Ty->isArrayType()) {
506     // In C90 mode, arrays only promote to pointers if the array expression is
507     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508     // type 'array of type' is converted to an expression that has type 'pointer
509     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
510     // that has type 'array of type' ...".  The relevant change is "an lvalue"
511     // (C90) to "an expression" (C99).
512     //
513     // C++ 4.2p1:
514     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515     // T" can be converted to an rvalue of type "pointer to T".
516     //
517     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519                             CK_ArrayToPointerDecay).get();
520   }
521   return E;
522 }
523 
524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525   // Check to see if we are dereferencing a null pointer.  If so,
526   // and if not volatile-qualified, this is undefined behavior that the
527   // optimizer will delete, so warn about it.  People sometimes try to use this
528   // to get a deterministic trap and are surprised by clang's behavior.  This
529   // only handles the pattern "*null", which is a very syntactic check.
530   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531   if (UO && UO->getOpcode() == UO_Deref &&
532       UO->getSubExpr()->getType()->isPointerType()) {
533     const LangAS AS =
534         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535     if ((!isTargetAddressSpace(AS) ||
536          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539         !UO->getType().isVolatileQualified()) {
540       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541                             S.PDiag(diag::warn_indirection_through_null)
542                                 << UO->getSubExpr()->getSourceRange());
543       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544                             S.PDiag(diag::note_indirection_through_null));
545     }
546   }
547 }
548 
549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550                                     SourceLocation AssignLoc,
551                                     const Expr* RHS) {
552   const ObjCIvarDecl *IV = OIRE->getDecl();
553   if (!IV)
554     return;
555 
556   DeclarationName MemberName = IV->getDeclName();
557   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558   if (!Member || !Member->isStr("isa"))
559     return;
560 
561   const Expr *Base = OIRE->getBase();
562   QualType BaseType = Base->getType();
563   if (OIRE->isArrow())
564     BaseType = BaseType->getPointeeType();
565   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567       ObjCInterfaceDecl *ClassDeclared = nullptr;
568       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569       if (!ClassDeclared->getSuperClass()
570           && (*ClassDeclared->ivar_begin()) == IV) {
571         if (RHS) {
572           NamedDecl *ObjectSetClass =
573             S.LookupSingleName(S.TUScope,
574                                &S.Context.Idents.get("object_setClass"),
575                                SourceLocation(), S.LookupOrdinaryName);
576           if (ObjectSetClass) {
577             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580                                               "object_setClass(")
581                 << FixItHint::CreateReplacement(
582                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584           }
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587         } else {
588           NamedDecl *ObjectGetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_getClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectGetClass)
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595                                               "object_getClass(")
596                 << FixItHint::CreateReplacement(
597                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598           else
599             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600         }
601         S.Diag(IV->getLocation(), diag::note_ivar_decl);
602       }
603     }
604 }
605 
606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607   // Handle any placeholder expressions which made it here.
608   if (E->getType()->isPlaceholderType()) {
609     ExprResult result = CheckPlaceholderExpr(E);
610     if (result.isInvalid()) return ExprError();
611     E = result.get();
612   }
613 
614   // C++ [conv.lval]p1:
615   //   A glvalue of a non-function, non-array type T can be
616   //   converted to a prvalue.
617   if (!E->isGLValue()) return E;
618 
619   QualType T = E->getType();
620   assert(!T.isNull() && "r-value conversion on typeless expression?");
621 
622   // lvalue-to-rvalue conversion cannot be applied to function or array types.
623   if (T->isFunctionType() || T->isArrayType())
624     return E;
625 
626   // We don't want to throw lvalue-to-rvalue casts on top of
627   // expressions of certain types in C++.
628   if (getLangOpts().CPlusPlus &&
629       (E->getType() == Context.OverloadTy ||
630        T->isDependentType() ||
631        T->isRecordType()))
632     return E;
633 
634   // The C standard is actually really unclear on this point, and
635   // DR106 tells us what the result should be but not why.  It's
636   // generally best to say that void types just doesn't undergo
637   // lvalue-to-rvalue at all.  Note that expressions of unqualified
638   // 'void' type are never l-values, but qualified void can be.
639   if (T->isVoidType())
640     return E;
641 
642   // OpenCL usually rejects direct accesses to values of 'half' type.
643   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
644       T->isHalfType()) {
645     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646       << 0 << T;
647     return ExprError();
648   }
649 
650   CheckForNullPointerDereference(*this, E);
651   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653                                      &Context.Idents.get("object_getClass"),
654                                      SourceLocation(), LookupOrdinaryName);
655     if (ObjectGetClass)
656       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658           << FixItHint::CreateReplacement(
659                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660     else
661       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662   }
663   else if (const ObjCIvarRefExpr *OIRE =
664             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666 
667   // C++ [conv.lval]p1:
668   //   [...] If T is a non-class type, the type of the prvalue is the
669   //   cv-unqualified version of T. Otherwise, the type of the
670   //   rvalue is T.
671   //
672   // C99 6.3.2.1p2:
673   //   If the lvalue has qualified type, the value has the unqualified
674   //   version of the type of the lvalue; otherwise, the value has the
675   //   type of the lvalue.
676   if (T.hasQualifiers())
677     T = T.getUnqualifiedType();
678 
679   // Under the MS ABI, lock down the inheritance model now.
680   if (T->isMemberPointerType() &&
681       Context.getTargetInfo().getCXXABI().isMicrosoft())
682     (void)isCompleteType(E->getExprLoc(), T);
683 
684   ExprResult Res = CheckLValueToRValueConversionOperand(E);
685   if (Res.isInvalid())
686     return Res;
687   E = Res.get();
688 
689   // Loading a __weak object implicitly retains the value, so we need a cleanup to
690   // balance that.
691   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692     Cleanup.setExprNeedsCleanups(true);
693 
694   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695     Cleanup.setExprNeedsCleanups(true);
696 
697   // C++ [conv.lval]p3:
698   //   If T is cv std::nullptr_t, the result is a null pointer constant.
699   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
701 
702   // C11 6.3.2.1p2:
703   //   ... if the lvalue has atomic type, the value has the non-atomic version
704   //   of the type of the lvalue ...
705   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706     T = Atomic->getValueType().getUnqualifiedType();
707     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708                                    nullptr, VK_RValue);
709   }
710 
711   return Res;
712 }
713 
714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716   if (Res.isInvalid())
717     return ExprError();
718   Res = DefaultLvalueConversion(Res.get());
719   if (Res.isInvalid())
720     return ExprError();
721   return Res;
722 }
723 
724 /// CallExprUnaryConversions - a special case of an unary conversion
725 /// performed on a function designator of a call expression.
726 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727   QualType Ty = E->getType();
728   ExprResult Res = E;
729   // Only do implicit cast for a function type, but not for a pointer
730   // to function type.
731   if (Ty->isFunctionType()) {
732     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733                             CK_FunctionToPointerDecay);
734     if (Res.isInvalid())
735       return ExprError();
736   }
737   Res = DefaultLvalueConversion(Res.get());
738   if (Res.isInvalid())
739     return ExprError();
740   return Res.get();
741 }
742 
743 /// UsualUnaryConversions - Performs various conversions that are common to most
744 /// operators (C99 6.3). The conversions of array and function types are
745 /// sometimes suppressed. For example, the array->pointer conversion doesn't
746 /// apply if the array is an argument to the sizeof or address (&) operators.
747 /// In these instances, this routine should *not* be called.
748 ExprResult Sema::UsualUnaryConversions(Expr *E) {
749   // First, convert to an r-value.
750   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751   if (Res.isInvalid())
752     return ExprError();
753   E = Res.get();
754 
755   QualType Ty = E->getType();
756   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
757 
758   // Half FP have to be promoted to float unless it is natively supported
759   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761 
762   // Try to perform integral promotions if the object has a theoretically
763   // promotable type.
764   if (Ty->isIntegralOrUnscopedEnumerationType()) {
765     // C99 6.3.1.1p2:
766     //
767     //   The following may be used in an expression wherever an int or
768     //   unsigned int may be used:
769     //     - an object or expression with an integer type whose integer
770     //       conversion rank is less than or equal to the rank of int
771     //       and unsigned int.
772     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
773     //
774     //   If an int can represent all values of the original type, the
775     //   value is converted to an int; otherwise, it is converted to an
776     //   unsigned int. These are called the integer promotions. All
777     //   other types are unchanged by the integer promotions.
778 
779     QualType PTy = Context.isPromotableBitField(E);
780     if (!PTy.isNull()) {
781       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782       return E;
783     }
784     if (Ty->isPromotableIntegerType()) {
785       QualType PT = Context.getPromotedIntegerType(Ty);
786       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787       return E;
788     }
789   }
790   return E;
791 }
792 
793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794 /// do not have a prototype. Arguments that have type float or __fp16
795 /// are promoted to double. All other argument types are converted by
796 /// UsualUnaryConversions().
797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798   QualType Ty = E->getType();
799   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
800 
801   ExprResult Res = UsualUnaryConversions(E);
802   if (Res.isInvalid())
803     return ExprError();
804   E = Res.get();
805 
806   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
807   // promote to double.
808   // Note that default argument promotion applies only to float (and
809   // half/fp16); it does not apply to _Float16.
810   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811   if (BTy && (BTy->getKind() == BuiltinType::Half ||
812               BTy->getKind() == BuiltinType::Float)) {
813     if (getLangOpts().OpenCL &&
814         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815         if (BTy->getKind() == BuiltinType::Half) {
816             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817         }
818     } else {
819       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820     }
821   }
822 
823   // C++ performs lvalue-to-rvalue conversion as a default argument
824   // promotion, even on class types, but note:
825   //   C++11 [conv.lval]p2:
826   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
827   //     operand or a subexpression thereof the value contained in the
828   //     referenced object is not accessed. Otherwise, if the glvalue
829   //     has a class type, the conversion copy-initializes a temporary
830   //     of type T from the glvalue and the result of the conversion
831   //     is a prvalue for the temporary.
832   // FIXME: add some way to gate this entire thing for correctness in
833   // potentially potentially evaluated contexts.
834   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835     ExprResult Temp = PerformCopyInitialization(
836                        InitializedEntity::InitializeTemporary(E->getType()),
837                                                 E->getExprLoc(), E);
838     if (Temp.isInvalid())
839       return ExprError();
840     E = Temp.get();
841   }
842 
843   return E;
844 }
845 
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850   if (Ty->isIncompleteType()) {
851     // C++11 [expr.call]p7:
852     //   After these conversions, if the argument does not have arithmetic,
853     //   enumeration, pointer, pointer to member, or class type, the program
854     //   is ill-formed.
855     //
856     // Since we've already performed array-to-pointer and function-to-pointer
857     // decay, the only such type in C++ is cv void. This also handles
858     // initializer lists as variadic arguments.
859     if (Ty->isVoidType())
860       return VAK_Invalid;
861 
862     if (Ty->isObjCObjectType())
863       return VAK_Invalid;
864     return VAK_Valid;
865   }
866 
867   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868     return VAK_Invalid;
869 
870   if (Ty.isCXX98PODType(Context))
871     return VAK_Valid;
872 
873   // C++11 [expr.call]p7:
874   //   Passing a potentially-evaluated argument of class type (Clause 9)
875   //   having a non-trivial copy constructor, a non-trivial move constructor,
876   //   or a non-trivial destructor, with no corresponding parameter,
877   //   is conditionally-supported with implementation-defined semantics.
878   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880       if (!Record->hasNonTrivialCopyConstructor() &&
881           !Record->hasNonTrivialMoveConstructor() &&
882           !Record->hasNonTrivialDestructor())
883         return VAK_ValidInCXX11;
884 
885   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886     return VAK_Valid;
887 
888   if (Ty->isObjCObjectType())
889     return VAK_Invalid;
890 
891   if (getLangOpts().MSVCCompat)
892     return VAK_MSVCUndefined;
893 
894   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895   // permitted to reject them. We should consider doing so.
896   return VAK_Undefined;
897 }
898 
899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900   // Don't allow one to pass an Objective-C interface to a vararg.
901   const QualType &Ty = E->getType();
902   VarArgKind VAK = isValidVarArgType(Ty);
903 
904   // Complain about passing non-POD types through varargs.
905   switch (VAK) {
906   case VAK_ValidInCXX11:
907     DiagRuntimeBehavior(
908         E->getBeginLoc(), nullptr,
909         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910     LLVM_FALLTHROUGH;
911   case VAK_Valid:
912     if (Ty->isRecordType()) {
913       // This is unlikely to be what the user intended. If the class has a
914       // 'c_str' member function, the user probably meant to call that.
915       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916                           PDiag(diag::warn_pass_class_arg_to_vararg)
917                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
918     }
919     break;
920 
921   case VAK_Undefined:
922   case VAK_MSVCUndefined:
923     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925                             << getLangOpts().CPlusPlus11 << Ty << CT);
926     break;
927 
928   case VAK_Invalid:
929     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930       Diag(E->getBeginLoc(),
931            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932           << Ty << CT;
933     else if (Ty->isObjCObjectType())
934       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936                               << Ty << CT);
937     else
938       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939           << isa<InitListExpr>(E) << Ty << CT;
940     break;
941   }
942 }
943 
944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945 /// will create a trap if the resulting type is not a POD type.
946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947                                                   FunctionDecl *FDecl) {
948   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949     // Strip the unbridged-cast placeholder expression off, if applicable.
950     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951         (CT == VariadicMethod ||
952          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953       E = stripARCUnbridgedCast(E);
954 
955     // Otherwise, do normal placeholder checking.
956     } else {
957       ExprResult ExprRes = CheckPlaceholderExpr(E);
958       if (ExprRes.isInvalid())
959         return ExprError();
960       E = ExprRes.get();
961     }
962   }
963 
964   ExprResult ExprRes = DefaultArgumentPromotion(E);
965   if (ExprRes.isInvalid())
966     return ExprError();
967 
968   // Copy blocks to the heap.
969   if (ExprRes.get()->getType()->isBlockPointerType())
970     maybeExtendBlockObject(ExprRes);
971 
972   E = ExprRes.get();
973 
974   // Diagnostics regarding non-POD argument types are
975   // emitted along with format string checking in Sema::CheckFunctionCall().
976   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977     // Turn this into a trap.
978     CXXScopeSpec SS;
979     SourceLocation TemplateKWLoc;
980     UnqualifiedId Name;
981     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982                        E->getBeginLoc());
983     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984                                           /*HasTrailingLParen=*/true,
985                                           /*IsAddressOfOperand=*/false);
986     if (TrapFn.isInvalid())
987       return ExprError();
988 
989     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990                                     None, E->getEndLoc());
991     if (Call.isInvalid())
992       return ExprError();
993 
994     ExprResult Comma =
995         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996     if (Comma.isInvalid())
997       return ExprError();
998     return Comma.get();
999   }
1000 
1001   if (!getLangOpts().CPlusPlus &&
1002       RequireCompleteType(E->getExprLoc(), E->getType(),
1003                           diag::err_call_incomplete_argument))
1004     return ExprError();
1005 
1006   return E;
1007 }
1008 
1009 /// Converts an integer to complex float type.  Helper function of
1010 /// UsualArithmeticConversions()
1011 ///
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015                                                   ExprResult &ComplexExpr,
1016                                                   QualType IntTy,
1017                                                   QualType ComplexTy,
1018                                                   bool SkipCast) {
1019   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020   if (SkipCast) return false;
1021   if (IntTy->isIntegerType()) {
1022     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025                                   CK_FloatingRealToComplex);
1026   } else {
1027     assert(IntTy->isComplexIntegerType());
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029                                   CK_IntegralComplexToFloatingComplex);
1030   }
1031   return false;
1032 }
1033 
1034 /// Handle arithmetic conversion with complex types.  Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037                                              ExprResult &RHS, QualType LHSType,
1038                                              QualType RHSType,
1039                                              bool IsCompAssign) {
1040   // if we have an integer operand, the result is the complex type.
1041   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042                                              /*skipCast*/false))
1043     return LHSType;
1044   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045                                              /*skipCast*/IsCompAssign))
1046     return RHSType;
1047 
1048   // This handles complex/complex, complex/float, or float/complex.
1049   // When both operands are complex, the shorter operand is converted to the
1050   // type of the longer, and that is the type of the result. This corresponds
1051   // to what is done when combining two real floating-point operands.
1052   // The fun begins when size promotion occur across type domains.
1053   // From H&S 6.3.4: When one operand is complex and the other is a real
1054   // floating-point type, the less precise type is converted, within it's
1055   // real or complex domain, to the precision of the other type. For example,
1056   // when combining a "long double" with a "double _Complex", the
1057   // "double _Complex" is promoted to "long double _Complex".
1058 
1059   // Compute the rank of the two types, regardless of whether they are complex.
1060   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061 
1062   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064   QualType LHSElementType =
1065       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066   QualType RHSElementType =
1067       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068 
1069   QualType ResultType = S.Context.getComplexType(LHSElementType);
1070   if (Order < 0) {
1071     // Promote the precision of the LHS if not an assignment.
1072     ResultType = S.Context.getComplexType(RHSElementType);
1073     if (!IsCompAssign) {
1074       if (LHSComplexType)
1075         LHS =
1076             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077       else
1078         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079     }
1080   } else if (Order > 0) {
1081     // Promote the precision of the RHS.
1082     if (RHSComplexType)
1083       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084     else
1085       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086   }
1087   return ResultType;
1088 }
1089 
1090 /// Handle arithmetic conversion from integer to float.  Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093                                            ExprResult &IntExpr,
1094                                            QualType FloatTy, QualType IntTy,
1095                                            bool ConvertFloat, bool ConvertInt) {
1096   if (IntTy->isIntegerType()) {
1097     if (ConvertInt)
1098       // Convert intExpr to the lhs floating point type.
1099       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100                                     CK_IntegralToFloating);
1101     return FloatTy;
1102   }
1103 
1104   // Convert both sides to the appropriate complex float.
1105   assert(IntTy->isComplexIntegerType());
1106   QualType result = S.Context.getComplexType(FloatTy);
1107 
1108   // _Complex int -> _Complex float
1109   if (ConvertInt)
1110     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111                                   CK_IntegralComplexToFloatingComplex);
1112 
1113   // float -> _Complex float
1114   if (ConvertFloat)
1115     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116                                     CK_FloatingRealToComplex);
1117 
1118   return result;
1119 }
1120 
1121 /// Handle arithmethic conversion with floating point types.  Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124                                       ExprResult &RHS, QualType LHSType,
1125                                       QualType RHSType, bool IsCompAssign) {
1126   bool LHSFloat = LHSType->isRealFloatingType();
1127   bool RHSFloat = RHSType->isRealFloatingType();
1128 
1129   // If we have two real floating types, convert the smaller operand
1130   // to the bigger result.
1131   if (LHSFloat && RHSFloat) {
1132     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1133     if (order > 0) {
1134       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1135       return LHSType;
1136     }
1137 
1138     assert(order < 0 && "illegal float comparison");
1139     if (!IsCompAssign)
1140       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1141     return RHSType;
1142   }
1143 
1144   if (LHSFloat) {
1145     // Half FP has to be promoted to float unless it is natively supported
1146     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147       LHSType = S.Context.FloatTy;
1148 
1149     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150                                       /*ConvertFloat=*/!IsCompAssign,
1151                                       /*ConvertInt=*/ true);
1152   }
1153   assert(RHSFloat);
1154   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155                                     /*convertInt=*/ true,
1156                                     /*convertFloat=*/!IsCompAssign);
1157 }
1158 
1159 /// Diagnose attempts to convert between __float128 and long double if
1160 /// there is no support for such conversion. Helper function of
1161 /// UsualArithmeticConversions().
1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1163                                       QualType RHSType) {
1164   /*  No issue converting if at least one of the types is not a floating point
1165       type or the two types have the same rank.
1166   */
1167   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1169     return false;
1170 
1171   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1172          "The remaining types must be floating point types.");
1173 
1174   auto *LHSComplex = LHSType->getAs<ComplexType>();
1175   auto *RHSComplex = RHSType->getAs<ComplexType>();
1176 
1177   QualType LHSElemType = LHSComplex ?
1178     LHSComplex->getElementType() : LHSType;
1179   QualType RHSElemType = RHSComplex ?
1180     RHSComplex->getElementType() : RHSType;
1181 
1182   // No issue if the two types have the same representation
1183   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184       &S.Context.getFloatTypeSemantics(RHSElemType))
1185     return false;
1186 
1187   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188                                 RHSElemType == S.Context.LongDoubleTy);
1189   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190                             RHSElemType == S.Context.Float128Ty);
1191 
1192   // We've handled the situation where __float128 and long double have the same
1193   // representation. We allow all conversions for all possible long double types
1194   // except PPC's double double.
1195   return Float128AndLongDouble &&
1196     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1197      &llvm::APFloat::PPCDoubleDouble());
1198 }
1199 
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201 
1202 namespace {
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207 }
1208 
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211                              CK_IntegralComplexCast);
1212 }
1213 }
1214 
1215 /// Handle integer arithmetic conversions.  Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219                                         ExprResult &RHS, QualType LHSType,
1220                                         QualType RHSType, bool IsCompAssign) {
1221   // The rules for this case are in C99 6.3.1.8
1222   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225   if (LHSSigned == RHSSigned) {
1226     // Same signedness; use the higher-ranked type
1227     if (order >= 0) {
1228       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229       return LHSType;
1230     } else if (!IsCompAssign)
1231       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232     return RHSType;
1233   } else if (order != (LHSSigned ? 1 : -1)) {
1234     // The unsigned type has greater than or equal rank to the
1235     // signed type, so use the unsigned type
1236     if (RHSSigned) {
1237       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238       return LHSType;
1239     } else if (!IsCompAssign)
1240       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241     return RHSType;
1242   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243     // The two types are different widths; if we are here, that
1244     // means the signed type is larger than the unsigned type, so
1245     // use the signed type.
1246     if (LHSSigned) {
1247       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248       return LHSType;
1249     } else if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251     return RHSType;
1252   } else {
1253     // The signed type is higher-ranked than the unsigned type,
1254     // but isn't actually any bigger (like unsigned int and long
1255     // on most 32-bit systems).  Use the unsigned type corresponding
1256     // to the signed type.
1257     QualType result =
1258       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259     RHS = (*doRHSCast)(S, RHS.get(), result);
1260     if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), result);
1262     return result;
1263   }
1264 }
1265 
1266 /// Handle conversions with GCC complex int extension.  Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269                                            ExprResult &RHS, QualType LHSType,
1270                                            QualType RHSType,
1271                                            bool IsCompAssign) {
1272   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274 
1275   if (LHSComplexInt && RHSComplexInt) {
1276     QualType LHSEltType = LHSComplexInt->getElementType();
1277     QualType RHSEltType = RHSComplexInt->getElementType();
1278     QualType ScalarType =
1279       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281 
1282     return S.Context.getComplexType(ScalarType);
1283   }
1284 
1285   if (LHSComplexInt) {
1286     QualType LHSEltType = LHSComplexInt->getElementType();
1287     QualType ScalarType =
1288       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290     QualType ComplexType = S.Context.getComplexType(ScalarType);
1291     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292                               CK_IntegralRealToComplex);
1293 
1294     return ComplexType;
1295   }
1296 
1297   assert(RHSComplexInt);
1298 
1299   QualType RHSEltType = RHSComplexInt->getElementType();
1300   QualType ScalarType =
1301     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303   QualType ComplexType = S.Context.getComplexType(ScalarType);
1304 
1305   if (!IsCompAssign)
1306     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307                               CK_IntegralRealToComplex);
1308   return ComplexType;
1309 }
1310 
1311 /// Return the rank of a given fixed point or integer type. The value itself
1312 /// doesn't matter, but the values must be increasing with proper increasing
1313 /// rank as described in N1169 4.1.1.
1314 static unsigned GetFixedPointRank(QualType Ty) {
1315   const auto *BTy = Ty->getAs<BuiltinType>();
1316   assert(BTy && "Expected a builtin type.");
1317 
1318   switch (BTy->getKind()) {
1319   case BuiltinType::ShortFract:
1320   case BuiltinType::UShortFract:
1321   case BuiltinType::SatShortFract:
1322   case BuiltinType::SatUShortFract:
1323     return 1;
1324   case BuiltinType::Fract:
1325   case BuiltinType::UFract:
1326   case BuiltinType::SatFract:
1327   case BuiltinType::SatUFract:
1328     return 2;
1329   case BuiltinType::LongFract:
1330   case BuiltinType::ULongFract:
1331   case BuiltinType::SatLongFract:
1332   case BuiltinType::SatULongFract:
1333     return 3;
1334   case BuiltinType::ShortAccum:
1335   case BuiltinType::UShortAccum:
1336   case BuiltinType::SatShortAccum:
1337   case BuiltinType::SatUShortAccum:
1338     return 4;
1339   case BuiltinType::Accum:
1340   case BuiltinType::UAccum:
1341   case BuiltinType::SatAccum:
1342   case BuiltinType::SatUAccum:
1343     return 5;
1344   case BuiltinType::LongAccum:
1345   case BuiltinType::ULongAccum:
1346   case BuiltinType::SatLongAccum:
1347   case BuiltinType::SatULongAccum:
1348     return 6;
1349   default:
1350     if (BTy->isInteger())
1351       return 0;
1352     llvm_unreachable("Unexpected fixed point or integer type");
1353   }
1354 }
1355 
1356 /// handleFixedPointConversion - Fixed point operations between fixed
1357 /// point types and integers or other fixed point types do not fall under
1358 /// usual arithmetic conversion since these conversions could result in loss
1359 /// of precsision (N1169 4.1.4). These operations should be calculated with
1360 /// the full precision of their result type (N1169 4.1.6.2.1).
1361 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1362                                            QualType RHSTy) {
1363   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1364          "Expected at least one of the operands to be a fixed point type");
1365   assert((LHSTy->isFixedPointOrIntegerType() ||
1366           RHSTy->isFixedPointOrIntegerType()) &&
1367          "Special fixed point arithmetic operation conversions are only "
1368          "applied to ints or other fixed point types");
1369 
1370   // If one operand has signed fixed-point type and the other operand has
1371   // unsigned fixed-point type, then the unsigned fixed-point operand is
1372   // converted to its corresponding signed fixed-point type and the resulting
1373   // type is the type of the converted operand.
1374   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1375     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1376   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1377     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1378 
1379   // The result type is the type with the highest rank, whereby a fixed-point
1380   // conversion rank is always greater than an integer conversion rank; if the
1381   // type of either of the operands is a saturating fixedpoint type, the result
1382   // type shall be the saturating fixed-point type corresponding to the type
1383   // with the highest rank; the resulting value is converted (taking into
1384   // account rounding and overflow) to the precision of the resulting type.
1385   // Same ranks between signed and unsigned types are resolved earlier, so both
1386   // types are either signed or both unsigned at this point.
1387   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1388   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1389 
1390   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1391 
1392   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1393     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1394 
1395   return ResultTy;
1396 }
1397 
1398 /// Check that the usual arithmetic conversions can be performed on this pair of
1399 /// expressions that might be of enumeration type.
1400 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1401                                            SourceLocation Loc,
1402                                            Sema::ArithConvKind ACK) {
1403   // C++2a [expr.arith.conv]p1:
1404   //   If one operand is of enumeration type and the other operand is of a
1405   //   different enumeration type or a floating-point type, this behavior is
1406   //   deprecated ([depr.arith.conv.enum]).
1407   //
1408   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1409   // Eventually we will presumably reject these cases (in C++23 onwards?).
1410   QualType L = LHS->getType(), R = RHS->getType();
1411   bool LEnum = L->isUnscopedEnumerationType(),
1412        REnum = R->isUnscopedEnumerationType();
1413   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1414   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1415       (REnum && L->isFloatingType())) {
1416     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1417                     ? diag::warn_arith_conv_enum_float_cxx20
1418                     : diag::warn_arith_conv_enum_float)
1419         << LHS->getSourceRange() << RHS->getSourceRange()
1420         << (int)ACK << LEnum << L << R;
1421   } else if (!IsCompAssign && LEnum && REnum &&
1422              !S.Context.hasSameUnqualifiedType(L, R)) {
1423     unsigned DiagID;
1424     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1425         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1426       // If either enumeration type is unnamed, it's less likely that the
1427       // user cares about this, but this situation is still deprecated in
1428       // C++2a. Use a different warning group.
1429       DiagID = S.getLangOpts().CPlusPlus20
1430                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1431                     : diag::warn_arith_conv_mixed_anon_enum_types;
1432     } else if (ACK == Sema::ACK_Conditional) {
1433       // Conditional expressions are separated out because they have
1434       // historically had a different warning flag.
1435       DiagID = S.getLangOpts().CPlusPlus20
1436                    ? diag::warn_conditional_mixed_enum_types_cxx20
1437                    : diag::warn_conditional_mixed_enum_types;
1438     } else if (ACK == Sema::ACK_Comparison) {
1439       // Comparison expressions are separated out because they have
1440       // historically had a different warning flag.
1441       DiagID = S.getLangOpts().CPlusPlus20
1442                    ? diag::warn_comparison_mixed_enum_types_cxx20
1443                    : diag::warn_comparison_mixed_enum_types;
1444     } else {
1445       DiagID = S.getLangOpts().CPlusPlus20
1446                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1447                    : diag::warn_arith_conv_mixed_enum_types;
1448     }
1449     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1450                         << (int)ACK << L << R;
1451   }
1452 }
1453 
1454 /// UsualArithmeticConversions - Performs various conversions that are common to
1455 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1456 /// routine returns the first non-arithmetic type found. The client is
1457 /// responsible for emitting appropriate error diagnostics.
1458 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1459                                           SourceLocation Loc,
1460                                           ArithConvKind ACK) {
1461   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1462 
1463   if (ACK != ACK_CompAssign) {
1464     LHS = UsualUnaryConversions(LHS.get());
1465     if (LHS.isInvalid())
1466       return QualType();
1467   }
1468 
1469   RHS = UsualUnaryConversions(RHS.get());
1470   if (RHS.isInvalid())
1471     return QualType();
1472 
1473   // For conversion purposes, we ignore any qualifiers.
1474   // For example, "const float" and "float" are equivalent.
1475   QualType LHSType =
1476     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1477   QualType RHSType =
1478     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1479 
1480   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1481   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1482     LHSType = AtomicLHS->getValueType();
1483 
1484   // If both types are identical, no conversion is needed.
1485   if (LHSType == RHSType)
1486     return LHSType;
1487 
1488   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1489   // The caller can deal with this (e.g. pointer + int).
1490   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1491     return QualType();
1492 
1493   // Apply unary and bitfield promotions to the LHS's type.
1494   QualType LHSUnpromotedType = LHSType;
1495   if (LHSType->isPromotableIntegerType())
1496     LHSType = Context.getPromotedIntegerType(LHSType);
1497   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1498   if (!LHSBitfieldPromoteTy.isNull())
1499     LHSType = LHSBitfieldPromoteTy;
1500   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1501     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1502 
1503   // If both types are identical, no conversion is needed.
1504   if (LHSType == RHSType)
1505     return LHSType;
1506 
1507   // ExtInt types aren't subject to conversions between them or normal integers,
1508   // so this fails.
1509   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1510     return QualType();
1511 
1512   // At this point, we have two different arithmetic types.
1513 
1514   // Diagnose attempts to convert between __float128 and long double where
1515   // such conversions currently can't be handled.
1516   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1517     return QualType();
1518 
1519   // Handle complex types first (C99 6.3.1.8p1).
1520   if (LHSType->isComplexType() || RHSType->isComplexType())
1521     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522                                         ACK == ACK_CompAssign);
1523 
1524   // Now handle "real" floating types (i.e. float, double, long double).
1525   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1526     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527                                  ACK == ACK_CompAssign);
1528 
1529   // Handle GCC complex int extension.
1530   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1531     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1532                                       ACK == ACK_CompAssign);
1533 
1534   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1535     return handleFixedPointConversion(*this, LHSType, RHSType);
1536 
1537   // Finally, we have two differing integer types.
1538   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1539            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1540 }
1541 
1542 //===----------------------------------------------------------------------===//
1543 //  Semantic Analysis for various Expression Types
1544 //===----------------------------------------------------------------------===//
1545 
1546 
1547 ExprResult
1548 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1549                                 SourceLocation DefaultLoc,
1550                                 SourceLocation RParenLoc,
1551                                 Expr *ControllingExpr,
1552                                 ArrayRef<ParsedType> ArgTypes,
1553                                 ArrayRef<Expr *> ArgExprs) {
1554   unsigned NumAssocs = ArgTypes.size();
1555   assert(NumAssocs == ArgExprs.size());
1556 
1557   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1558   for (unsigned i = 0; i < NumAssocs; ++i) {
1559     if (ArgTypes[i])
1560       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1561     else
1562       Types[i] = nullptr;
1563   }
1564 
1565   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1566                                              ControllingExpr,
1567                                              llvm::makeArrayRef(Types, NumAssocs),
1568                                              ArgExprs);
1569   delete [] Types;
1570   return ER;
1571 }
1572 
1573 ExprResult
1574 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1575                                  SourceLocation DefaultLoc,
1576                                  SourceLocation RParenLoc,
1577                                  Expr *ControllingExpr,
1578                                  ArrayRef<TypeSourceInfo *> Types,
1579                                  ArrayRef<Expr *> Exprs) {
1580   unsigned NumAssocs = Types.size();
1581   assert(NumAssocs == Exprs.size());
1582 
1583   // Decay and strip qualifiers for the controlling expression type, and handle
1584   // placeholder type replacement. See committee discussion from WG14 DR423.
1585   {
1586     EnterExpressionEvaluationContext Unevaluated(
1587         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1588     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1589     if (R.isInvalid())
1590       return ExprError();
1591     ControllingExpr = R.get();
1592   }
1593 
1594   // The controlling expression is an unevaluated operand, so side effects are
1595   // likely unintended.
1596   if (!inTemplateInstantiation() &&
1597       ControllingExpr->HasSideEffects(Context, false))
1598     Diag(ControllingExpr->getExprLoc(),
1599          diag::warn_side_effects_unevaluated_context);
1600 
1601   bool TypeErrorFound = false,
1602        IsResultDependent = ControllingExpr->isTypeDependent(),
1603        ContainsUnexpandedParameterPack
1604          = ControllingExpr->containsUnexpandedParameterPack();
1605 
1606   for (unsigned i = 0; i < NumAssocs; ++i) {
1607     if (Exprs[i]->containsUnexpandedParameterPack())
1608       ContainsUnexpandedParameterPack = true;
1609 
1610     if (Types[i]) {
1611       if (Types[i]->getType()->containsUnexpandedParameterPack())
1612         ContainsUnexpandedParameterPack = true;
1613 
1614       if (Types[i]->getType()->isDependentType()) {
1615         IsResultDependent = true;
1616       } else {
1617         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1618         // complete object type other than a variably modified type."
1619         unsigned D = 0;
1620         if (Types[i]->getType()->isIncompleteType())
1621           D = diag::err_assoc_type_incomplete;
1622         else if (!Types[i]->getType()->isObjectType())
1623           D = diag::err_assoc_type_nonobject;
1624         else if (Types[i]->getType()->isVariablyModifiedType())
1625           D = diag::err_assoc_type_variably_modified;
1626 
1627         if (D != 0) {
1628           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1629             << Types[i]->getTypeLoc().getSourceRange()
1630             << Types[i]->getType();
1631           TypeErrorFound = true;
1632         }
1633 
1634         // C11 6.5.1.1p2 "No two generic associations in the same generic
1635         // selection shall specify compatible types."
1636         for (unsigned j = i+1; j < NumAssocs; ++j)
1637           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1638               Context.typesAreCompatible(Types[i]->getType(),
1639                                          Types[j]->getType())) {
1640             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1641                  diag::err_assoc_compatible_types)
1642               << Types[j]->getTypeLoc().getSourceRange()
1643               << Types[j]->getType()
1644               << Types[i]->getType();
1645             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1646                  diag::note_compat_assoc)
1647               << Types[i]->getTypeLoc().getSourceRange()
1648               << Types[i]->getType();
1649             TypeErrorFound = true;
1650           }
1651       }
1652     }
1653   }
1654   if (TypeErrorFound)
1655     return ExprError();
1656 
1657   // If we determined that the generic selection is result-dependent, don't
1658   // try to compute the result expression.
1659   if (IsResultDependent)
1660     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1661                                         Exprs, DefaultLoc, RParenLoc,
1662                                         ContainsUnexpandedParameterPack);
1663 
1664   SmallVector<unsigned, 1> CompatIndices;
1665   unsigned DefaultIndex = -1U;
1666   for (unsigned i = 0; i < NumAssocs; ++i) {
1667     if (!Types[i])
1668       DefaultIndex = i;
1669     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1670                                         Types[i]->getType()))
1671       CompatIndices.push_back(i);
1672   }
1673 
1674   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1675   // type compatible with at most one of the types named in its generic
1676   // association list."
1677   if (CompatIndices.size() > 1) {
1678     // We strip parens here because the controlling expression is typically
1679     // parenthesized in macro definitions.
1680     ControllingExpr = ControllingExpr->IgnoreParens();
1681     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1682         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1683         << (unsigned)CompatIndices.size();
1684     for (unsigned I : CompatIndices) {
1685       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1686            diag::note_compat_assoc)
1687         << Types[I]->getTypeLoc().getSourceRange()
1688         << Types[I]->getType();
1689     }
1690     return ExprError();
1691   }
1692 
1693   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1694   // its controlling expression shall have type compatible with exactly one of
1695   // the types named in its generic association list."
1696   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1697     // We strip parens here because the controlling expression is typically
1698     // parenthesized in macro definitions.
1699     ControllingExpr = ControllingExpr->IgnoreParens();
1700     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1701         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1702     return ExprError();
1703   }
1704 
1705   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1706   // type name that is compatible with the type of the controlling expression,
1707   // then the result expression of the generic selection is the expression
1708   // in that generic association. Otherwise, the result expression of the
1709   // generic selection is the expression in the default generic association."
1710   unsigned ResultIndex =
1711     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1712 
1713   return GenericSelectionExpr::Create(
1714       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1715       ContainsUnexpandedParameterPack, ResultIndex);
1716 }
1717 
1718 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1719 /// location of the token and the offset of the ud-suffix within it.
1720 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1721                                      unsigned Offset) {
1722   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1723                                         S.getLangOpts());
1724 }
1725 
1726 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1727 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1728 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1729                                                  IdentifierInfo *UDSuffix,
1730                                                  SourceLocation UDSuffixLoc,
1731                                                  ArrayRef<Expr*> Args,
1732                                                  SourceLocation LitEndLoc) {
1733   assert(Args.size() <= 2 && "too many arguments for literal operator");
1734 
1735   QualType ArgTy[2];
1736   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1737     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1738     if (ArgTy[ArgIdx]->isArrayType())
1739       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1740   }
1741 
1742   DeclarationName OpName =
1743     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1744   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1745   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1746 
1747   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1748   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1749                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1750                               /*AllowStringTemplate*/ false,
1751                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1752     return ExprError();
1753 
1754   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1755 }
1756 
1757 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1758 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1759 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1760 /// multiple tokens.  However, the common case is that StringToks points to one
1761 /// string.
1762 ///
1763 ExprResult
1764 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1765   assert(!StringToks.empty() && "Must have at least one string!");
1766 
1767   StringLiteralParser Literal(StringToks, PP);
1768   if (Literal.hadError)
1769     return ExprError();
1770 
1771   SmallVector<SourceLocation, 4> StringTokLocs;
1772   for (const Token &Tok : StringToks)
1773     StringTokLocs.push_back(Tok.getLocation());
1774 
1775   QualType CharTy = Context.CharTy;
1776   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1777   if (Literal.isWide()) {
1778     CharTy = Context.getWideCharType();
1779     Kind = StringLiteral::Wide;
1780   } else if (Literal.isUTF8()) {
1781     if (getLangOpts().Char8)
1782       CharTy = Context.Char8Ty;
1783     Kind = StringLiteral::UTF8;
1784   } else if (Literal.isUTF16()) {
1785     CharTy = Context.Char16Ty;
1786     Kind = StringLiteral::UTF16;
1787   } else if (Literal.isUTF32()) {
1788     CharTy = Context.Char32Ty;
1789     Kind = StringLiteral::UTF32;
1790   } else if (Literal.isPascal()) {
1791     CharTy = Context.UnsignedCharTy;
1792   }
1793 
1794   // Warn on initializing an array of char from a u8 string literal; this
1795   // becomes ill-formed in C++2a.
1796   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1797       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1798     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1799 
1800     // Create removals for all 'u8' prefixes in the string literal(s). This
1801     // ensures C++2a compatibility (but may change the program behavior when
1802     // built by non-Clang compilers for which the execution character set is
1803     // not always UTF-8).
1804     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1805     SourceLocation RemovalDiagLoc;
1806     for (const Token &Tok : StringToks) {
1807       if (Tok.getKind() == tok::utf8_string_literal) {
1808         if (RemovalDiagLoc.isInvalid())
1809           RemovalDiagLoc = Tok.getLocation();
1810         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1811             Tok.getLocation(),
1812             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1813                                            getSourceManager(), getLangOpts())));
1814       }
1815     }
1816     Diag(RemovalDiagLoc, RemovalDiag);
1817   }
1818 
1819   QualType StrTy =
1820       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1821 
1822   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1823   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1824                                              Kind, Literal.Pascal, StrTy,
1825                                              &StringTokLocs[0],
1826                                              StringTokLocs.size());
1827   if (Literal.getUDSuffix().empty())
1828     return Lit;
1829 
1830   // We're building a user-defined literal.
1831   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1832   SourceLocation UDSuffixLoc =
1833     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1834                    Literal.getUDSuffixOffset());
1835 
1836   // Make sure we're allowed user-defined literals here.
1837   if (!UDLScope)
1838     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1839 
1840   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1841   //   operator "" X (str, len)
1842   QualType SizeType = Context.getSizeType();
1843 
1844   DeclarationName OpName =
1845     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1846   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1847   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1848 
1849   QualType ArgTy[] = {
1850     Context.getArrayDecayedType(StrTy), SizeType
1851   };
1852 
1853   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1854   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1855                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1856                                 /*AllowStringTemplate*/ true,
1857                                 /*DiagnoseMissing*/ true)) {
1858 
1859   case LOLR_Cooked: {
1860     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1861     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1862                                                     StringTokLocs[0]);
1863     Expr *Args[] = { Lit, LenArg };
1864 
1865     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1866   }
1867 
1868   case LOLR_StringTemplate: {
1869     TemplateArgumentListInfo ExplicitArgs;
1870 
1871     unsigned CharBits = Context.getIntWidth(CharTy);
1872     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1873     llvm::APSInt Value(CharBits, CharIsUnsigned);
1874 
1875     TemplateArgument TypeArg(CharTy);
1876     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1877     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1878 
1879     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1880       Value = Lit->getCodeUnit(I);
1881       TemplateArgument Arg(Context, Value, CharTy);
1882       TemplateArgumentLocInfo ArgInfo;
1883       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884     }
1885     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1886                                     &ExplicitArgs);
1887   }
1888   case LOLR_Raw:
1889   case LOLR_Template:
1890   case LOLR_ErrorNoDiagnostic:
1891     llvm_unreachable("unexpected literal operator lookup result");
1892   case LOLR_Error:
1893     return ExprError();
1894   }
1895   llvm_unreachable("unexpected literal operator lookup result");
1896 }
1897 
1898 DeclRefExpr *
1899 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1900                        SourceLocation Loc,
1901                        const CXXScopeSpec *SS) {
1902   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1903   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1904 }
1905 
1906 DeclRefExpr *
1907 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1908                        const DeclarationNameInfo &NameInfo,
1909                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1910                        SourceLocation TemplateKWLoc,
1911                        const TemplateArgumentListInfo *TemplateArgs) {
1912   NestedNameSpecifierLoc NNS =
1913       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1914   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1915                           TemplateArgs);
1916 }
1917 
1918 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1919   // A declaration named in an unevaluated operand never constitutes an odr-use.
1920   if (isUnevaluatedContext())
1921     return NOUR_Unevaluated;
1922 
1923   // C++2a [basic.def.odr]p4:
1924   //   A variable x whose name appears as a potentially-evaluated expression e
1925   //   is odr-used by e unless [...] x is a reference that is usable in
1926   //   constant expressions.
1927   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1928     if (VD->getType()->isReferenceType() &&
1929         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1930         VD->isUsableInConstantExpressions(Context))
1931       return NOUR_Constant;
1932   }
1933 
1934   // All remaining non-variable cases constitute an odr-use. For variables, we
1935   // need to wait and see how the expression is used.
1936   return NOUR_None;
1937 }
1938 
1939 /// BuildDeclRefExpr - Build an expression that references a
1940 /// declaration that does not require a closure capture.
1941 DeclRefExpr *
1942 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943                        const DeclarationNameInfo &NameInfo,
1944                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1945                        SourceLocation TemplateKWLoc,
1946                        const TemplateArgumentListInfo *TemplateArgs) {
1947   bool RefersToCapturedVariable =
1948       isa<VarDecl>(D) &&
1949       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1950 
1951   DeclRefExpr *E = DeclRefExpr::Create(
1952       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1953       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1954   MarkDeclRefReferenced(E);
1955 
1956   // C++ [except.spec]p17:
1957   //   An exception-specification is considered to be needed when:
1958   //   - in an expression, the function is the unique lookup result or
1959   //     the selected member of a set of overloaded functions.
1960   //
1961   // We delay doing this until after we've built the function reference and
1962   // marked it as used so that:
1963   //  a) if the function is defaulted, we get errors from defining it before /
1964   //     instead of errors from computing its exception specification, and
1965   //  b) if the function is a defaulted comparison, we can use the body we
1966   //     build when defining it as input to the exception specification
1967   //     computation rather than computing a new body.
1968   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1969     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1970       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1971         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1972     }
1973   }
1974 
1975   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1976       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1977       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1978     getCurFunction()->recordUseOfWeak(E);
1979 
1980   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1981   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1982     FD = IFD->getAnonField();
1983   if (FD) {
1984     UnusedPrivateFields.remove(FD);
1985     // Just in case we're building an illegal pointer-to-member.
1986     if (FD->isBitField())
1987       E->setObjectKind(OK_BitField);
1988   }
1989 
1990   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1991   // designates a bit-field.
1992   if (auto *BD = dyn_cast<BindingDecl>(D))
1993     if (auto *BE = BD->getBinding())
1994       E->setObjectKind(BE->getObjectKind());
1995 
1996   return E;
1997 }
1998 
1999 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2000 /// possibly a list of template arguments.
2001 ///
2002 /// If this produces template arguments, it is permitted to call
2003 /// DecomposeTemplateName.
2004 ///
2005 /// This actually loses a lot of source location information for
2006 /// non-standard name kinds; we should consider preserving that in
2007 /// some way.
2008 void
2009 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2010                              TemplateArgumentListInfo &Buffer,
2011                              DeclarationNameInfo &NameInfo,
2012                              const TemplateArgumentListInfo *&TemplateArgs) {
2013   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2014     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2015     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2016 
2017     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2018                                        Id.TemplateId->NumArgs);
2019     translateTemplateArguments(TemplateArgsPtr, Buffer);
2020 
2021     TemplateName TName = Id.TemplateId->Template.get();
2022     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2023     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2024     TemplateArgs = &Buffer;
2025   } else {
2026     NameInfo = GetNameFromUnqualifiedId(Id);
2027     TemplateArgs = nullptr;
2028   }
2029 }
2030 
2031 static void emitEmptyLookupTypoDiagnostic(
2032     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2033     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2034     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2035   DeclContext *Ctx =
2036       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2037   if (!TC) {
2038     // Emit a special diagnostic for failed member lookups.
2039     // FIXME: computing the declaration context might fail here (?)
2040     if (Ctx)
2041       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2042                                                  << SS.getRange();
2043     else
2044       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2045     return;
2046   }
2047 
2048   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2049   bool DroppedSpecifier =
2050       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2051   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2052                         ? diag::note_implicit_param_decl
2053                         : diag::note_previous_decl;
2054   if (!Ctx)
2055     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2056                          SemaRef.PDiag(NoteID));
2057   else
2058     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2059                                  << Typo << Ctx << DroppedSpecifier
2060                                  << SS.getRange(),
2061                          SemaRef.PDiag(NoteID));
2062 }
2063 
2064 /// Diagnose an empty lookup.
2065 ///
2066 /// \return false if new lookup candidates were found
2067 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2068                                CorrectionCandidateCallback &CCC,
2069                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2070                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2071   DeclarationName Name = R.getLookupName();
2072 
2073   unsigned diagnostic = diag::err_undeclared_var_use;
2074   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2075   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2076       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2077       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2078     diagnostic = diag::err_undeclared_use;
2079     diagnostic_suggest = diag::err_undeclared_use_suggest;
2080   }
2081 
2082   // If the original lookup was an unqualified lookup, fake an
2083   // unqualified lookup.  This is useful when (for example) the
2084   // original lookup would not have found something because it was a
2085   // dependent name.
2086   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2087   while (DC) {
2088     if (isa<CXXRecordDecl>(DC)) {
2089       LookupQualifiedName(R, DC);
2090 
2091       if (!R.empty()) {
2092         // Don't give errors about ambiguities in this lookup.
2093         R.suppressDiagnostics();
2094 
2095         // During a default argument instantiation the CurContext points
2096         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2097         // function parameter list, hence add an explicit check.
2098         bool isDefaultArgument =
2099             !CodeSynthesisContexts.empty() &&
2100             CodeSynthesisContexts.back().Kind ==
2101                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2102         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2103         bool isInstance = CurMethod &&
2104                           CurMethod->isInstance() &&
2105                           DC == CurMethod->getParent() && !isDefaultArgument;
2106 
2107         // Give a code modification hint to insert 'this->'.
2108         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2109         // Actually quite difficult!
2110         if (getLangOpts().MSVCCompat)
2111           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2112         if (isInstance) {
2113           Diag(R.getNameLoc(), diagnostic) << Name
2114             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2115           CheckCXXThisCapture(R.getNameLoc());
2116         } else {
2117           Diag(R.getNameLoc(), diagnostic) << Name;
2118         }
2119 
2120         // Do we really want to note all of these?
2121         for (NamedDecl *D : R)
2122           Diag(D->getLocation(), diag::note_dependent_var_use);
2123 
2124         // Return true if we are inside a default argument instantiation
2125         // and the found name refers to an instance member function, otherwise
2126         // the function calling DiagnoseEmptyLookup will try to create an
2127         // implicit member call and this is wrong for default argument.
2128         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2129           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2130           return true;
2131         }
2132 
2133         // Tell the callee to try to recover.
2134         return false;
2135       }
2136 
2137       R.clear();
2138     }
2139 
2140     DC = DC->getLookupParent();
2141   }
2142 
2143   // We didn't find anything, so try to correct for a typo.
2144   TypoCorrection Corrected;
2145   if (S && Out) {
2146     SourceLocation TypoLoc = R.getNameLoc();
2147     assert(!ExplicitTemplateArgs &&
2148            "Diagnosing an empty lookup with explicit template args!");
2149     *Out = CorrectTypoDelayed(
2150         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2151         [=](const TypoCorrection &TC) {
2152           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2153                                         diagnostic, diagnostic_suggest);
2154         },
2155         nullptr, CTK_ErrorRecovery);
2156     if (*Out)
2157       return true;
2158   } else if (S &&
2159              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2160                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2161     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2162     bool DroppedSpecifier =
2163         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2164     R.setLookupName(Corrected.getCorrection());
2165 
2166     bool AcceptableWithRecovery = false;
2167     bool AcceptableWithoutRecovery = false;
2168     NamedDecl *ND = Corrected.getFoundDecl();
2169     if (ND) {
2170       if (Corrected.isOverloaded()) {
2171         OverloadCandidateSet OCS(R.getNameLoc(),
2172                                  OverloadCandidateSet::CSK_Normal);
2173         OverloadCandidateSet::iterator Best;
2174         for (NamedDecl *CD : Corrected) {
2175           if (FunctionTemplateDecl *FTD =
2176                    dyn_cast<FunctionTemplateDecl>(CD))
2177             AddTemplateOverloadCandidate(
2178                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2179                 Args, OCS);
2180           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2181             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2182               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2183                                    Args, OCS);
2184         }
2185         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2186         case OR_Success:
2187           ND = Best->FoundDecl;
2188           Corrected.setCorrectionDecl(ND);
2189           break;
2190         default:
2191           // FIXME: Arbitrarily pick the first declaration for the note.
2192           Corrected.setCorrectionDecl(ND);
2193           break;
2194         }
2195       }
2196       R.addDecl(ND);
2197       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2198         CXXRecordDecl *Record = nullptr;
2199         if (Corrected.getCorrectionSpecifier()) {
2200           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2201           Record = Ty->getAsCXXRecordDecl();
2202         }
2203         if (!Record)
2204           Record = cast<CXXRecordDecl>(
2205               ND->getDeclContext()->getRedeclContext());
2206         R.setNamingClass(Record);
2207       }
2208 
2209       auto *UnderlyingND = ND->getUnderlyingDecl();
2210       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2211                                isa<FunctionTemplateDecl>(UnderlyingND);
2212       // FIXME: If we ended up with a typo for a type name or
2213       // Objective-C class name, we're in trouble because the parser
2214       // is in the wrong place to recover. Suggest the typo
2215       // correction, but don't make it a fix-it since we're not going
2216       // to recover well anyway.
2217       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2218                                   getAsTypeTemplateDecl(UnderlyingND) ||
2219                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2220     } else {
2221       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2222       // because we aren't able to recover.
2223       AcceptableWithoutRecovery = true;
2224     }
2225 
2226     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2227       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2228                             ? diag::note_implicit_param_decl
2229                             : diag::note_previous_decl;
2230       if (SS.isEmpty())
2231         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2232                      PDiag(NoteID), AcceptableWithRecovery);
2233       else
2234         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2235                                   << Name << computeDeclContext(SS, false)
2236                                   << DroppedSpecifier << SS.getRange(),
2237                      PDiag(NoteID), AcceptableWithRecovery);
2238 
2239       // Tell the callee whether to try to recover.
2240       return !AcceptableWithRecovery;
2241     }
2242   }
2243   R.clear();
2244 
2245   // Emit a special diagnostic for failed member lookups.
2246   // FIXME: computing the declaration context might fail here (?)
2247   if (!SS.isEmpty()) {
2248     Diag(R.getNameLoc(), diag::err_no_member)
2249       << Name << computeDeclContext(SS, false)
2250       << SS.getRange();
2251     return true;
2252   }
2253 
2254   // Give up, we can't recover.
2255   Diag(R.getNameLoc(), diagnostic) << Name;
2256   return true;
2257 }
2258 
2259 /// In Microsoft mode, if we are inside a template class whose parent class has
2260 /// dependent base classes, and we can't resolve an unqualified identifier, then
2261 /// assume the identifier is a member of a dependent base class.  We can only
2262 /// recover successfully in static methods, instance methods, and other contexts
2263 /// where 'this' is available.  This doesn't precisely match MSVC's
2264 /// instantiation model, but it's close enough.
2265 static Expr *
2266 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2267                                DeclarationNameInfo &NameInfo,
2268                                SourceLocation TemplateKWLoc,
2269                                const TemplateArgumentListInfo *TemplateArgs) {
2270   // Only try to recover from lookup into dependent bases in static methods or
2271   // contexts where 'this' is available.
2272   QualType ThisType = S.getCurrentThisType();
2273   const CXXRecordDecl *RD = nullptr;
2274   if (!ThisType.isNull())
2275     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2276   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2277     RD = MD->getParent();
2278   if (!RD || !RD->hasAnyDependentBases())
2279     return nullptr;
2280 
2281   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2282   // is available, suggest inserting 'this->' as a fixit.
2283   SourceLocation Loc = NameInfo.getLoc();
2284   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2285   DB << NameInfo.getName() << RD;
2286 
2287   if (!ThisType.isNull()) {
2288     DB << FixItHint::CreateInsertion(Loc, "this->");
2289     return CXXDependentScopeMemberExpr::Create(
2290         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2291         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2292         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2293   }
2294 
2295   // Synthesize a fake NNS that points to the derived class.  This will
2296   // perform name lookup during template instantiation.
2297   CXXScopeSpec SS;
2298   auto *NNS =
2299       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2300   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2301   return DependentScopeDeclRefExpr::Create(
2302       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2303       TemplateArgs);
2304 }
2305 
2306 ExprResult
2307 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2308                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2309                         bool HasTrailingLParen, bool IsAddressOfOperand,
2310                         CorrectionCandidateCallback *CCC,
2311                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2312   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2313          "cannot be direct & operand and have a trailing lparen");
2314   if (SS.isInvalid())
2315     return ExprError();
2316 
2317   TemplateArgumentListInfo TemplateArgsBuffer;
2318 
2319   // Decompose the UnqualifiedId into the following data.
2320   DeclarationNameInfo NameInfo;
2321   const TemplateArgumentListInfo *TemplateArgs;
2322   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2323 
2324   DeclarationName Name = NameInfo.getName();
2325   IdentifierInfo *II = Name.getAsIdentifierInfo();
2326   SourceLocation NameLoc = NameInfo.getLoc();
2327 
2328   if (II && II->isEditorPlaceholder()) {
2329     // FIXME: When typed placeholders are supported we can create a typed
2330     // placeholder expression node.
2331     return ExprError();
2332   }
2333 
2334   // C++ [temp.dep.expr]p3:
2335   //   An id-expression is type-dependent if it contains:
2336   //     -- an identifier that was declared with a dependent type,
2337   //        (note: handled after lookup)
2338   //     -- a template-id that is dependent,
2339   //        (note: handled in BuildTemplateIdExpr)
2340   //     -- a conversion-function-id that specifies a dependent type,
2341   //     -- a nested-name-specifier that contains a class-name that
2342   //        names a dependent type.
2343   // Determine whether this is a member of an unknown specialization;
2344   // we need to handle these differently.
2345   bool DependentID = false;
2346   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2347       Name.getCXXNameType()->isDependentType()) {
2348     DependentID = true;
2349   } else if (SS.isSet()) {
2350     if (DeclContext *DC = computeDeclContext(SS, false)) {
2351       if (RequireCompleteDeclContext(SS, DC))
2352         return ExprError();
2353     } else {
2354       DependentID = true;
2355     }
2356   }
2357 
2358   if (DependentID)
2359     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360                                       IsAddressOfOperand, TemplateArgs);
2361 
2362   // Perform the required lookup.
2363   LookupResult R(*this, NameInfo,
2364                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2365                      ? LookupObjCImplicitSelfParam
2366                      : LookupOrdinaryName);
2367   if (TemplateKWLoc.isValid() || TemplateArgs) {
2368     // Lookup the template name again to correctly establish the context in
2369     // which it was found. This is really unfortunate as we already did the
2370     // lookup to determine that it was a template name in the first place. If
2371     // this becomes a performance hit, we can work harder to preserve those
2372     // results until we get here but it's likely not worth it.
2373     bool MemberOfUnknownSpecialization;
2374     AssumedTemplateKind AssumedTemplate;
2375     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2376                            MemberOfUnknownSpecialization, TemplateKWLoc,
2377                            &AssumedTemplate))
2378       return ExprError();
2379 
2380     if (MemberOfUnknownSpecialization ||
2381         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2382       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2383                                         IsAddressOfOperand, TemplateArgs);
2384   } else {
2385     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2386     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2387 
2388     // If the result might be in a dependent base class, this is a dependent
2389     // id-expression.
2390     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2391       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2392                                         IsAddressOfOperand, TemplateArgs);
2393 
2394     // If this reference is in an Objective-C method, then we need to do
2395     // some special Objective-C lookup, too.
2396     if (IvarLookupFollowUp) {
2397       ExprResult E(LookupInObjCMethod(R, S, II, true));
2398       if (E.isInvalid())
2399         return ExprError();
2400 
2401       if (Expr *Ex = E.getAs<Expr>())
2402         return Ex;
2403     }
2404   }
2405 
2406   if (R.isAmbiguous())
2407     return ExprError();
2408 
2409   // This could be an implicitly declared function reference (legal in C90,
2410   // extension in C99, forbidden in C++).
2411   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2412     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2413     if (D) R.addDecl(D);
2414   }
2415 
2416   // Determine whether this name might be a candidate for
2417   // argument-dependent lookup.
2418   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2419 
2420   if (R.empty() && !ADL) {
2421     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2422       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2423                                                    TemplateKWLoc, TemplateArgs))
2424         return E;
2425     }
2426 
2427     // Don't diagnose an empty lookup for inline assembly.
2428     if (IsInlineAsmIdentifier)
2429       return ExprError();
2430 
2431     // If this name wasn't predeclared and if this is not a function
2432     // call, diagnose the problem.
2433     TypoExpr *TE = nullptr;
2434     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2435                                                        : nullptr);
2436     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2437     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2438            "Typo correction callback misconfigured");
2439     if (CCC) {
2440       // Make sure the callback knows what the typo being diagnosed is.
2441       CCC->setTypoName(II);
2442       if (SS.isValid())
2443         CCC->setTypoNNS(SS.getScopeRep());
2444     }
2445     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2446     // a template name, but we happen to have always already looked up the name
2447     // before we get here if it must be a template name.
2448     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2449                             None, &TE)) {
2450       if (TE && KeywordReplacement) {
2451         auto &State = getTypoExprState(TE);
2452         auto BestTC = State.Consumer->getNextCorrection();
2453         if (BestTC.isKeyword()) {
2454           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2455           if (State.DiagHandler)
2456             State.DiagHandler(BestTC);
2457           KeywordReplacement->startToken();
2458           KeywordReplacement->setKind(II->getTokenID());
2459           KeywordReplacement->setIdentifierInfo(II);
2460           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2461           // Clean up the state associated with the TypoExpr, since it has
2462           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2463           clearDelayedTypo(TE);
2464           // Signal that a correction to a keyword was performed by returning a
2465           // valid-but-null ExprResult.
2466           return (Expr*)nullptr;
2467         }
2468         State.Consumer->resetCorrectionStream();
2469       }
2470       return TE ? TE : ExprError();
2471     }
2472 
2473     assert(!R.empty() &&
2474            "DiagnoseEmptyLookup returned false but added no results");
2475 
2476     // If we found an Objective-C instance variable, let
2477     // LookupInObjCMethod build the appropriate expression to
2478     // reference the ivar.
2479     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2480       R.clear();
2481       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2482       // In a hopelessly buggy code, Objective-C instance variable
2483       // lookup fails and no expression will be built to reference it.
2484       if (!E.isInvalid() && !E.get())
2485         return ExprError();
2486       return E;
2487     }
2488   }
2489 
2490   // This is guaranteed from this point on.
2491   assert(!R.empty() || ADL);
2492 
2493   // Check whether this might be a C++ implicit instance member access.
2494   // C++ [class.mfct.non-static]p3:
2495   //   When an id-expression that is not part of a class member access
2496   //   syntax and not used to form a pointer to member is used in the
2497   //   body of a non-static member function of class X, if name lookup
2498   //   resolves the name in the id-expression to a non-static non-type
2499   //   member of some class C, the id-expression is transformed into a
2500   //   class member access expression using (*this) as the
2501   //   postfix-expression to the left of the . operator.
2502   //
2503   // But we don't actually need to do this for '&' operands if R
2504   // resolved to a function or overloaded function set, because the
2505   // expression is ill-formed if it actually works out to be a
2506   // non-static member function:
2507   //
2508   // C++ [expr.ref]p4:
2509   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2510   //   [t]he expression can be used only as the left-hand operand of a
2511   //   member function call.
2512   //
2513   // There are other safeguards against such uses, but it's important
2514   // to get this right here so that we don't end up making a
2515   // spuriously dependent expression if we're inside a dependent
2516   // instance method.
2517   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2518     bool MightBeImplicitMember;
2519     if (!IsAddressOfOperand)
2520       MightBeImplicitMember = true;
2521     else if (!SS.isEmpty())
2522       MightBeImplicitMember = false;
2523     else if (R.isOverloadedResult())
2524       MightBeImplicitMember = false;
2525     else if (R.isUnresolvableResult())
2526       MightBeImplicitMember = true;
2527     else
2528       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2529                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2530                               isa<MSPropertyDecl>(R.getFoundDecl());
2531 
2532     if (MightBeImplicitMember)
2533       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2534                                              R, TemplateArgs, S);
2535   }
2536 
2537   if (TemplateArgs || TemplateKWLoc.isValid()) {
2538 
2539     // In C++1y, if this is a variable template id, then check it
2540     // in BuildTemplateIdExpr().
2541     // The single lookup result must be a variable template declaration.
2542     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2543         Id.TemplateId->Kind == TNK_Var_template) {
2544       assert(R.getAsSingle<VarTemplateDecl>() &&
2545              "There should only be one declaration found.");
2546     }
2547 
2548     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2549   }
2550 
2551   return BuildDeclarationNameExpr(SS, R, ADL);
2552 }
2553 
2554 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2555 /// declaration name, generally during template instantiation.
2556 /// There's a large number of things which don't need to be done along
2557 /// this path.
2558 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2559     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2560     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2561   DeclContext *DC = computeDeclContext(SS, false);
2562   if (!DC)
2563     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2564                                      NameInfo, /*TemplateArgs=*/nullptr);
2565 
2566   if (RequireCompleteDeclContext(SS, DC))
2567     return ExprError();
2568 
2569   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2570   LookupQualifiedName(R, DC);
2571 
2572   if (R.isAmbiguous())
2573     return ExprError();
2574 
2575   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2576     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2577                                      NameInfo, /*TemplateArgs=*/nullptr);
2578 
2579   if (R.empty()) {
2580     Diag(NameInfo.getLoc(), diag::err_no_member)
2581       << NameInfo.getName() << DC << SS.getRange();
2582     return ExprError();
2583   }
2584 
2585   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2586     // Diagnose a missing typename if this resolved unambiguously to a type in
2587     // a dependent context.  If we can recover with a type, downgrade this to
2588     // a warning in Microsoft compatibility mode.
2589     unsigned DiagID = diag::err_typename_missing;
2590     if (RecoveryTSI && getLangOpts().MSVCCompat)
2591       DiagID = diag::ext_typename_missing;
2592     SourceLocation Loc = SS.getBeginLoc();
2593     auto D = Diag(Loc, DiagID);
2594     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2595       << SourceRange(Loc, NameInfo.getEndLoc());
2596 
2597     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2598     // context.
2599     if (!RecoveryTSI)
2600       return ExprError();
2601 
2602     // Only issue the fixit if we're prepared to recover.
2603     D << FixItHint::CreateInsertion(Loc, "typename ");
2604 
2605     // Recover by pretending this was an elaborated type.
2606     QualType Ty = Context.getTypeDeclType(TD);
2607     TypeLocBuilder TLB;
2608     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2609 
2610     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2611     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2612     QTL.setElaboratedKeywordLoc(SourceLocation());
2613     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2614 
2615     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2616 
2617     return ExprEmpty();
2618   }
2619 
2620   // Defend against this resolving to an implicit member access. We usually
2621   // won't get here if this might be a legitimate a class member (we end up in
2622   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2623   // a pointer-to-member or in an unevaluated context in C++11.
2624   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2625     return BuildPossibleImplicitMemberExpr(SS,
2626                                            /*TemplateKWLoc=*/SourceLocation(),
2627                                            R, /*TemplateArgs=*/nullptr, S);
2628 
2629   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2630 }
2631 
2632 /// The parser has read a name in, and Sema has detected that we're currently
2633 /// inside an ObjC method. Perform some additional checks and determine if we
2634 /// should form a reference to an ivar.
2635 ///
2636 /// Ideally, most of this would be done by lookup, but there's
2637 /// actually quite a lot of extra work involved.
2638 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2639                                         IdentifierInfo *II) {
2640   SourceLocation Loc = Lookup.getNameLoc();
2641   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2642 
2643   // Check for error condition which is already reported.
2644   if (!CurMethod)
2645     return DeclResult(true);
2646 
2647   // There are two cases to handle here.  1) scoped lookup could have failed,
2648   // in which case we should look for an ivar.  2) scoped lookup could have
2649   // found a decl, but that decl is outside the current instance method (i.e.
2650   // a global variable).  In these two cases, we do a lookup for an ivar with
2651   // this name, if the lookup sucedes, we replace it our current decl.
2652 
2653   // If we're in a class method, we don't normally want to look for
2654   // ivars.  But if we don't find anything else, and there's an
2655   // ivar, that's an error.
2656   bool IsClassMethod = CurMethod->isClassMethod();
2657 
2658   bool LookForIvars;
2659   if (Lookup.empty())
2660     LookForIvars = true;
2661   else if (IsClassMethod)
2662     LookForIvars = false;
2663   else
2664     LookForIvars = (Lookup.isSingleResult() &&
2665                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2666   ObjCInterfaceDecl *IFace = nullptr;
2667   if (LookForIvars) {
2668     IFace = CurMethod->getClassInterface();
2669     ObjCInterfaceDecl *ClassDeclared;
2670     ObjCIvarDecl *IV = nullptr;
2671     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2672       // Diagnose using an ivar in a class method.
2673       if (IsClassMethod) {
2674         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675         return DeclResult(true);
2676       }
2677 
2678       // Diagnose the use of an ivar outside of the declaring class.
2679       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2680           !declaresSameEntity(ClassDeclared, IFace) &&
2681           !getLangOpts().DebuggerSupport)
2682         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2683 
2684       // Success.
2685       return IV;
2686     }
2687   } else if (CurMethod->isInstanceMethod()) {
2688     // We should warn if a local variable hides an ivar.
2689     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2690       ObjCInterfaceDecl *ClassDeclared;
2691       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2692         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2693             declaresSameEntity(IFace, ClassDeclared))
2694           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2695       }
2696     }
2697   } else if (Lookup.isSingleResult() &&
2698              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2699     // If accessing a stand-alone ivar in a class method, this is an error.
2700     if (const ObjCIvarDecl *IV =
2701             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2702       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2703       return DeclResult(true);
2704     }
2705   }
2706 
2707   // Didn't encounter an error, didn't find an ivar.
2708   return DeclResult(false);
2709 }
2710 
2711 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2712                                   ObjCIvarDecl *IV) {
2713   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2714   assert(CurMethod && CurMethod->isInstanceMethod() &&
2715          "should not reference ivar from this context");
2716 
2717   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2718   assert(IFace && "should not reference ivar from this context");
2719 
2720   // If we're referencing an invalid decl, just return this as a silent
2721   // error node.  The error diagnostic was already emitted on the decl.
2722   if (IV->isInvalidDecl())
2723     return ExprError();
2724 
2725   // Check if referencing a field with __attribute__((deprecated)).
2726   if (DiagnoseUseOfDecl(IV, Loc))
2727     return ExprError();
2728 
2729   // FIXME: This should use a new expr for a direct reference, don't
2730   // turn this into Self->ivar, just return a BareIVarExpr or something.
2731   IdentifierInfo &II = Context.Idents.get("self");
2732   UnqualifiedId SelfName;
2733   SelfName.setIdentifier(&II, SourceLocation());
2734   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2735   CXXScopeSpec SelfScopeSpec;
2736   SourceLocation TemplateKWLoc;
2737   ExprResult SelfExpr =
2738       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2739                         /*HasTrailingLParen=*/false,
2740                         /*IsAddressOfOperand=*/false);
2741   if (SelfExpr.isInvalid())
2742     return ExprError();
2743 
2744   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2745   if (SelfExpr.isInvalid())
2746     return ExprError();
2747 
2748   MarkAnyDeclReferenced(Loc, IV, true);
2749 
2750   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2751   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2752       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2753     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2754 
2755   ObjCIvarRefExpr *Result = new (Context)
2756       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2757                       IV->getLocation(), SelfExpr.get(), true, true);
2758 
2759   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2760     if (!isUnevaluatedContext() &&
2761         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2762       getCurFunction()->recordUseOfWeak(Result);
2763   }
2764   if (getLangOpts().ObjCAutoRefCount)
2765     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2766       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2767 
2768   return Result;
2769 }
2770 
2771 /// The parser has read a name in, and Sema has detected that we're currently
2772 /// inside an ObjC method. Perform some additional checks and determine if we
2773 /// should form a reference to an ivar. If so, build an expression referencing
2774 /// that ivar.
2775 ExprResult
2776 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2777                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2778   // FIXME: Integrate this lookup step into LookupParsedName.
2779   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2780   if (Ivar.isInvalid())
2781     return ExprError();
2782   if (Ivar.isUsable())
2783     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2784                             cast<ObjCIvarDecl>(Ivar.get()));
2785 
2786   if (Lookup.empty() && II && AllowBuiltinCreation)
2787     LookupBuiltin(Lookup);
2788 
2789   // Sentinel value saying that we didn't do anything special.
2790   return ExprResult(false);
2791 }
2792 
2793 /// Cast a base object to a member's actual type.
2794 ///
2795 /// Logically this happens in three phases:
2796 ///
2797 /// * First we cast from the base type to the naming class.
2798 ///   The naming class is the class into which we were looking
2799 ///   when we found the member;  it's the qualifier type if a
2800 ///   qualifier was provided, and otherwise it's the base type.
2801 ///
2802 /// * Next we cast from the naming class to the declaring class.
2803 ///   If the member we found was brought into a class's scope by
2804 ///   a using declaration, this is that class;  otherwise it's
2805 ///   the class declaring the member.
2806 ///
2807 /// * Finally we cast from the declaring class to the "true"
2808 ///   declaring class of the member.  This conversion does not
2809 ///   obey access control.
2810 ExprResult
2811 Sema::PerformObjectMemberConversion(Expr *From,
2812                                     NestedNameSpecifier *Qualifier,
2813                                     NamedDecl *FoundDecl,
2814                                     NamedDecl *Member) {
2815   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2816   if (!RD)
2817     return From;
2818 
2819   QualType DestRecordType;
2820   QualType DestType;
2821   QualType FromRecordType;
2822   QualType FromType = From->getType();
2823   bool PointerConversions = false;
2824   if (isa<FieldDecl>(Member)) {
2825     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2826     auto FromPtrType = FromType->getAs<PointerType>();
2827     DestRecordType = Context.getAddrSpaceQualType(
2828         DestRecordType, FromPtrType
2829                             ? FromType->getPointeeType().getAddressSpace()
2830                             : FromType.getAddressSpace());
2831 
2832     if (FromPtrType) {
2833       DestType = Context.getPointerType(DestRecordType);
2834       FromRecordType = FromPtrType->getPointeeType();
2835       PointerConversions = true;
2836     } else {
2837       DestType = DestRecordType;
2838       FromRecordType = FromType;
2839     }
2840   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2841     if (Method->isStatic())
2842       return From;
2843 
2844     DestType = Method->getThisType();
2845     DestRecordType = DestType->getPointeeType();
2846 
2847     if (FromType->getAs<PointerType>()) {
2848       FromRecordType = FromType->getPointeeType();
2849       PointerConversions = true;
2850     } else {
2851       FromRecordType = FromType;
2852       DestType = DestRecordType;
2853     }
2854 
2855     LangAS FromAS = FromRecordType.getAddressSpace();
2856     LangAS DestAS = DestRecordType.getAddressSpace();
2857     if (FromAS != DestAS) {
2858       QualType FromRecordTypeWithoutAS =
2859           Context.removeAddrSpaceQualType(FromRecordType);
2860       QualType FromTypeWithDestAS =
2861           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2862       if (PointerConversions)
2863         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2864       From = ImpCastExprToType(From, FromTypeWithDestAS,
2865                                CK_AddressSpaceConversion, From->getValueKind())
2866                  .get();
2867     }
2868   } else {
2869     // No conversion necessary.
2870     return From;
2871   }
2872 
2873   if (DestType->isDependentType() || FromType->isDependentType())
2874     return From;
2875 
2876   // If the unqualified types are the same, no conversion is necessary.
2877   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2878     return From;
2879 
2880   SourceRange FromRange = From->getSourceRange();
2881   SourceLocation FromLoc = FromRange.getBegin();
2882 
2883   ExprValueKind VK = From->getValueKind();
2884 
2885   // C++ [class.member.lookup]p8:
2886   //   [...] Ambiguities can often be resolved by qualifying a name with its
2887   //   class name.
2888   //
2889   // If the member was a qualified name and the qualified referred to a
2890   // specific base subobject type, we'll cast to that intermediate type
2891   // first and then to the object in which the member is declared. That allows
2892   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2893   //
2894   //   class Base { public: int x; };
2895   //   class Derived1 : public Base { };
2896   //   class Derived2 : public Base { };
2897   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2898   //
2899   //   void VeryDerived::f() {
2900   //     x = 17; // error: ambiguous base subobjects
2901   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2902   //   }
2903   if (Qualifier && Qualifier->getAsType()) {
2904     QualType QType = QualType(Qualifier->getAsType(), 0);
2905     assert(QType->isRecordType() && "lookup done with non-record type");
2906 
2907     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2908 
2909     // In C++98, the qualifier type doesn't actually have to be a base
2910     // type of the object type, in which case we just ignore it.
2911     // Otherwise build the appropriate casts.
2912     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2913       CXXCastPath BasePath;
2914       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2915                                        FromLoc, FromRange, &BasePath))
2916         return ExprError();
2917 
2918       if (PointerConversions)
2919         QType = Context.getPointerType(QType);
2920       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2921                                VK, &BasePath).get();
2922 
2923       FromType = QType;
2924       FromRecordType = QRecordType;
2925 
2926       // If the qualifier type was the same as the destination type,
2927       // we're done.
2928       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2929         return From;
2930     }
2931   }
2932 
2933   bool IgnoreAccess = false;
2934 
2935   // If we actually found the member through a using declaration, cast
2936   // down to the using declaration's type.
2937   //
2938   // Pointer equality is fine here because only one declaration of a
2939   // class ever has member declarations.
2940   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2941     assert(isa<UsingShadowDecl>(FoundDecl));
2942     QualType URecordType = Context.getTypeDeclType(
2943                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2944 
2945     // We only need to do this if the naming-class to declaring-class
2946     // conversion is non-trivial.
2947     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2948       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2949       CXXCastPath BasePath;
2950       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2951                                        FromLoc, FromRange, &BasePath))
2952         return ExprError();
2953 
2954       QualType UType = URecordType;
2955       if (PointerConversions)
2956         UType = Context.getPointerType(UType);
2957       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2958                                VK, &BasePath).get();
2959       FromType = UType;
2960       FromRecordType = URecordType;
2961     }
2962 
2963     // We don't do access control for the conversion from the
2964     // declaring class to the true declaring class.
2965     IgnoreAccess = true;
2966   }
2967 
2968   CXXCastPath BasePath;
2969   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2970                                    FromLoc, FromRange, &BasePath,
2971                                    IgnoreAccess))
2972     return ExprError();
2973 
2974   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2975                            VK, &BasePath);
2976 }
2977 
2978 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2979                                       const LookupResult &R,
2980                                       bool HasTrailingLParen) {
2981   // Only when used directly as the postfix-expression of a call.
2982   if (!HasTrailingLParen)
2983     return false;
2984 
2985   // Never if a scope specifier was provided.
2986   if (SS.isSet())
2987     return false;
2988 
2989   // Only in C++ or ObjC++.
2990   if (!getLangOpts().CPlusPlus)
2991     return false;
2992 
2993   // Turn off ADL when we find certain kinds of declarations during
2994   // normal lookup:
2995   for (NamedDecl *D : R) {
2996     // C++0x [basic.lookup.argdep]p3:
2997     //     -- a declaration of a class member
2998     // Since using decls preserve this property, we check this on the
2999     // original decl.
3000     if (D->isCXXClassMember())
3001       return false;
3002 
3003     // C++0x [basic.lookup.argdep]p3:
3004     //     -- a block-scope function declaration that is not a
3005     //        using-declaration
3006     // NOTE: we also trigger this for function templates (in fact, we
3007     // don't check the decl type at all, since all other decl types
3008     // turn off ADL anyway).
3009     if (isa<UsingShadowDecl>(D))
3010       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3011     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3012       return false;
3013 
3014     // C++0x [basic.lookup.argdep]p3:
3015     //     -- a declaration that is neither a function or a function
3016     //        template
3017     // And also for builtin functions.
3018     if (isa<FunctionDecl>(D)) {
3019       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3020 
3021       // But also builtin functions.
3022       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3023         return false;
3024     } else if (!isa<FunctionTemplateDecl>(D))
3025       return false;
3026   }
3027 
3028   return true;
3029 }
3030 
3031 
3032 /// Diagnoses obvious problems with the use of the given declaration
3033 /// as an expression.  This is only actually called for lookups that
3034 /// were not overloaded, and it doesn't promise that the declaration
3035 /// will in fact be used.
3036 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3037   if (D->isInvalidDecl())
3038     return true;
3039 
3040   if (isa<TypedefNameDecl>(D)) {
3041     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3042     return true;
3043   }
3044 
3045   if (isa<ObjCInterfaceDecl>(D)) {
3046     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3047     return true;
3048   }
3049 
3050   if (isa<NamespaceDecl>(D)) {
3051     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3052     return true;
3053   }
3054 
3055   return false;
3056 }
3057 
3058 // Certain multiversion types should be treated as overloaded even when there is
3059 // only one result.
3060 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3061   assert(R.isSingleResult() && "Expected only a single result");
3062   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3063   return FD &&
3064          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3065 }
3066 
3067 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3068                                           LookupResult &R, bool NeedsADL,
3069                                           bool AcceptInvalidDecl) {
3070   // If this is a single, fully-resolved result and we don't need ADL,
3071   // just build an ordinary singleton decl ref.
3072   if (!NeedsADL && R.isSingleResult() &&
3073       !R.getAsSingle<FunctionTemplateDecl>() &&
3074       !ShouldLookupResultBeMultiVersionOverload(R))
3075     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3076                                     R.getRepresentativeDecl(), nullptr,
3077                                     AcceptInvalidDecl);
3078 
3079   // We only need to check the declaration if there's exactly one
3080   // result, because in the overloaded case the results can only be
3081   // functions and function templates.
3082   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3083       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3084     return ExprError();
3085 
3086   // Otherwise, just build an unresolved lookup expression.  Suppress
3087   // any lookup-related diagnostics; we'll hash these out later, when
3088   // we've picked a target.
3089   R.suppressDiagnostics();
3090 
3091   UnresolvedLookupExpr *ULE
3092     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3093                                    SS.getWithLocInContext(Context),
3094                                    R.getLookupNameInfo(),
3095                                    NeedsADL, R.isOverloadedResult(),
3096                                    R.begin(), R.end());
3097 
3098   return ULE;
3099 }
3100 
3101 static void
3102 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3103                                    ValueDecl *var, DeclContext *DC);
3104 
3105 /// Complete semantic analysis for a reference to the given declaration.
3106 ExprResult Sema::BuildDeclarationNameExpr(
3107     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3108     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3109     bool AcceptInvalidDecl) {
3110   assert(D && "Cannot refer to a NULL declaration");
3111   assert(!isa<FunctionTemplateDecl>(D) &&
3112          "Cannot refer unambiguously to a function template");
3113 
3114   SourceLocation Loc = NameInfo.getLoc();
3115   if (CheckDeclInExpr(*this, Loc, D))
3116     return ExprError();
3117 
3118   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3119     // Specifically diagnose references to class templates that are missing
3120     // a template argument list.
3121     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3122     return ExprError();
3123   }
3124 
3125   // Make sure that we're referring to a value.
3126   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3127   if (!VD) {
3128     Diag(Loc, diag::err_ref_non_value)
3129       << D << SS.getRange();
3130     Diag(D->getLocation(), diag::note_declared_at);
3131     return ExprError();
3132   }
3133 
3134   // Check whether this declaration can be used. Note that we suppress
3135   // this check when we're going to perform argument-dependent lookup
3136   // on this function name, because this might not be the function
3137   // that overload resolution actually selects.
3138   if (DiagnoseUseOfDecl(VD, Loc))
3139     return ExprError();
3140 
3141   // Only create DeclRefExpr's for valid Decl's.
3142   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3143     return ExprError();
3144 
3145   // Handle members of anonymous structs and unions.  If we got here,
3146   // and the reference is to a class member indirect field, then this
3147   // must be the subject of a pointer-to-member expression.
3148   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3149     if (!indirectField->isCXXClassMember())
3150       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3151                                                       indirectField);
3152 
3153   {
3154     QualType type = VD->getType();
3155     if (type.isNull())
3156       return ExprError();
3157     ExprValueKind valueKind = VK_RValue;
3158 
3159     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3160     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3161     // is expanded by some outer '...' in the context of the use.
3162     type = type.getNonPackExpansionType();
3163 
3164     switch (D->getKind()) {
3165     // Ignore all the non-ValueDecl kinds.
3166 #define ABSTRACT_DECL(kind)
3167 #define VALUE(type, base)
3168 #define DECL(type, base) \
3169     case Decl::type:
3170 #include "clang/AST/DeclNodes.inc"
3171       llvm_unreachable("invalid value decl kind");
3172 
3173     // These shouldn't make it here.
3174     case Decl::ObjCAtDefsField:
3175       llvm_unreachable("forming non-member reference to ivar?");
3176 
3177     // Enum constants are always r-values and never references.
3178     // Unresolved using declarations are dependent.
3179     case Decl::EnumConstant:
3180     case Decl::UnresolvedUsingValue:
3181     case Decl::OMPDeclareReduction:
3182     case Decl::OMPDeclareMapper:
3183       valueKind = VK_RValue;
3184       break;
3185 
3186     // Fields and indirect fields that got here must be for
3187     // pointer-to-member expressions; we just call them l-values for
3188     // internal consistency, because this subexpression doesn't really
3189     // exist in the high-level semantics.
3190     case Decl::Field:
3191     case Decl::IndirectField:
3192     case Decl::ObjCIvar:
3193       assert(getLangOpts().CPlusPlus &&
3194              "building reference to field in C?");
3195 
3196       // These can't have reference type in well-formed programs, but
3197       // for internal consistency we do this anyway.
3198       type = type.getNonReferenceType();
3199       valueKind = VK_LValue;
3200       break;
3201 
3202     // Non-type template parameters are either l-values or r-values
3203     // depending on the type.
3204     case Decl::NonTypeTemplateParm: {
3205       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3206         type = reftype->getPointeeType();
3207         valueKind = VK_LValue; // even if the parameter is an r-value reference
3208         break;
3209       }
3210 
3211       // For non-references, we need to strip qualifiers just in case
3212       // the template parameter was declared as 'const int' or whatever.
3213       valueKind = VK_RValue;
3214       type = type.getUnqualifiedType();
3215       break;
3216     }
3217 
3218     case Decl::Var:
3219     case Decl::VarTemplateSpecialization:
3220     case Decl::VarTemplatePartialSpecialization:
3221     case Decl::Decomposition:
3222     case Decl::OMPCapturedExpr:
3223       // In C, "extern void blah;" is valid and is an r-value.
3224       if (!getLangOpts().CPlusPlus &&
3225           !type.hasQualifiers() &&
3226           type->isVoidType()) {
3227         valueKind = VK_RValue;
3228         break;
3229       }
3230       LLVM_FALLTHROUGH;
3231 
3232     case Decl::ImplicitParam:
3233     case Decl::ParmVar: {
3234       // These are always l-values.
3235       valueKind = VK_LValue;
3236       type = type.getNonReferenceType();
3237 
3238       // FIXME: Does the addition of const really only apply in
3239       // potentially-evaluated contexts? Since the variable isn't actually
3240       // captured in an unevaluated context, it seems that the answer is no.
3241       if (!isUnevaluatedContext()) {
3242         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3243         if (!CapturedType.isNull())
3244           type = CapturedType;
3245       }
3246 
3247       break;
3248     }
3249 
3250     case Decl::Binding: {
3251       // These are always lvalues.
3252       valueKind = VK_LValue;
3253       type = type.getNonReferenceType();
3254       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3255       // decides how that's supposed to work.
3256       auto *BD = cast<BindingDecl>(VD);
3257       if (BD->getDeclContext() != CurContext) {
3258         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3259         if (DD && DD->hasLocalStorage())
3260           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3261       }
3262       break;
3263     }
3264 
3265     case Decl::Function: {
3266       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3267         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3268           type = Context.BuiltinFnTy;
3269           valueKind = VK_RValue;
3270           break;
3271         }
3272       }
3273 
3274       const FunctionType *fty = type->castAs<FunctionType>();
3275 
3276       // If we're referring to a function with an __unknown_anytype
3277       // result type, make the entire expression __unknown_anytype.
3278       if (fty->getReturnType() == Context.UnknownAnyTy) {
3279         type = Context.UnknownAnyTy;
3280         valueKind = VK_RValue;
3281         break;
3282       }
3283 
3284       // Functions are l-values in C++.
3285       if (getLangOpts().CPlusPlus) {
3286         valueKind = VK_LValue;
3287         break;
3288       }
3289 
3290       // C99 DR 316 says that, if a function type comes from a
3291       // function definition (without a prototype), that type is only
3292       // used for checking compatibility. Therefore, when referencing
3293       // the function, we pretend that we don't have the full function
3294       // type.
3295       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3296           isa<FunctionProtoType>(fty))
3297         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3298                                               fty->getExtInfo());
3299 
3300       // Functions are r-values in C.
3301       valueKind = VK_RValue;
3302       break;
3303     }
3304 
3305     case Decl::CXXDeductionGuide:
3306       llvm_unreachable("building reference to deduction guide");
3307 
3308     case Decl::MSProperty:
3309     case Decl::MSGuid:
3310       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3311       // or duplicated between host and device?
3312       valueKind = VK_LValue;
3313       break;
3314 
3315     case Decl::CXXMethod:
3316       // If we're referring to a method with an __unknown_anytype
3317       // result type, make the entire expression __unknown_anytype.
3318       // This should only be possible with a type written directly.
3319       if (const FunctionProtoType *proto
3320             = dyn_cast<FunctionProtoType>(VD->getType()))
3321         if (proto->getReturnType() == Context.UnknownAnyTy) {
3322           type = Context.UnknownAnyTy;
3323           valueKind = VK_RValue;
3324           break;
3325         }
3326 
3327       // C++ methods are l-values if static, r-values if non-static.
3328       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3329         valueKind = VK_LValue;
3330         break;
3331       }
3332       LLVM_FALLTHROUGH;
3333 
3334     case Decl::CXXConversion:
3335     case Decl::CXXDestructor:
3336     case Decl::CXXConstructor:
3337       valueKind = VK_RValue;
3338       break;
3339     }
3340 
3341     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3342                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3343                             TemplateArgs);
3344   }
3345 }
3346 
3347 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3348                                     SmallString<32> &Target) {
3349   Target.resize(CharByteWidth * (Source.size() + 1));
3350   char *ResultPtr = &Target[0];
3351   const llvm::UTF8 *ErrorPtr;
3352   bool success =
3353       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3354   (void)success;
3355   assert(success);
3356   Target.resize(ResultPtr - &Target[0]);
3357 }
3358 
3359 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3360                                      PredefinedExpr::IdentKind IK) {
3361   // Pick the current block, lambda, captured statement or function.
3362   Decl *currentDecl = nullptr;
3363   if (const BlockScopeInfo *BSI = getCurBlock())
3364     currentDecl = BSI->TheDecl;
3365   else if (const LambdaScopeInfo *LSI = getCurLambda())
3366     currentDecl = LSI->CallOperator;
3367   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3368     currentDecl = CSI->TheCapturedDecl;
3369   else
3370     currentDecl = getCurFunctionOrMethodDecl();
3371 
3372   if (!currentDecl) {
3373     Diag(Loc, diag::ext_predef_outside_function);
3374     currentDecl = Context.getTranslationUnitDecl();
3375   }
3376 
3377   QualType ResTy;
3378   StringLiteral *SL = nullptr;
3379   if (cast<DeclContext>(currentDecl)->isDependentContext())
3380     ResTy = Context.DependentTy;
3381   else {
3382     // Pre-defined identifiers are of type char[x], where x is the length of
3383     // the string.
3384     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3385     unsigned Length = Str.length();
3386 
3387     llvm::APInt LengthI(32, Length + 1);
3388     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3389       ResTy =
3390           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3391       SmallString<32> RawChars;
3392       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3393                               Str, RawChars);
3394       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3395                                            ArrayType::Normal,
3396                                            /*IndexTypeQuals*/ 0);
3397       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3398                                  /*Pascal*/ false, ResTy, Loc);
3399     } else {
3400       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3401       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3402                                            ArrayType::Normal,
3403                                            /*IndexTypeQuals*/ 0);
3404       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3405                                  /*Pascal*/ false, ResTy, Loc);
3406     }
3407   }
3408 
3409   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3410 }
3411 
3412 static std::pair<QualType, StringLiteral *>
3413 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3414                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3415   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3416 
3417   if (OpType->isDependentType()) {
3418       Result.first = Context.DependentTy;
3419       return Result;
3420   }
3421 
3422   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3423   llvm::APInt Length(32, Str.length() + 1);
3424   Result.first =
3425       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3426   Result.first = Context.getConstantArrayType(
3427       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3428   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3429                                         /*Pascal*/ false, Result.first, OpLoc);
3430   return Result;
3431 }
3432 
3433 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3434                                        TypeSourceInfo *Operand) {
3435   QualType ResultTy;
3436   StringLiteral *SL;
3437   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3438       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3439 
3440   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3441                                 PredefinedExpr::UniqueStableNameType, SL,
3442                                 Operand);
3443 }
3444 
3445 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3446                                        Expr *E) {
3447   QualType ResultTy;
3448   StringLiteral *SL;
3449   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3450       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3451 
3452   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3453                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3454 }
3455 
3456 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3457                                            SourceLocation L, SourceLocation R,
3458                                            ParsedType Ty) {
3459   TypeSourceInfo *TInfo = nullptr;
3460   QualType T = GetTypeFromParser(Ty, &TInfo);
3461 
3462   if (T.isNull())
3463     return ExprError();
3464   if (!TInfo)
3465     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3466 
3467   return BuildUniqueStableName(OpLoc, TInfo);
3468 }
3469 
3470 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3471                                            SourceLocation L, SourceLocation R,
3472                                            Expr *E) {
3473   return BuildUniqueStableName(OpLoc, E);
3474 }
3475 
3476 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3477   PredefinedExpr::IdentKind IK;
3478 
3479   switch (Kind) {
3480   default: llvm_unreachable("Unknown simple primary expr!");
3481   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3482   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3483   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3484   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3485   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3486   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3487   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3488   }
3489 
3490   return BuildPredefinedExpr(Loc, IK);
3491 }
3492 
3493 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3494   SmallString<16> CharBuffer;
3495   bool Invalid = false;
3496   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3497   if (Invalid)
3498     return ExprError();
3499 
3500   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3501                             PP, Tok.getKind());
3502   if (Literal.hadError())
3503     return ExprError();
3504 
3505   QualType Ty;
3506   if (Literal.isWide())
3507     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3508   else if (Literal.isUTF8() && getLangOpts().Char8)
3509     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3510   else if (Literal.isUTF16())
3511     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3512   else if (Literal.isUTF32())
3513     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3514   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3515     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3516   else
3517     Ty = Context.CharTy;  // 'x' -> char in C++
3518 
3519   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3520   if (Literal.isWide())
3521     Kind = CharacterLiteral::Wide;
3522   else if (Literal.isUTF16())
3523     Kind = CharacterLiteral::UTF16;
3524   else if (Literal.isUTF32())
3525     Kind = CharacterLiteral::UTF32;
3526   else if (Literal.isUTF8())
3527     Kind = CharacterLiteral::UTF8;
3528 
3529   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3530                                              Tok.getLocation());
3531 
3532   if (Literal.getUDSuffix().empty())
3533     return Lit;
3534 
3535   // We're building a user-defined literal.
3536   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3537   SourceLocation UDSuffixLoc =
3538     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3539 
3540   // Make sure we're allowed user-defined literals here.
3541   if (!UDLScope)
3542     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3543 
3544   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3545   //   operator "" X (ch)
3546   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3547                                         Lit, Tok.getLocation());
3548 }
3549 
3550 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3551   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3552   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3553                                 Context.IntTy, Loc);
3554 }
3555 
3556 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3557                                   QualType Ty, SourceLocation Loc) {
3558   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3559 
3560   using llvm::APFloat;
3561   APFloat Val(Format);
3562 
3563   APFloat::opStatus result = Literal.GetFloatValue(Val);
3564 
3565   // Overflow is always an error, but underflow is only an error if
3566   // we underflowed to zero (APFloat reports denormals as underflow).
3567   if ((result & APFloat::opOverflow) ||
3568       ((result & APFloat::opUnderflow) && Val.isZero())) {
3569     unsigned diagnostic;
3570     SmallString<20> buffer;
3571     if (result & APFloat::opOverflow) {
3572       diagnostic = diag::warn_float_overflow;
3573       APFloat::getLargest(Format).toString(buffer);
3574     } else {
3575       diagnostic = diag::warn_float_underflow;
3576       APFloat::getSmallest(Format).toString(buffer);
3577     }
3578 
3579     S.Diag(Loc, diagnostic)
3580       << Ty
3581       << StringRef(buffer.data(), buffer.size());
3582   }
3583 
3584   bool isExact = (result == APFloat::opOK);
3585   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3586 }
3587 
3588 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3589   assert(E && "Invalid expression");
3590 
3591   if (E->isValueDependent())
3592     return false;
3593 
3594   QualType QT = E->getType();
3595   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3596     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3597     return true;
3598   }
3599 
3600   llvm::APSInt ValueAPS;
3601   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3602 
3603   if (R.isInvalid())
3604     return true;
3605 
3606   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3607   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3608     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3609         << ValueAPS.toString(10) << ValueIsPositive;
3610     return true;
3611   }
3612 
3613   return false;
3614 }
3615 
3616 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3617   // Fast path for a single digit (which is quite common).  A single digit
3618   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3619   if (Tok.getLength() == 1) {
3620     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3621     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3622   }
3623 
3624   SmallString<128> SpellingBuffer;
3625   // NumericLiteralParser wants to overread by one character.  Add padding to
3626   // the buffer in case the token is copied to the buffer.  If getSpelling()
3627   // returns a StringRef to the memory buffer, it should have a null char at
3628   // the EOF, so it is also safe.
3629   SpellingBuffer.resize(Tok.getLength() + 1);
3630 
3631   // Get the spelling of the token, which eliminates trigraphs, etc.
3632   bool Invalid = false;
3633   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3634   if (Invalid)
3635     return ExprError();
3636 
3637   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3638   if (Literal.hadError)
3639     return ExprError();
3640 
3641   if (Literal.hasUDSuffix()) {
3642     // We're building a user-defined literal.
3643     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3644     SourceLocation UDSuffixLoc =
3645       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3646 
3647     // Make sure we're allowed user-defined literals here.
3648     if (!UDLScope)
3649       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3650 
3651     QualType CookedTy;
3652     if (Literal.isFloatingLiteral()) {
3653       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3654       // long double, the literal is treated as a call of the form
3655       //   operator "" X (f L)
3656       CookedTy = Context.LongDoubleTy;
3657     } else {
3658       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3659       // unsigned long long, the literal is treated as a call of the form
3660       //   operator "" X (n ULL)
3661       CookedTy = Context.UnsignedLongLongTy;
3662     }
3663 
3664     DeclarationName OpName =
3665       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3666     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3667     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3668 
3669     SourceLocation TokLoc = Tok.getLocation();
3670 
3671     // Perform literal operator lookup to determine if we're building a raw
3672     // literal or a cooked one.
3673     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3674     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3675                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3676                                   /*AllowStringTemplate*/ false,
3677                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3678     case LOLR_ErrorNoDiagnostic:
3679       // Lookup failure for imaginary constants isn't fatal, there's still the
3680       // GNU extension producing _Complex types.
3681       break;
3682     case LOLR_Error:
3683       return ExprError();
3684     case LOLR_Cooked: {
3685       Expr *Lit;
3686       if (Literal.isFloatingLiteral()) {
3687         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3688       } else {
3689         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3690         if (Literal.GetIntegerValue(ResultVal))
3691           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3692               << /* Unsigned */ 1;
3693         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3694                                      Tok.getLocation());
3695       }
3696       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3697     }
3698 
3699     case LOLR_Raw: {
3700       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3701       // literal is treated as a call of the form
3702       //   operator "" X ("n")
3703       unsigned Length = Literal.getUDSuffixOffset();
3704       QualType StrTy = Context.getConstantArrayType(
3705           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3706           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3707       Expr *Lit = StringLiteral::Create(
3708           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3709           /*Pascal*/false, StrTy, &TokLoc, 1);
3710       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3711     }
3712 
3713     case LOLR_Template: {
3714       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3715       // template), L is treated as a call fo the form
3716       //   operator "" X <'c1', 'c2', ... 'ck'>()
3717       // where n is the source character sequence c1 c2 ... ck.
3718       TemplateArgumentListInfo ExplicitArgs;
3719       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3720       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3721       llvm::APSInt Value(CharBits, CharIsUnsigned);
3722       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3723         Value = TokSpelling[I];
3724         TemplateArgument Arg(Context, Value, Context.CharTy);
3725         TemplateArgumentLocInfo ArgInfo;
3726         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3727       }
3728       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3729                                       &ExplicitArgs);
3730     }
3731     case LOLR_StringTemplate:
3732       llvm_unreachable("unexpected literal operator lookup result");
3733     }
3734   }
3735 
3736   Expr *Res;
3737 
3738   if (Literal.isFixedPointLiteral()) {
3739     QualType Ty;
3740 
3741     if (Literal.isAccum) {
3742       if (Literal.isHalf) {
3743         Ty = Context.ShortAccumTy;
3744       } else if (Literal.isLong) {
3745         Ty = Context.LongAccumTy;
3746       } else {
3747         Ty = Context.AccumTy;
3748       }
3749     } else if (Literal.isFract) {
3750       if (Literal.isHalf) {
3751         Ty = Context.ShortFractTy;
3752       } else if (Literal.isLong) {
3753         Ty = Context.LongFractTy;
3754       } else {
3755         Ty = Context.FractTy;
3756       }
3757     }
3758 
3759     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3760 
3761     bool isSigned = !Literal.isUnsigned;
3762     unsigned scale = Context.getFixedPointScale(Ty);
3763     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3764 
3765     llvm::APInt Val(bit_width, 0, isSigned);
3766     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3767     bool ValIsZero = Val.isNullValue() && !Overflowed;
3768 
3769     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3770     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3771       // Clause 6.4.4 - The value of a constant shall be in the range of
3772       // representable values for its type, with exception for constants of a
3773       // fract type with a value of exactly 1; such a constant shall denote
3774       // the maximal value for the type.
3775       --Val;
3776     else if (Val.ugt(MaxVal) || Overflowed)
3777       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3778 
3779     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3780                                               Tok.getLocation(), scale);
3781   } else if (Literal.isFloatingLiteral()) {
3782     QualType Ty;
3783     if (Literal.isHalf){
3784       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3785         Ty = Context.HalfTy;
3786       else {
3787         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3788         return ExprError();
3789       }
3790     } else if (Literal.isFloat)
3791       Ty = Context.FloatTy;
3792     else if (Literal.isLong)
3793       Ty = Context.LongDoubleTy;
3794     else if (Literal.isFloat16)
3795       Ty = Context.Float16Ty;
3796     else if (Literal.isFloat128)
3797       Ty = Context.Float128Ty;
3798     else
3799       Ty = Context.DoubleTy;
3800 
3801     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3802 
3803     if (Ty == Context.DoubleTy) {
3804       if (getLangOpts().SinglePrecisionConstants) {
3805         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3806         if (BTy->getKind() != BuiltinType::Float) {
3807           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3808         }
3809       } else if (getLangOpts().OpenCL &&
3810                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3811         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3812         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3813         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3814       }
3815     }
3816   } else if (!Literal.isIntegerLiteral()) {
3817     return ExprError();
3818   } else {
3819     QualType Ty;
3820 
3821     // 'long long' is a C99 or C++11 feature.
3822     if (!getLangOpts().C99 && Literal.isLongLong) {
3823       if (getLangOpts().CPlusPlus)
3824         Diag(Tok.getLocation(),
3825              getLangOpts().CPlusPlus11 ?
3826              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3827       else
3828         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3829     }
3830 
3831     // Get the value in the widest-possible width.
3832     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3833     llvm::APInt ResultVal(MaxWidth, 0);
3834 
3835     if (Literal.GetIntegerValue(ResultVal)) {
3836       // If this value didn't fit into uintmax_t, error and force to ull.
3837       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3838           << /* Unsigned */ 1;
3839       Ty = Context.UnsignedLongLongTy;
3840       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3841              "long long is not intmax_t?");
3842     } else {
3843       // If this value fits into a ULL, try to figure out what else it fits into
3844       // according to the rules of C99 6.4.4.1p5.
3845 
3846       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3847       // be an unsigned int.
3848       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3849 
3850       // Check from smallest to largest, picking the smallest type we can.
3851       unsigned Width = 0;
3852 
3853       // Microsoft specific integer suffixes are explicitly sized.
3854       if (Literal.MicrosoftInteger) {
3855         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3856           Width = 8;
3857           Ty = Context.CharTy;
3858         } else {
3859           Width = Literal.MicrosoftInteger;
3860           Ty = Context.getIntTypeForBitwidth(Width,
3861                                              /*Signed=*/!Literal.isUnsigned);
3862         }
3863       }
3864 
3865       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3866         // Are int/unsigned possibilities?
3867         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3868 
3869         // Does it fit in a unsigned int?
3870         if (ResultVal.isIntN(IntSize)) {
3871           // Does it fit in a signed int?
3872           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3873             Ty = Context.IntTy;
3874           else if (AllowUnsigned)
3875             Ty = Context.UnsignedIntTy;
3876           Width = IntSize;
3877         }
3878       }
3879 
3880       // Are long/unsigned long possibilities?
3881       if (Ty.isNull() && !Literal.isLongLong) {
3882         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3883 
3884         // Does it fit in a unsigned long?
3885         if (ResultVal.isIntN(LongSize)) {
3886           // Does it fit in a signed long?
3887           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3888             Ty = Context.LongTy;
3889           else if (AllowUnsigned)
3890             Ty = Context.UnsignedLongTy;
3891           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3892           // is compatible.
3893           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3894             const unsigned LongLongSize =
3895                 Context.getTargetInfo().getLongLongWidth();
3896             Diag(Tok.getLocation(),
3897                  getLangOpts().CPlusPlus
3898                      ? Literal.isLong
3899                            ? diag::warn_old_implicitly_unsigned_long_cxx
3900                            : /*C++98 UB*/ diag::
3901                                  ext_old_implicitly_unsigned_long_cxx
3902                      : diag::warn_old_implicitly_unsigned_long)
3903                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3904                                             : /*will be ill-formed*/ 1);
3905             Ty = Context.UnsignedLongTy;
3906           }
3907           Width = LongSize;
3908         }
3909       }
3910 
3911       // Check long long if needed.
3912       if (Ty.isNull()) {
3913         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3914 
3915         // Does it fit in a unsigned long long?
3916         if (ResultVal.isIntN(LongLongSize)) {
3917           // Does it fit in a signed long long?
3918           // To be compatible with MSVC, hex integer literals ending with the
3919           // LL or i64 suffix are always signed in Microsoft mode.
3920           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3921               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3922             Ty = Context.LongLongTy;
3923           else if (AllowUnsigned)
3924             Ty = Context.UnsignedLongLongTy;
3925           Width = LongLongSize;
3926         }
3927       }
3928 
3929       // If we still couldn't decide a type, we probably have something that
3930       // does not fit in a signed long long, but has no U suffix.
3931       if (Ty.isNull()) {
3932         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3933         Ty = Context.UnsignedLongLongTy;
3934         Width = Context.getTargetInfo().getLongLongWidth();
3935       }
3936 
3937       if (ResultVal.getBitWidth() != Width)
3938         ResultVal = ResultVal.trunc(Width);
3939     }
3940     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3941   }
3942 
3943   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3944   if (Literal.isImaginary) {
3945     Res = new (Context) ImaginaryLiteral(Res,
3946                                         Context.getComplexType(Res->getType()));
3947 
3948     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3949   }
3950   return Res;
3951 }
3952 
3953 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3954   assert(E && "ActOnParenExpr() missing expr");
3955   return new (Context) ParenExpr(L, R, E);
3956 }
3957 
3958 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3959                                          SourceLocation Loc,
3960                                          SourceRange ArgRange) {
3961   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3962   // scalar or vector data type argument..."
3963   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3964   // type (C99 6.2.5p18) or void.
3965   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3966     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3967       << T << ArgRange;
3968     return true;
3969   }
3970 
3971   assert((T->isVoidType() || !T->isIncompleteType()) &&
3972          "Scalar types should always be complete");
3973   return false;
3974 }
3975 
3976 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3977                                            SourceLocation Loc,
3978                                            SourceRange ArgRange,
3979                                            UnaryExprOrTypeTrait TraitKind) {
3980   // Invalid types must be hard errors for SFINAE in C++.
3981   if (S.LangOpts.CPlusPlus)
3982     return true;
3983 
3984   // C99 6.5.3.4p1:
3985   if (T->isFunctionType() &&
3986       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3987        TraitKind == UETT_PreferredAlignOf)) {
3988     // sizeof(function)/alignof(function) is allowed as an extension.
3989     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3990         << getTraitSpelling(TraitKind) << ArgRange;
3991     return false;
3992   }
3993 
3994   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3995   // this is an error (OpenCL v1.1 s6.3.k)
3996   if (T->isVoidType()) {
3997     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3998                                         : diag::ext_sizeof_alignof_void_type;
3999     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4000     return false;
4001   }
4002 
4003   return true;
4004 }
4005 
4006 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4007                                              SourceLocation Loc,
4008                                              SourceRange ArgRange,
4009                                              UnaryExprOrTypeTrait TraitKind) {
4010   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4011   // runtime doesn't allow it.
4012   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4013     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4014       << T << (TraitKind == UETT_SizeOf)
4015       << ArgRange;
4016     return true;
4017   }
4018 
4019   return false;
4020 }
4021 
4022 /// Check whether E is a pointer from a decayed array type (the decayed
4023 /// pointer type is equal to T) and emit a warning if it is.
4024 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4025                                      Expr *E) {
4026   // Don't warn if the operation changed the type.
4027   if (T != E->getType())
4028     return;
4029 
4030   // Now look for array decays.
4031   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4032   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4033     return;
4034 
4035   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4036                                              << ICE->getType()
4037                                              << ICE->getSubExpr()->getType();
4038 }
4039 
4040 /// Check the constraints on expression operands to unary type expression
4041 /// and type traits.
4042 ///
4043 /// Completes any types necessary and validates the constraints on the operand
4044 /// expression. The logic mostly mirrors the type-based overload, but may modify
4045 /// the expression as it completes the type for that expression through template
4046 /// instantiation, etc.
4047 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4048                                             UnaryExprOrTypeTrait ExprKind) {
4049   QualType ExprTy = E->getType();
4050   assert(!ExprTy->isReferenceType());
4051 
4052   bool IsUnevaluatedOperand =
4053       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4054        ExprKind == UETT_PreferredAlignOf);
4055   if (IsUnevaluatedOperand) {
4056     ExprResult Result = CheckUnevaluatedOperand(E);
4057     if (Result.isInvalid())
4058       return true;
4059     E = Result.get();
4060   }
4061 
4062   if (ExprKind == UETT_VecStep)
4063     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4064                                         E->getSourceRange());
4065 
4066   // Explicitly list some types as extensions.
4067   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4068                                       E->getSourceRange(), ExprKind))
4069     return false;
4070 
4071   // 'alignof' applied to an expression only requires the base element type of
4072   // the expression to be complete. 'sizeof' requires the expression's type to
4073   // be complete (and will attempt to complete it if it's an array of unknown
4074   // bound).
4075   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4076     if (RequireCompleteSizedType(
4077             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4078             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4079             getTraitSpelling(ExprKind), E->getSourceRange()))
4080       return true;
4081   } else {
4082     if (RequireCompleteSizedExprType(
4083             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4084             getTraitSpelling(ExprKind), E->getSourceRange()))
4085       return true;
4086   }
4087 
4088   // Completing the expression's type may have changed it.
4089   ExprTy = E->getType();
4090   assert(!ExprTy->isReferenceType());
4091 
4092   if (ExprTy->isFunctionType()) {
4093     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4094         << getTraitSpelling(ExprKind) << E->getSourceRange();
4095     return true;
4096   }
4097 
4098   // The operand for sizeof and alignof is in an unevaluated expression context,
4099   // so side effects could result in unintended consequences.
4100   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4101       E->HasSideEffects(Context, false))
4102     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4103 
4104   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4105                                        E->getSourceRange(), ExprKind))
4106     return true;
4107 
4108   if (ExprKind == UETT_SizeOf) {
4109     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4110       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4111         QualType OType = PVD->getOriginalType();
4112         QualType Type = PVD->getType();
4113         if (Type->isPointerType() && OType->isArrayType()) {
4114           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4115             << Type << OType;
4116           Diag(PVD->getLocation(), diag::note_declared_at);
4117         }
4118       }
4119     }
4120 
4121     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4122     // decays into a pointer and returns an unintended result. This is most
4123     // likely a typo for "sizeof(array) op x".
4124     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4125       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4126                                BO->getLHS());
4127       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4128                                BO->getRHS());
4129     }
4130   }
4131 
4132   return false;
4133 }
4134 
4135 /// Check the constraints on operands to unary expression and type
4136 /// traits.
4137 ///
4138 /// This will complete any types necessary, and validate the various constraints
4139 /// on those operands.
4140 ///
4141 /// The UsualUnaryConversions() function is *not* called by this routine.
4142 /// C99 6.3.2.1p[2-4] all state:
4143 ///   Except when it is the operand of the sizeof operator ...
4144 ///
4145 /// C++ [expr.sizeof]p4
4146 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4147 ///   standard conversions are not applied to the operand of sizeof.
4148 ///
4149 /// This policy is followed for all of the unary trait expressions.
4150 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4151                                             SourceLocation OpLoc,
4152                                             SourceRange ExprRange,
4153                                             UnaryExprOrTypeTrait ExprKind) {
4154   if (ExprType->isDependentType())
4155     return false;
4156 
4157   // C++ [expr.sizeof]p2:
4158   //     When applied to a reference or a reference type, the result
4159   //     is the size of the referenced type.
4160   // C++11 [expr.alignof]p3:
4161   //     When alignof is applied to a reference type, the result
4162   //     shall be the alignment of the referenced type.
4163   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4164     ExprType = Ref->getPointeeType();
4165 
4166   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4167   //   When alignof or _Alignof is applied to an array type, the result
4168   //   is the alignment of the element type.
4169   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4170       ExprKind == UETT_OpenMPRequiredSimdAlign)
4171     ExprType = Context.getBaseElementType(ExprType);
4172 
4173   if (ExprKind == UETT_VecStep)
4174     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4175 
4176   // Explicitly list some types as extensions.
4177   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4178                                       ExprKind))
4179     return false;
4180 
4181   if (RequireCompleteSizedType(
4182           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4183           getTraitSpelling(ExprKind), ExprRange))
4184     return true;
4185 
4186   if (ExprType->isFunctionType()) {
4187     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4188         << getTraitSpelling(ExprKind) << ExprRange;
4189     return true;
4190   }
4191 
4192   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4193                                        ExprKind))
4194     return true;
4195 
4196   return false;
4197 }
4198 
4199 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4200   // Cannot know anything else if the expression is dependent.
4201   if (E->isTypeDependent())
4202     return false;
4203 
4204   if (E->getObjectKind() == OK_BitField) {
4205     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4206        << 1 << E->getSourceRange();
4207     return true;
4208   }
4209 
4210   ValueDecl *D = nullptr;
4211   Expr *Inner = E->IgnoreParens();
4212   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4213     D = DRE->getDecl();
4214   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4215     D = ME->getMemberDecl();
4216   }
4217 
4218   // If it's a field, require the containing struct to have a
4219   // complete definition so that we can compute the layout.
4220   //
4221   // This can happen in C++11 onwards, either by naming the member
4222   // in a way that is not transformed into a member access expression
4223   // (in an unevaluated operand, for instance), or by naming the member
4224   // in a trailing-return-type.
4225   //
4226   // For the record, since __alignof__ on expressions is a GCC
4227   // extension, GCC seems to permit this but always gives the
4228   // nonsensical answer 0.
4229   //
4230   // We don't really need the layout here --- we could instead just
4231   // directly check for all the appropriate alignment-lowing
4232   // attributes --- but that would require duplicating a lot of
4233   // logic that just isn't worth duplicating for such a marginal
4234   // use-case.
4235   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4236     // Fast path this check, since we at least know the record has a
4237     // definition if we can find a member of it.
4238     if (!FD->getParent()->isCompleteDefinition()) {
4239       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4240         << E->getSourceRange();
4241       return true;
4242     }
4243 
4244     // Otherwise, if it's a field, and the field doesn't have
4245     // reference type, then it must have a complete type (or be a
4246     // flexible array member, which we explicitly want to
4247     // white-list anyway), which makes the following checks trivial.
4248     if (!FD->getType()->isReferenceType())
4249       return false;
4250   }
4251 
4252   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4253 }
4254 
4255 bool Sema::CheckVecStepExpr(Expr *E) {
4256   E = E->IgnoreParens();
4257 
4258   // Cannot know anything else if the expression is dependent.
4259   if (E->isTypeDependent())
4260     return false;
4261 
4262   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4263 }
4264 
4265 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4266                                         CapturingScopeInfo *CSI) {
4267   assert(T->isVariablyModifiedType());
4268   assert(CSI != nullptr);
4269 
4270   // We're going to walk down into the type and look for VLA expressions.
4271   do {
4272     const Type *Ty = T.getTypePtr();
4273     switch (Ty->getTypeClass()) {
4274 #define TYPE(Class, Base)
4275 #define ABSTRACT_TYPE(Class, Base)
4276 #define NON_CANONICAL_TYPE(Class, Base)
4277 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4278 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4279 #include "clang/AST/TypeNodes.inc"
4280       T = QualType();
4281       break;
4282     // These types are never variably-modified.
4283     case Type::Builtin:
4284     case Type::Complex:
4285     case Type::Vector:
4286     case Type::ExtVector:
4287     case Type::ConstantMatrix:
4288     case Type::Record:
4289     case Type::Enum:
4290     case Type::Elaborated:
4291     case Type::TemplateSpecialization:
4292     case Type::ObjCObject:
4293     case Type::ObjCInterface:
4294     case Type::ObjCObjectPointer:
4295     case Type::ObjCTypeParam:
4296     case Type::Pipe:
4297     case Type::ExtInt:
4298       llvm_unreachable("type class is never variably-modified!");
4299     case Type::Adjusted:
4300       T = cast<AdjustedType>(Ty)->getOriginalType();
4301       break;
4302     case Type::Decayed:
4303       T = cast<DecayedType>(Ty)->getPointeeType();
4304       break;
4305     case Type::Pointer:
4306       T = cast<PointerType>(Ty)->getPointeeType();
4307       break;
4308     case Type::BlockPointer:
4309       T = cast<BlockPointerType>(Ty)->getPointeeType();
4310       break;
4311     case Type::LValueReference:
4312     case Type::RValueReference:
4313       T = cast<ReferenceType>(Ty)->getPointeeType();
4314       break;
4315     case Type::MemberPointer:
4316       T = cast<MemberPointerType>(Ty)->getPointeeType();
4317       break;
4318     case Type::ConstantArray:
4319     case Type::IncompleteArray:
4320       // Losing element qualification here is fine.
4321       T = cast<ArrayType>(Ty)->getElementType();
4322       break;
4323     case Type::VariableArray: {
4324       // Losing element qualification here is fine.
4325       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4326 
4327       // Unknown size indication requires no size computation.
4328       // Otherwise, evaluate and record it.
4329       auto Size = VAT->getSizeExpr();
4330       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4331           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4332         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4333 
4334       T = VAT->getElementType();
4335       break;
4336     }
4337     case Type::FunctionProto:
4338     case Type::FunctionNoProto:
4339       T = cast<FunctionType>(Ty)->getReturnType();
4340       break;
4341     case Type::Paren:
4342     case Type::TypeOf:
4343     case Type::UnaryTransform:
4344     case Type::Attributed:
4345     case Type::SubstTemplateTypeParm:
4346     case Type::PackExpansion:
4347     case Type::MacroQualified:
4348       // Keep walking after single level desugaring.
4349       T = T.getSingleStepDesugaredType(Context);
4350       break;
4351     case Type::Typedef:
4352       T = cast<TypedefType>(Ty)->desugar();
4353       break;
4354     case Type::Decltype:
4355       T = cast<DecltypeType>(Ty)->desugar();
4356       break;
4357     case Type::Auto:
4358     case Type::DeducedTemplateSpecialization:
4359       T = cast<DeducedType>(Ty)->getDeducedType();
4360       break;
4361     case Type::TypeOfExpr:
4362       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4363       break;
4364     case Type::Atomic:
4365       T = cast<AtomicType>(Ty)->getValueType();
4366       break;
4367     }
4368   } while (!T.isNull() && T->isVariablyModifiedType());
4369 }
4370 
4371 /// Build a sizeof or alignof expression given a type operand.
4372 ExprResult
4373 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4374                                      SourceLocation OpLoc,
4375                                      UnaryExprOrTypeTrait ExprKind,
4376                                      SourceRange R) {
4377   if (!TInfo)
4378     return ExprError();
4379 
4380   QualType T = TInfo->getType();
4381 
4382   if (!T->isDependentType() &&
4383       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4384     return ExprError();
4385 
4386   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4387     if (auto *TT = T->getAs<TypedefType>()) {
4388       for (auto I = FunctionScopes.rbegin(),
4389                 E = std::prev(FunctionScopes.rend());
4390            I != E; ++I) {
4391         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4392         if (CSI == nullptr)
4393           break;
4394         DeclContext *DC = nullptr;
4395         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4396           DC = LSI->CallOperator;
4397         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4398           DC = CRSI->TheCapturedDecl;
4399         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4400           DC = BSI->TheDecl;
4401         if (DC) {
4402           if (DC->containsDecl(TT->getDecl()))
4403             break;
4404           captureVariablyModifiedType(Context, T, CSI);
4405         }
4406       }
4407     }
4408   }
4409 
4410   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4411   return new (Context) UnaryExprOrTypeTraitExpr(
4412       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4413 }
4414 
4415 /// Build a sizeof or alignof expression given an expression
4416 /// operand.
4417 ExprResult
4418 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4419                                      UnaryExprOrTypeTrait ExprKind) {
4420   ExprResult PE = CheckPlaceholderExpr(E);
4421   if (PE.isInvalid())
4422     return ExprError();
4423 
4424   E = PE.get();
4425 
4426   // Verify that the operand is valid.
4427   bool isInvalid = false;
4428   if (E->isTypeDependent()) {
4429     // Delay type-checking for type-dependent expressions.
4430   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4431     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4432   } else if (ExprKind == UETT_VecStep) {
4433     isInvalid = CheckVecStepExpr(E);
4434   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4435       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4436       isInvalid = true;
4437   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4438     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4439     isInvalid = true;
4440   } else {
4441     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4442   }
4443 
4444   if (isInvalid)
4445     return ExprError();
4446 
4447   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4448     PE = TransformToPotentiallyEvaluated(E);
4449     if (PE.isInvalid()) return ExprError();
4450     E = PE.get();
4451   }
4452 
4453   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4454   return new (Context) UnaryExprOrTypeTraitExpr(
4455       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4456 }
4457 
4458 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4459 /// expr and the same for @c alignof and @c __alignof
4460 /// Note that the ArgRange is invalid if isType is false.
4461 ExprResult
4462 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4463                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4464                                     void *TyOrEx, SourceRange ArgRange) {
4465   // If error parsing type, ignore.
4466   if (!TyOrEx) return ExprError();
4467 
4468   if (IsType) {
4469     TypeSourceInfo *TInfo;
4470     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4471     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4472   }
4473 
4474   Expr *ArgEx = (Expr *)TyOrEx;
4475   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4476   return Result;
4477 }
4478 
4479 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4480                                      bool IsReal) {
4481   if (V.get()->isTypeDependent())
4482     return S.Context.DependentTy;
4483 
4484   // _Real and _Imag are only l-values for normal l-values.
4485   if (V.get()->getObjectKind() != OK_Ordinary) {
4486     V = S.DefaultLvalueConversion(V.get());
4487     if (V.isInvalid())
4488       return QualType();
4489   }
4490 
4491   // These operators return the element type of a complex type.
4492   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4493     return CT->getElementType();
4494 
4495   // Otherwise they pass through real integer and floating point types here.
4496   if (V.get()->getType()->isArithmeticType())
4497     return V.get()->getType();
4498 
4499   // Test for placeholders.
4500   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4501   if (PR.isInvalid()) return QualType();
4502   if (PR.get() != V.get()) {
4503     V = PR;
4504     return CheckRealImagOperand(S, V, Loc, IsReal);
4505   }
4506 
4507   // Reject anything else.
4508   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4509     << (IsReal ? "__real" : "__imag");
4510   return QualType();
4511 }
4512 
4513 
4514 
4515 ExprResult
4516 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4517                           tok::TokenKind Kind, Expr *Input) {
4518   UnaryOperatorKind Opc;
4519   switch (Kind) {
4520   default: llvm_unreachable("Unknown unary op!");
4521   case tok::plusplus:   Opc = UO_PostInc; break;
4522   case tok::minusminus: Opc = UO_PostDec; break;
4523   }
4524 
4525   // Since this might is a postfix expression, get rid of ParenListExprs.
4526   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4527   if (Result.isInvalid()) return ExprError();
4528   Input = Result.get();
4529 
4530   return BuildUnaryOp(S, OpLoc, Opc, Input);
4531 }
4532 
4533 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4534 ///
4535 /// \return true on error
4536 static bool checkArithmeticOnObjCPointer(Sema &S,
4537                                          SourceLocation opLoc,
4538                                          Expr *op) {
4539   assert(op->getType()->isObjCObjectPointerType());
4540   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4541       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4542     return false;
4543 
4544   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4545     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4546     << op->getSourceRange();
4547   return true;
4548 }
4549 
4550 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4551   auto *BaseNoParens = Base->IgnoreParens();
4552   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4553     return MSProp->getPropertyDecl()->getType()->isArrayType();
4554   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4555 }
4556 
4557 ExprResult
4558 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4559                               Expr *idx, SourceLocation rbLoc) {
4560   if (base && !base->getType().isNull() &&
4561       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4562     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4563                                     /*Length=*/nullptr, rbLoc);
4564 
4565   // Since this might be a postfix expression, get rid of ParenListExprs.
4566   if (isa<ParenListExpr>(base)) {
4567     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4568     if (result.isInvalid()) return ExprError();
4569     base = result.get();
4570   }
4571 
4572   // Check if base and idx form a MatrixSubscriptExpr.
4573   //
4574   // Helper to check for comma expressions, which are not allowed as indices for
4575   // matrix subscript expressions.
4576   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4577     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4578       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4579           << SourceRange(base->getBeginLoc(), rbLoc);
4580       return true;
4581     }
4582     return false;
4583   };
4584   // The matrix subscript operator ([][])is considered a single operator.
4585   // Separating the index expressions by parenthesis is not allowed.
4586   if (base->getType()->isSpecificPlaceholderType(
4587           BuiltinType::IncompleteMatrixIdx) &&
4588       !isa<MatrixSubscriptExpr>(base)) {
4589     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4590         << SourceRange(base->getBeginLoc(), rbLoc);
4591     return ExprError();
4592   }
4593   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4594   // a new MatrixSubscriptExpr.
4595   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4596   if (matSubscriptE) {
4597     if (CheckAndReportCommaError(idx))
4598       return ExprError();
4599 
4600     assert(matSubscriptE->isIncomplete() &&
4601            "base has to be an incomplete matrix subscript");
4602     return CreateBuiltinMatrixSubscriptExpr(
4603         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4604   }
4605   Expr *matrixBase = base;
4606   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4607   if (!IsMSPropertySubscript) {
4608     ExprResult result = CheckPlaceholderExpr(base);
4609     if (!result.isInvalid())
4610       matrixBase = result.get();
4611   }
4612   if (matrixBase->getType()->isMatrixType()) {
4613     if (CheckAndReportCommaError(idx))
4614       return ExprError();
4615 
4616     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4617   }
4618 
4619   // A comma-expression as the index is deprecated in C++2a onwards.
4620   if (getLangOpts().CPlusPlus20 &&
4621       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4622        (isa<CXXOperatorCallExpr>(idx) &&
4623         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4624     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4625       << SourceRange(base->getBeginLoc(), rbLoc);
4626   }
4627 
4628   // Handle any non-overload placeholder types in the base and index
4629   // expressions.  We can't handle overloads here because the other
4630   // operand might be an overloadable type, in which case the overload
4631   // resolution for the operator overload should get the first crack
4632   // at the overload.
4633   if (base->getType()->isNonOverloadPlaceholderType()) {
4634     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4635     if (!IsMSPropertySubscript) {
4636       ExprResult result = CheckPlaceholderExpr(base);
4637       if (result.isInvalid())
4638         return ExprError();
4639       base = result.get();
4640     }
4641   }
4642   if (idx->getType()->isNonOverloadPlaceholderType()) {
4643     ExprResult result = CheckPlaceholderExpr(idx);
4644     if (result.isInvalid()) return ExprError();
4645     idx = result.get();
4646   }
4647 
4648   // Build an unanalyzed expression if either operand is type-dependent.
4649   if (getLangOpts().CPlusPlus &&
4650       (base->isTypeDependent() || idx->isTypeDependent())) {
4651     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4652                                             VK_LValue, OK_Ordinary, rbLoc);
4653   }
4654 
4655   // MSDN, property (C++)
4656   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4657   // This attribute can also be used in the declaration of an empty array in a
4658   // class or structure definition. For example:
4659   // __declspec(property(get=GetX, put=PutX)) int x[];
4660   // The above statement indicates that x[] can be used with one or more array
4661   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4662   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4663   if (IsMSPropertySubscript) {
4664     // Build MS property subscript expression if base is MS property reference
4665     // or MS property subscript.
4666     return new (Context) MSPropertySubscriptExpr(
4667         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4668   }
4669 
4670   // Use C++ overloaded-operator rules if either operand has record
4671   // type.  The spec says to do this if either type is *overloadable*,
4672   // but enum types can't declare subscript operators or conversion
4673   // operators, so there's nothing interesting for overload resolution
4674   // to do if there aren't any record types involved.
4675   //
4676   // ObjC pointers have their own subscripting logic that is not tied
4677   // to overload resolution and so should not take this path.
4678   if (getLangOpts().CPlusPlus &&
4679       (base->getType()->isRecordType() ||
4680        (!base->getType()->isObjCObjectPointerType() &&
4681         idx->getType()->isRecordType()))) {
4682     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4683   }
4684 
4685   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4686 
4687   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4688     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4689 
4690   return Res;
4691 }
4692 
4693 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4694   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4695   InitializationKind Kind =
4696       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4697   InitializationSequence InitSeq(*this, Entity, Kind, E);
4698   return InitSeq.Perform(*this, Entity, Kind, E);
4699 }
4700 
4701 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4702                                                   Expr *ColumnIdx,
4703                                                   SourceLocation RBLoc) {
4704   ExprResult BaseR = CheckPlaceholderExpr(Base);
4705   if (BaseR.isInvalid())
4706     return BaseR;
4707   Base = BaseR.get();
4708 
4709   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4710   if (RowR.isInvalid())
4711     return RowR;
4712   RowIdx = RowR.get();
4713 
4714   if (!ColumnIdx)
4715     return new (Context) MatrixSubscriptExpr(
4716         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4717 
4718   // Build an unanalyzed expression if any of the operands is type-dependent.
4719   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4720       ColumnIdx->isTypeDependent())
4721     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4722                                              Context.DependentTy, RBLoc);
4723 
4724   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4725   if (ColumnR.isInvalid())
4726     return ColumnR;
4727   ColumnIdx = ColumnR.get();
4728 
4729   // Check that IndexExpr is an integer expression. If it is a constant
4730   // expression, check that it is less than Dim (= the number of elements in the
4731   // corresponding dimension).
4732   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4733                           bool IsColumnIdx) -> Expr * {
4734     if (!IndexExpr->getType()->isIntegerType() &&
4735         !IndexExpr->isTypeDependent()) {
4736       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4737           << IsColumnIdx;
4738       return nullptr;
4739     }
4740 
4741     llvm::APSInt Idx;
4742     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4743         (Idx < 0 || Idx >= Dim)) {
4744       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4745           << IsColumnIdx << Dim;
4746       return nullptr;
4747     }
4748 
4749     ExprResult ConvExpr =
4750         tryConvertExprToType(IndexExpr, Context.getSizeType());
4751     assert(!ConvExpr.isInvalid() &&
4752            "should be able to convert any integer type to size type");
4753     return ConvExpr.get();
4754   };
4755 
4756   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4757   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4758   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4759   if (!RowIdx || !ColumnIdx)
4760     return ExprError();
4761 
4762   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4763                                            MTy->getElementType(), RBLoc);
4764 }
4765 
4766 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4767   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4768   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4769 
4770   // For expressions like `&(*s).b`, the base is recorded and what should be
4771   // checked.
4772   const MemberExpr *Member = nullptr;
4773   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4774     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4775 
4776   LastRecord.PossibleDerefs.erase(StrippedExpr);
4777 }
4778 
4779 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4780   QualType ResultTy = E->getType();
4781   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4782 
4783   // Bail if the element is an array since it is not memory access.
4784   if (isa<ArrayType>(ResultTy))
4785     return;
4786 
4787   if (ResultTy->hasAttr(attr::NoDeref)) {
4788     LastRecord.PossibleDerefs.insert(E);
4789     return;
4790   }
4791 
4792   // Check if the base type is a pointer to a member access of a struct
4793   // marked with noderef.
4794   const Expr *Base = E->getBase();
4795   QualType BaseTy = Base->getType();
4796   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4797     // Not a pointer access
4798     return;
4799 
4800   const MemberExpr *Member = nullptr;
4801   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4802          Member->isArrow())
4803     Base = Member->getBase();
4804 
4805   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4806     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4807       LastRecord.PossibleDerefs.insert(E);
4808   }
4809 }
4810 
4811 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4812                                           Expr *LowerBound,
4813                                           SourceLocation ColonLoc, Expr *Length,
4814                                           SourceLocation RBLoc) {
4815   if (Base->getType()->isPlaceholderType() &&
4816       !Base->getType()->isSpecificPlaceholderType(
4817           BuiltinType::OMPArraySection)) {
4818     ExprResult Result = CheckPlaceholderExpr(Base);
4819     if (Result.isInvalid())
4820       return ExprError();
4821     Base = Result.get();
4822   }
4823   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4824     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4825     if (Result.isInvalid())
4826       return ExprError();
4827     Result = DefaultLvalueConversion(Result.get());
4828     if (Result.isInvalid())
4829       return ExprError();
4830     LowerBound = Result.get();
4831   }
4832   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4833     ExprResult Result = CheckPlaceholderExpr(Length);
4834     if (Result.isInvalid())
4835       return ExprError();
4836     Result = DefaultLvalueConversion(Result.get());
4837     if (Result.isInvalid())
4838       return ExprError();
4839     Length = Result.get();
4840   }
4841 
4842   // Build an unanalyzed expression if either operand is type-dependent.
4843   if (Base->isTypeDependent() ||
4844       (LowerBound &&
4845        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4846       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4847     return new (Context)
4848         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4849                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4850   }
4851 
4852   // Perform default conversions.
4853   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4854   QualType ResultTy;
4855   if (OriginalTy->isAnyPointerType()) {
4856     ResultTy = OriginalTy->getPointeeType();
4857   } else if (OriginalTy->isArrayType()) {
4858     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4859   } else {
4860     return ExprError(
4861         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4862         << Base->getSourceRange());
4863   }
4864   // C99 6.5.2.1p1
4865   if (LowerBound) {
4866     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4867                                                       LowerBound);
4868     if (Res.isInvalid())
4869       return ExprError(Diag(LowerBound->getExprLoc(),
4870                             diag::err_omp_typecheck_section_not_integer)
4871                        << 0 << LowerBound->getSourceRange());
4872     LowerBound = Res.get();
4873 
4874     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4875         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4876       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4877           << 0 << LowerBound->getSourceRange();
4878   }
4879   if (Length) {
4880     auto Res =
4881         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4882     if (Res.isInvalid())
4883       return ExprError(Diag(Length->getExprLoc(),
4884                             diag::err_omp_typecheck_section_not_integer)
4885                        << 1 << Length->getSourceRange());
4886     Length = Res.get();
4887 
4888     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4889         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4890       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4891           << 1 << Length->getSourceRange();
4892   }
4893 
4894   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4895   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4896   // type. Note that functions are not objects, and that (in C99 parlance)
4897   // incomplete types are not object types.
4898   if (ResultTy->isFunctionType()) {
4899     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4900         << ResultTy << Base->getSourceRange();
4901     return ExprError();
4902   }
4903 
4904   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4905                           diag::err_omp_section_incomplete_type, Base))
4906     return ExprError();
4907 
4908   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4909     Expr::EvalResult Result;
4910     if (LowerBound->EvaluateAsInt(Result, Context)) {
4911       // OpenMP 4.5, [2.4 Array Sections]
4912       // The array section must be a subset of the original array.
4913       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4914       if (LowerBoundValue.isNegative()) {
4915         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4916             << LowerBound->getSourceRange();
4917         return ExprError();
4918       }
4919     }
4920   }
4921 
4922   if (Length) {
4923     Expr::EvalResult Result;
4924     if (Length->EvaluateAsInt(Result, Context)) {
4925       // OpenMP 4.5, [2.4 Array Sections]
4926       // The length must evaluate to non-negative integers.
4927       llvm::APSInt LengthValue = Result.Val.getInt();
4928       if (LengthValue.isNegative()) {
4929         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4930             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4931             << Length->getSourceRange();
4932         return ExprError();
4933       }
4934     }
4935   } else if (ColonLoc.isValid() &&
4936              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4937                                       !OriginalTy->isVariableArrayType()))) {
4938     // OpenMP 4.5, [2.4 Array Sections]
4939     // When the size of the array dimension is not known, the length must be
4940     // specified explicitly.
4941     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4942         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4943     return ExprError();
4944   }
4945 
4946   if (!Base->getType()->isSpecificPlaceholderType(
4947           BuiltinType::OMPArraySection)) {
4948     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4949     if (Result.isInvalid())
4950       return ExprError();
4951     Base = Result.get();
4952   }
4953   return new (Context)
4954       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4955                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4956 }
4957 
4958 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4959                                           SourceLocation RParenLoc,
4960                                           ArrayRef<Expr *> Dims,
4961                                           ArrayRef<SourceRange> Brackets) {
4962   if (Base->getType()->isPlaceholderType()) {
4963     ExprResult Result = CheckPlaceholderExpr(Base);
4964     if (Result.isInvalid())
4965       return ExprError();
4966     Result = DefaultLvalueConversion(Result.get());
4967     if (Result.isInvalid())
4968       return ExprError();
4969     Base = Result.get();
4970   }
4971   QualType BaseTy = Base->getType();
4972   // Delay analysis of the types/expressions if instantiation/specialization is
4973   // required.
4974   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4975     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4976                                        LParenLoc, RParenLoc, Dims, Brackets);
4977   if (!BaseTy->isPointerType() ||
4978       (!Base->isTypeDependent() &&
4979        BaseTy->getPointeeType()->isIncompleteType()))
4980     return ExprError(Diag(Base->getExprLoc(),
4981                           diag::err_omp_non_pointer_type_array_shaping_base)
4982                      << Base->getSourceRange());
4983 
4984   SmallVector<Expr *, 4> NewDims;
4985   bool ErrorFound = false;
4986   for (Expr *Dim : Dims) {
4987     if (Dim->getType()->isPlaceholderType()) {
4988       ExprResult Result = CheckPlaceholderExpr(Dim);
4989       if (Result.isInvalid()) {
4990         ErrorFound = true;
4991         continue;
4992       }
4993       Result = DefaultLvalueConversion(Result.get());
4994       if (Result.isInvalid()) {
4995         ErrorFound = true;
4996         continue;
4997       }
4998       Dim = Result.get();
4999     }
5000     if (!Dim->isTypeDependent()) {
5001       ExprResult Result =
5002           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5003       if (Result.isInvalid()) {
5004         ErrorFound = true;
5005         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5006             << Dim->getSourceRange();
5007         continue;
5008       }
5009       Dim = Result.get();
5010       Expr::EvalResult EvResult;
5011       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5012         // OpenMP 5.0, [2.1.4 Array Shaping]
5013         // Each si is an integral type expression that must evaluate to a
5014         // positive integer.
5015         llvm::APSInt Value = EvResult.Val.getInt();
5016         if (!Value.isStrictlyPositive()) {
5017           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5018               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5019               << Dim->getSourceRange();
5020           ErrorFound = true;
5021           continue;
5022         }
5023       }
5024     }
5025     NewDims.push_back(Dim);
5026   }
5027   if (ErrorFound)
5028     return ExprError();
5029   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5030                                      LParenLoc, RParenLoc, NewDims, Brackets);
5031 }
5032 
5033 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5034                                       SourceLocation LLoc, SourceLocation RLoc,
5035                                       ArrayRef<OMPIteratorData> Data) {
5036   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5037   bool IsCorrect = true;
5038   for (const OMPIteratorData &D : Data) {
5039     TypeSourceInfo *TInfo = nullptr;
5040     SourceLocation StartLoc;
5041     QualType DeclTy;
5042     if (!D.Type.getAsOpaquePtr()) {
5043       // OpenMP 5.0, 2.1.6 Iterators
5044       // In an iterator-specifier, if the iterator-type is not specified then
5045       // the type of that iterator is of int type.
5046       DeclTy = Context.IntTy;
5047       StartLoc = D.DeclIdentLoc;
5048     } else {
5049       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5050       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5051     }
5052 
5053     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5054                              DeclTy->containsUnexpandedParameterPack() ||
5055                              DeclTy->isInstantiationDependentType();
5056     if (!IsDeclTyDependent) {
5057       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5058         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5059         // The iterator-type must be an integral or pointer type.
5060         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5061             << DeclTy;
5062         IsCorrect = false;
5063         continue;
5064       }
5065       if (DeclTy.isConstant(Context)) {
5066         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5067         // The iterator-type must not be const qualified.
5068         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5069             << DeclTy;
5070         IsCorrect = false;
5071         continue;
5072       }
5073     }
5074 
5075     // Iterator declaration.
5076     assert(D.DeclIdent && "Identifier expected.");
5077     // Always try to create iterator declarator to avoid extra error messages
5078     // about unknown declarations use.
5079     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5080                                D.DeclIdent, DeclTy, TInfo, SC_None);
5081     VD->setImplicit();
5082     if (S) {
5083       // Check for conflicting previous declaration.
5084       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5085       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5086                             ForVisibleRedeclaration);
5087       Previous.suppressDiagnostics();
5088       LookupName(Previous, S);
5089 
5090       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5091                            /*AllowInlineNamespace=*/false);
5092       if (!Previous.empty()) {
5093         NamedDecl *Old = Previous.getRepresentativeDecl();
5094         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5095         Diag(Old->getLocation(), diag::note_previous_definition);
5096       } else {
5097         PushOnScopeChains(VD, S);
5098       }
5099     } else {
5100       CurContext->addDecl(VD);
5101     }
5102     Expr *Begin = D.Range.Begin;
5103     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5104       ExprResult BeginRes =
5105           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5106       Begin = BeginRes.get();
5107     }
5108     Expr *End = D.Range.End;
5109     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5110       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5111       End = EndRes.get();
5112     }
5113     Expr *Step = D.Range.Step;
5114     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5115       if (!Step->getType()->isIntegralType(Context)) {
5116         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5117             << Step << Step->getSourceRange();
5118         IsCorrect = false;
5119         continue;
5120       }
5121       llvm::APSInt Result;
5122       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5123       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5124       // If the step expression of a range-specification equals zero, the
5125       // behavior is unspecified.
5126       if (IsConstant && Result.isNullValue()) {
5127         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5128             << Step << Step->getSourceRange();
5129         IsCorrect = false;
5130         continue;
5131       }
5132     }
5133     if (!Begin || !End || !IsCorrect) {
5134       IsCorrect = false;
5135       continue;
5136     }
5137     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5138     IDElem.IteratorDecl = VD;
5139     IDElem.AssignmentLoc = D.AssignLoc;
5140     IDElem.Range.Begin = Begin;
5141     IDElem.Range.End = End;
5142     IDElem.Range.Step = Step;
5143     IDElem.ColonLoc = D.ColonLoc;
5144     IDElem.SecondColonLoc = D.SecColonLoc;
5145   }
5146   if (!IsCorrect) {
5147     // Invalidate all created iterator declarations if error is found.
5148     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5149       if (Decl *ID = D.IteratorDecl)
5150         ID->setInvalidDecl();
5151     }
5152     return ExprError();
5153   }
5154   SmallVector<OMPIteratorHelperData, 4> Helpers;
5155   if (!CurContext->isDependentContext()) {
5156     // Build number of ityeration for each iteration range.
5157     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5158     // ((Begini-Stepi-1-Endi) / -Stepi);
5159     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5160       // (Endi - Begini)
5161       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5162                                           D.Range.Begin);
5163       if(!Res.isUsable()) {
5164         IsCorrect = false;
5165         continue;
5166       }
5167       ExprResult St, St1;
5168       if (D.Range.Step) {
5169         St = D.Range.Step;
5170         // (Endi - Begini) + Stepi
5171         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5172         if (!Res.isUsable()) {
5173           IsCorrect = false;
5174           continue;
5175         }
5176         // (Endi - Begini) + Stepi - 1
5177         Res =
5178             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5179                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5180         if (!Res.isUsable()) {
5181           IsCorrect = false;
5182           continue;
5183         }
5184         // ((Endi - Begini) + Stepi - 1) / Stepi
5185         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5186         if (!Res.isUsable()) {
5187           IsCorrect = false;
5188           continue;
5189         }
5190         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5191         // (Begini - Endi)
5192         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5193                                              D.Range.Begin, D.Range.End);
5194         if (!Res1.isUsable()) {
5195           IsCorrect = false;
5196           continue;
5197         }
5198         // (Begini - Endi) - Stepi
5199         Res1 =
5200             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5201         if (!Res1.isUsable()) {
5202           IsCorrect = false;
5203           continue;
5204         }
5205         // (Begini - Endi) - Stepi - 1
5206         Res1 =
5207             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5208                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5209         if (!Res1.isUsable()) {
5210           IsCorrect = false;
5211           continue;
5212         }
5213         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5214         Res1 =
5215             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5216         if (!Res1.isUsable()) {
5217           IsCorrect = false;
5218           continue;
5219         }
5220         // Stepi > 0.
5221         ExprResult CmpRes =
5222             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5223                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5224         if (!CmpRes.isUsable()) {
5225           IsCorrect = false;
5226           continue;
5227         }
5228         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5229                                  Res.get(), Res1.get());
5230         if (!Res.isUsable()) {
5231           IsCorrect = false;
5232           continue;
5233         }
5234       }
5235       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5236       if (!Res.isUsable()) {
5237         IsCorrect = false;
5238         continue;
5239       }
5240 
5241       // Build counter update.
5242       // Build counter.
5243       auto *CounterVD =
5244           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5245                           D.IteratorDecl->getBeginLoc(), nullptr,
5246                           Res.get()->getType(), nullptr, SC_None);
5247       CounterVD->setImplicit();
5248       ExprResult RefRes =
5249           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5250                            D.IteratorDecl->getBeginLoc());
5251       // Build counter update.
5252       // I = Begini + counter * Stepi;
5253       ExprResult UpdateRes;
5254       if (D.Range.Step) {
5255         UpdateRes = CreateBuiltinBinOp(
5256             D.AssignmentLoc, BO_Mul,
5257             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5258       } else {
5259         UpdateRes = DefaultLvalueConversion(RefRes.get());
5260       }
5261       if (!UpdateRes.isUsable()) {
5262         IsCorrect = false;
5263         continue;
5264       }
5265       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5266                                      UpdateRes.get());
5267       if (!UpdateRes.isUsable()) {
5268         IsCorrect = false;
5269         continue;
5270       }
5271       ExprResult VDRes =
5272           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5273                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5274                            D.IteratorDecl->getBeginLoc());
5275       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5276                                      UpdateRes.get());
5277       if (!UpdateRes.isUsable()) {
5278         IsCorrect = false;
5279         continue;
5280       }
5281       UpdateRes =
5282           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5283       if (!UpdateRes.isUsable()) {
5284         IsCorrect = false;
5285         continue;
5286       }
5287       ExprResult CounterUpdateRes =
5288           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5289       if (!CounterUpdateRes.isUsable()) {
5290         IsCorrect = false;
5291         continue;
5292       }
5293       CounterUpdateRes =
5294           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5295       if (!CounterUpdateRes.isUsable()) {
5296         IsCorrect = false;
5297         continue;
5298       }
5299       OMPIteratorHelperData &HD = Helpers.emplace_back();
5300       HD.CounterVD = CounterVD;
5301       HD.Upper = Res.get();
5302       HD.Update = UpdateRes.get();
5303       HD.CounterUpdate = CounterUpdateRes.get();
5304     }
5305   } else {
5306     Helpers.assign(ID.size(), {});
5307   }
5308   if (!IsCorrect) {
5309     // Invalidate all created iterator declarations if error is found.
5310     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5311       if (Decl *ID = D.IteratorDecl)
5312         ID->setInvalidDecl();
5313     }
5314     return ExprError();
5315   }
5316   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5317                                  LLoc, RLoc, ID, Helpers);
5318 }
5319 
5320 ExprResult
5321 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5322                                       Expr *Idx, SourceLocation RLoc) {
5323   Expr *LHSExp = Base;
5324   Expr *RHSExp = Idx;
5325 
5326   ExprValueKind VK = VK_LValue;
5327   ExprObjectKind OK = OK_Ordinary;
5328 
5329   // Per C++ core issue 1213, the result is an xvalue if either operand is
5330   // a non-lvalue array, and an lvalue otherwise.
5331   if (getLangOpts().CPlusPlus11) {
5332     for (auto *Op : {LHSExp, RHSExp}) {
5333       Op = Op->IgnoreImplicit();
5334       if (Op->getType()->isArrayType() && !Op->isLValue())
5335         VK = VK_XValue;
5336     }
5337   }
5338 
5339   // Perform default conversions.
5340   if (!LHSExp->getType()->getAs<VectorType>()) {
5341     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5342     if (Result.isInvalid())
5343       return ExprError();
5344     LHSExp = Result.get();
5345   }
5346   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5347   if (Result.isInvalid())
5348     return ExprError();
5349   RHSExp = Result.get();
5350 
5351   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5352 
5353   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5354   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5355   // in the subscript position. As a result, we need to derive the array base
5356   // and index from the expression types.
5357   Expr *BaseExpr, *IndexExpr;
5358   QualType ResultType;
5359   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5360     BaseExpr = LHSExp;
5361     IndexExpr = RHSExp;
5362     ResultType = Context.DependentTy;
5363   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5364     BaseExpr = LHSExp;
5365     IndexExpr = RHSExp;
5366     ResultType = PTy->getPointeeType();
5367   } else if (const ObjCObjectPointerType *PTy =
5368                LHSTy->getAs<ObjCObjectPointerType>()) {
5369     BaseExpr = LHSExp;
5370     IndexExpr = RHSExp;
5371 
5372     // Use custom logic if this should be the pseudo-object subscript
5373     // expression.
5374     if (!LangOpts.isSubscriptPointerArithmetic())
5375       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5376                                           nullptr);
5377 
5378     ResultType = PTy->getPointeeType();
5379   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5380      // Handle the uncommon case of "123[Ptr]".
5381     BaseExpr = RHSExp;
5382     IndexExpr = LHSExp;
5383     ResultType = PTy->getPointeeType();
5384   } else if (const ObjCObjectPointerType *PTy =
5385                RHSTy->getAs<ObjCObjectPointerType>()) {
5386      // Handle the uncommon case of "123[Ptr]".
5387     BaseExpr = RHSExp;
5388     IndexExpr = LHSExp;
5389     ResultType = PTy->getPointeeType();
5390     if (!LangOpts.isSubscriptPointerArithmetic()) {
5391       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5392         << ResultType << BaseExpr->getSourceRange();
5393       return ExprError();
5394     }
5395   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5396     BaseExpr = LHSExp;    // vectors: V[123]
5397     IndexExpr = RHSExp;
5398     // We apply C++ DR1213 to vector subscripting too.
5399     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5400       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5401       if (Materialized.isInvalid())
5402         return ExprError();
5403       LHSExp = Materialized.get();
5404     }
5405     VK = LHSExp->getValueKind();
5406     if (VK != VK_RValue)
5407       OK = OK_VectorComponent;
5408 
5409     ResultType = VTy->getElementType();
5410     QualType BaseType = BaseExpr->getType();
5411     Qualifiers BaseQuals = BaseType.getQualifiers();
5412     Qualifiers MemberQuals = ResultType.getQualifiers();
5413     Qualifiers Combined = BaseQuals + MemberQuals;
5414     if (Combined != MemberQuals)
5415       ResultType = Context.getQualifiedType(ResultType, Combined);
5416   } else if (LHSTy->isArrayType()) {
5417     // If we see an array that wasn't promoted by
5418     // DefaultFunctionArrayLvalueConversion, it must be an array that
5419     // wasn't promoted because of the C90 rule that doesn't
5420     // allow promoting non-lvalue arrays.  Warn, then
5421     // force the promotion here.
5422     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5423         << LHSExp->getSourceRange();
5424     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5425                                CK_ArrayToPointerDecay).get();
5426     LHSTy = LHSExp->getType();
5427 
5428     BaseExpr = LHSExp;
5429     IndexExpr = RHSExp;
5430     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5431   } else if (RHSTy->isArrayType()) {
5432     // Same as previous, except for 123[f().a] case
5433     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5434         << RHSExp->getSourceRange();
5435     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5436                                CK_ArrayToPointerDecay).get();
5437     RHSTy = RHSExp->getType();
5438 
5439     BaseExpr = RHSExp;
5440     IndexExpr = LHSExp;
5441     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5442   } else {
5443     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5444        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5445   }
5446   // C99 6.5.2.1p1
5447   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5448     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5449                      << IndexExpr->getSourceRange());
5450 
5451   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5452        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5453          && !IndexExpr->isTypeDependent())
5454     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5455 
5456   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5457   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5458   // type. Note that Functions are not objects, and that (in C99 parlance)
5459   // incomplete types are not object types.
5460   if (ResultType->isFunctionType()) {
5461     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5462         << ResultType << BaseExpr->getSourceRange();
5463     return ExprError();
5464   }
5465 
5466   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5467     // GNU extension: subscripting on pointer to void
5468     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5469       << BaseExpr->getSourceRange();
5470 
5471     // C forbids expressions of unqualified void type from being l-values.
5472     // See IsCForbiddenLValueType.
5473     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5474   } else if (!ResultType->isDependentType() &&
5475              RequireCompleteSizedType(
5476                  LLoc, ResultType,
5477                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5478     return ExprError();
5479 
5480   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5481          !ResultType.isCForbiddenLValueType());
5482 
5483   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5484       FunctionScopes.size() > 1) {
5485     if (auto *TT =
5486             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5487       for (auto I = FunctionScopes.rbegin(),
5488                 E = std::prev(FunctionScopes.rend());
5489            I != E; ++I) {
5490         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5491         if (CSI == nullptr)
5492           break;
5493         DeclContext *DC = nullptr;
5494         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5495           DC = LSI->CallOperator;
5496         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5497           DC = CRSI->TheCapturedDecl;
5498         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5499           DC = BSI->TheDecl;
5500         if (DC) {
5501           if (DC->containsDecl(TT->getDecl()))
5502             break;
5503           captureVariablyModifiedType(
5504               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5505         }
5506       }
5507     }
5508   }
5509 
5510   return new (Context)
5511       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5512 }
5513 
5514 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5515                                   ParmVarDecl *Param) {
5516   if (Param->hasUnparsedDefaultArg()) {
5517     // If we've already cleared out the location for the default argument,
5518     // that means we're parsing it right now.
5519     if (!UnparsedDefaultArgLocs.count(Param)) {
5520       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5521       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5522       Param->setInvalidDecl();
5523       return true;
5524     }
5525 
5526     Diag(CallLoc,
5527          diag::err_use_of_default_argument_to_function_declared_later) <<
5528       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5529     Diag(UnparsedDefaultArgLocs[Param],
5530          diag::note_default_argument_declared_here);
5531     return true;
5532   }
5533 
5534   if (Param->hasUninstantiatedDefaultArg()) {
5535     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5536 
5537     EnterExpressionEvaluationContext EvalContext(
5538         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5539 
5540     // Instantiate the expression.
5541     //
5542     // FIXME: Pass in a correct Pattern argument, otherwise
5543     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5544     //
5545     // template<typename T>
5546     // struct A {
5547     //   static int FooImpl();
5548     //
5549     //   template<typename Tp>
5550     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5551     //   // template argument list [[T], [Tp]], should be [[Tp]].
5552     //   friend A<Tp> Foo(int a);
5553     // };
5554     //
5555     // template<typename T>
5556     // A<T> Foo(int a = A<T>::FooImpl());
5557     MultiLevelTemplateArgumentList MutiLevelArgList
5558       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5559 
5560     InstantiatingTemplate Inst(*this, CallLoc, Param,
5561                                MutiLevelArgList.getInnermost());
5562     if (Inst.isInvalid())
5563       return true;
5564     if (Inst.isAlreadyInstantiating()) {
5565       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5566       Param->setInvalidDecl();
5567       return true;
5568     }
5569 
5570     ExprResult Result;
5571     {
5572       // C++ [dcl.fct.default]p5:
5573       //   The names in the [default argument] expression are bound, and
5574       //   the semantic constraints are checked, at the point where the
5575       //   default argument expression appears.
5576       ContextRAII SavedContext(*this, FD);
5577       LocalInstantiationScope Local(*this);
5578       runWithSufficientStackSpace(CallLoc, [&] {
5579         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5580                                   /*DirectInit*/false);
5581       });
5582     }
5583     if (Result.isInvalid())
5584       return true;
5585 
5586     // Check the expression as an initializer for the parameter.
5587     InitializedEntity Entity
5588       = InitializedEntity::InitializeParameter(Context, Param);
5589     InitializationKind Kind = InitializationKind::CreateCopy(
5590         Param->getLocation(),
5591         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5592     Expr *ResultE = Result.getAs<Expr>();
5593 
5594     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5595     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5596     if (Result.isInvalid())
5597       return true;
5598 
5599     Result =
5600         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5601                             /*DiscardedValue*/ false);
5602     if (Result.isInvalid())
5603       return true;
5604 
5605     // Remember the instantiated default argument.
5606     Param->setDefaultArg(Result.getAs<Expr>());
5607     if (ASTMutationListener *L = getASTMutationListener()) {
5608       L->DefaultArgumentInstantiated(Param);
5609     }
5610   }
5611 
5612   assert(Param->hasInit() && "default argument but no initializer?");
5613 
5614   // If the default expression creates temporaries, we need to
5615   // push them to the current stack of expression temporaries so they'll
5616   // be properly destroyed.
5617   // FIXME: We should really be rebuilding the default argument with new
5618   // bound temporaries; see the comment in PR5810.
5619   // We don't need to do that with block decls, though, because
5620   // blocks in default argument expression can never capture anything.
5621   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5622     // Set the "needs cleanups" bit regardless of whether there are
5623     // any explicit objects.
5624     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5625 
5626     // Append all the objects to the cleanup list.  Right now, this
5627     // should always be a no-op, because blocks in default argument
5628     // expressions should never be able to capture anything.
5629     assert(!Init->getNumObjects() &&
5630            "default argument expression has capturing blocks?");
5631   }
5632 
5633   // We already type-checked the argument, so we know it works.
5634   // Just mark all of the declarations in this potentially-evaluated expression
5635   // as being "referenced".
5636   EnterExpressionEvaluationContext EvalContext(
5637       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5638   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5639                                    /*SkipLocalVariables=*/true);
5640   return false;
5641 }
5642 
5643 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5644                                         FunctionDecl *FD, ParmVarDecl *Param) {
5645   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5646   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5647     return ExprError();
5648   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5649 }
5650 
5651 Sema::VariadicCallType
5652 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5653                           Expr *Fn) {
5654   if (Proto && Proto->isVariadic()) {
5655     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5656       return VariadicConstructor;
5657     else if (Fn && Fn->getType()->isBlockPointerType())
5658       return VariadicBlock;
5659     else if (FDecl) {
5660       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5661         if (Method->isInstance())
5662           return VariadicMethod;
5663     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5664       return VariadicMethod;
5665     return VariadicFunction;
5666   }
5667   return VariadicDoesNotApply;
5668 }
5669 
5670 namespace {
5671 class FunctionCallCCC final : public FunctionCallFilterCCC {
5672 public:
5673   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5674                   unsigned NumArgs, MemberExpr *ME)
5675       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5676         FunctionName(FuncName) {}
5677 
5678   bool ValidateCandidate(const TypoCorrection &candidate) override {
5679     if (!candidate.getCorrectionSpecifier() ||
5680         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5681       return false;
5682     }
5683 
5684     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5685   }
5686 
5687   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5688     return std::make_unique<FunctionCallCCC>(*this);
5689   }
5690 
5691 private:
5692   const IdentifierInfo *const FunctionName;
5693 };
5694 }
5695 
5696 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5697                                                FunctionDecl *FDecl,
5698                                                ArrayRef<Expr *> Args) {
5699   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5700   DeclarationName FuncName = FDecl->getDeclName();
5701   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5702 
5703   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5704   if (TypoCorrection Corrected = S.CorrectTypo(
5705           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5706           S.getScopeForContext(S.CurContext), nullptr, CCC,
5707           Sema::CTK_ErrorRecovery)) {
5708     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5709       if (Corrected.isOverloaded()) {
5710         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5711         OverloadCandidateSet::iterator Best;
5712         for (NamedDecl *CD : Corrected) {
5713           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5714             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5715                                    OCS);
5716         }
5717         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5718         case OR_Success:
5719           ND = Best->FoundDecl;
5720           Corrected.setCorrectionDecl(ND);
5721           break;
5722         default:
5723           break;
5724         }
5725       }
5726       ND = ND->getUnderlyingDecl();
5727       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5728         return Corrected;
5729     }
5730   }
5731   return TypoCorrection();
5732 }
5733 
5734 /// ConvertArgumentsForCall - Converts the arguments specified in
5735 /// Args/NumArgs to the parameter types of the function FDecl with
5736 /// function prototype Proto. Call is the call expression itself, and
5737 /// Fn is the function expression. For a C++ member function, this
5738 /// routine does not attempt to convert the object argument. Returns
5739 /// true if the call is ill-formed.
5740 bool
5741 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5742                               FunctionDecl *FDecl,
5743                               const FunctionProtoType *Proto,
5744                               ArrayRef<Expr *> Args,
5745                               SourceLocation RParenLoc,
5746                               bool IsExecConfig) {
5747   // Bail out early if calling a builtin with custom typechecking.
5748   if (FDecl)
5749     if (unsigned ID = FDecl->getBuiltinID())
5750       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5751         return false;
5752 
5753   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5754   // assignment, to the types of the corresponding parameter, ...
5755   unsigned NumParams = Proto->getNumParams();
5756   bool Invalid = false;
5757   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5758   unsigned FnKind = Fn->getType()->isBlockPointerType()
5759                        ? 1 /* block */
5760                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5761                                        : 0 /* function */);
5762 
5763   // If too few arguments are available (and we don't have default
5764   // arguments for the remaining parameters), don't make the call.
5765   if (Args.size() < NumParams) {
5766     if (Args.size() < MinArgs) {
5767       TypoCorrection TC;
5768       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5769         unsigned diag_id =
5770             MinArgs == NumParams && !Proto->isVariadic()
5771                 ? diag::err_typecheck_call_too_few_args_suggest
5772                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5773         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5774                                         << static_cast<unsigned>(Args.size())
5775                                         << TC.getCorrectionRange());
5776       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5777         Diag(RParenLoc,
5778              MinArgs == NumParams && !Proto->isVariadic()
5779                  ? diag::err_typecheck_call_too_few_args_one
5780                  : diag::err_typecheck_call_too_few_args_at_least_one)
5781             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5782       else
5783         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5784                             ? diag::err_typecheck_call_too_few_args
5785                             : diag::err_typecheck_call_too_few_args_at_least)
5786             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5787             << Fn->getSourceRange();
5788 
5789       // Emit the location of the prototype.
5790       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5791         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5792 
5793       return true;
5794     }
5795     // We reserve space for the default arguments when we create
5796     // the call expression, before calling ConvertArgumentsForCall.
5797     assert((Call->getNumArgs() == NumParams) &&
5798            "We should have reserved space for the default arguments before!");
5799   }
5800 
5801   // If too many are passed and not variadic, error on the extras and drop
5802   // them.
5803   if (Args.size() > NumParams) {
5804     if (!Proto->isVariadic()) {
5805       TypoCorrection TC;
5806       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5807         unsigned diag_id =
5808             MinArgs == NumParams && !Proto->isVariadic()
5809                 ? diag::err_typecheck_call_too_many_args_suggest
5810                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5811         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5812                                         << static_cast<unsigned>(Args.size())
5813                                         << TC.getCorrectionRange());
5814       } else if (NumParams == 1 && FDecl &&
5815                  FDecl->getParamDecl(0)->getDeclName())
5816         Diag(Args[NumParams]->getBeginLoc(),
5817              MinArgs == NumParams
5818                  ? diag::err_typecheck_call_too_many_args_one
5819                  : diag::err_typecheck_call_too_many_args_at_most_one)
5820             << FnKind << FDecl->getParamDecl(0)
5821             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5822             << SourceRange(Args[NumParams]->getBeginLoc(),
5823                            Args.back()->getEndLoc());
5824       else
5825         Diag(Args[NumParams]->getBeginLoc(),
5826              MinArgs == NumParams
5827                  ? diag::err_typecheck_call_too_many_args
5828                  : diag::err_typecheck_call_too_many_args_at_most)
5829             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5830             << Fn->getSourceRange()
5831             << SourceRange(Args[NumParams]->getBeginLoc(),
5832                            Args.back()->getEndLoc());
5833 
5834       // Emit the location of the prototype.
5835       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5836         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5837 
5838       // This deletes the extra arguments.
5839       Call->shrinkNumArgs(NumParams);
5840       return true;
5841     }
5842   }
5843   SmallVector<Expr *, 8> AllArgs;
5844   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5845 
5846   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5847                                    AllArgs, CallType);
5848   if (Invalid)
5849     return true;
5850   unsigned TotalNumArgs = AllArgs.size();
5851   for (unsigned i = 0; i < TotalNumArgs; ++i)
5852     Call->setArg(i, AllArgs[i]);
5853 
5854   return false;
5855 }
5856 
5857 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5858                                   const FunctionProtoType *Proto,
5859                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5860                                   SmallVectorImpl<Expr *> &AllArgs,
5861                                   VariadicCallType CallType, bool AllowExplicit,
5862                                   bool IsListInitialization) {
5863   unsigned NumParams = Proto->getNumParams();
5864   bool Invalid = false;
5865   size_t ArgIx = 0;
5866   // Continue to check argument types (even if we have too few/many args).
5867   for (unsigned i = FirstParam; i < NumParams; i++) {
5868     QualType ProtoArgType = Proto->getParamType(i);
5869 
5870     Expr *Arg;
5871     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5872     if (ArgIx < Args.size()) {
5873       Arg = Args[ArgIx++];
5874 
5875       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5876                               diag::err_call_incomplete_argument, Arg))
5877         return true;
5878 
5879       // Strip the unbridged-cast placeholder expression off, if applicable.
5880       bool CFAudited = false;
5881       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5882           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5883           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5884         Arg = stripARCUnbridgedCast(Arg);
5885       else if (getLangOpts().ObjCAutoRefCount &&
5886                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5887                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5888         CFAudited = true;
5889 
5890       if (Proto->getExtParameterInfo(i).isNoEscape())
5891         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5892           BE->getBlockDecl()->setDoesNotEscape();
5893 
5894       InitializedEntity Entity =
5895           Param ? InitializedEntity::InitializeParameter(Context, Param,
5896                                                          ProtoArgType)
5897                 : InitializedEntity::InitializeParameter(
5898                       Context, ProtoArgType, Proto->isParamConsumed(i));
5899 
5900       // Remember that parameter belongs to a CF audited API.
5901       if (CFAudited)
5902         Entity.setParameterCFAudited();
5903 
5904       ExprResult ArgE = PerformCopyInitialization(
5905           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5906       if (ArgE.isInvalid())
5907         return true;
5908 
5909       Arg = ArgE.getAs<Expr>();
5910     } else {
5911       assert(Param && "can't use default arguments without a known callee");
5912 
5913       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5914       if (ArgExpr.isInvalid())
5915         return true;
5916 
5917       Arg = ArgExpr.getAs<Expr>();
5918     }
5919 
5920     // Check for array bounds violations for each argument to the call. This
5921     // check only triggers warnings when the argument isn't a more complex Expr
5922     // with its own checking, such as a BinaryOperator.
5923     CheckArrayAccess(Arg);
5924 
5925     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5926     CheckStaticArrayArgument(CallLoc, Param, Arg);
5927 
5928     AllArgs.push_back(Arg);
5929   }
5930 
5931   // If this is a variadic call, handle args passed through "...".
5932   if (CallType != VariadicDoesNotApply) {
5933     // Assume that extern "C" functions with variadic arguments that
5934     // return __unknown_anytype aren't *really* variadic.
5935     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5936         FDecl->isExternC()) {
5937       for (Expr *A : Args.slice(ArgIx)) {
5938         QualType paramType; // ignored
5939         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5940         Invalid |= arg.isInvalid();
5941         AllArgs.push_back(arg.get());
5942       }
5943 
5944     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5945     } else {
5946       for (Expr *A : Args.slice(ArgIx)) {
5947         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5948         Invalid |= Arg.isInvalid();
5949         AllArgs.push_back(Arg.get());
5950       }
5951     }
5952 
5953     // Check for array bounds violations.
5954     for (Expr *A : Args.slice(ArgIx))
5955       CheckArrayAccess(A);
5956   }
5957   return Invalid;
5958 }
5959 
5960 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5961   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5962   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5963     TL = DTL.getOriginalLoc();
5964   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5965     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5966       << ATL.getLocalSourceRange();
5967 }
5968 
5969 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5970 /// array parameter, check that it is non-null, and that if it is formed by
5971 /// array-to-pointer decay, the underlying array is sufficiently large.
5972 ///
5973 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5974 /// array type derivation, then for each call to the function, the value of the
5975 /// corresponding actual argument shall provide access to the first element of
5976 /// an array with at least as many elements as specified by the size expression.
5977 void
5978 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5979                                ParmVarDecl *Param,
5980                                const Expr *ArgExpr) {
5981   // Static array parameters are not supported in C++.
5982   if (!Param || getLangOpts().CPlusPlus)
5983     return;
5984 
5985   QualType OrigTy = Param->getOriginalType();
5986 
5987   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5988   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5989     return;
5990 
5991   if (ArgExpr->isNullPointerConstant(Context,
5992                                      Expr::NPC_NeverValueDependent)) {
5993     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5994     DiagnoseCalleeStaticArrayParam(*this, Param);
5995     return;
5996   }
5997 
5998   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5999   if (!CAT)
6000     return;
6001 
6002   const ConstantArrayType *ArgCAT =
6003     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6004   if (!ArgCAT)
6005     return;
6006 
6007   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6008                                              ArgCAT->getElementType())) {
6009     if (ArgCAT->getSize().ult(CAT->getSize())) {
6010       Diag(CallLoc, diag::warn_static_array_too_small)
6011           << ArgExpr->getSourceRange()
6012           << (unsigned)ArgCAT->getSize().getZExtValue()
6013           << (unsigned)CAT->getSize().getZExtValue() << 0;
6014       DiagnoseCalleeStaticArrayParam(*this, Param);
6015     }
6016     return;
6017   }
6018 
6019   Optional<CharUnits> ArgSize =
6020       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6021   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6022   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6023     Diag(CallLoc, diag::warn_static_array_too_small)
6024         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6025         << (unsigned)ParmSize->getQuantity() << 1;
6026     DiagnoseCalleeStaticArrayParam(*this, Param);
6027   }
6028 }
6029 
6030 /// Given a function expression of unknown-any type, try to rebuild it
6031 /// to have a function type.
6032 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6033 
6034 /// Is the given type a placeholder that we need to lower out
6035 /// immediately during argument processing?
6036 static bool isPlaceholderToRemoveAsArg(QualType type) {
6037   // Placeholders are never sugared.
6038   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6039   if (!placeholder) return false;
6040 
6041   switch (placeholder->getKind()) {
6042   // Ignore all the non-placeholder types.
6043 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6044   case BuiltinType::Id:
6045 #include "clang/Basic/OpenCLImageTypes.def"
6046 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6047   case BuiltinType::Id:
6048 #include "clang/Basic/OpenCLExtensionTypes.def"
6049   // In practice we'll never use this, since all SVE types are sugared
6050   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6051 #define SVE_TYPE(Name, Id, SingletonId) \
6052   case BuiltinType::Id:
6053 #include "clang/Basic/AArch64SVEACLETypes.def"
6054 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6055 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6056 #include "clang/AST/BuiltinTypes.def"
6057     return false;
6058 
6059   // We cannot lower out overload sets; they might validly be resolved
6060   // by the call machinery.
6061   case BuiltinType::Overload:
6062     return false;
6063 
6064   // Unbridged casts in ARC can be handled in some call positions and
6065   // should be left in place.
6066   case BuiltinType::ARCUnbridgedCast:
6067     return false;
6068 
6069   // Pseudo-objects should be converted as soon as possible.
6070   case BuiltinType::PseudoObject:
6071     return true;
6072 
6073   // The debugger mode could theoretically but currently does not try
6074   // to resolve unknown-typed arguments based on known parameter types.
6075   case BuiltinType::UnknownAny:
6076     return true;
6077 
6078   // These are always invalid as call arguments and should be reported.
6079   case BuiltinType::BoundMember:
6080   case BuiltinType::BuiltinFn:
6081   case BuiltinType::IncompleteMatrixIdx:
6082   case BuiltinType::OMPArraySection:
6083   case BuiltinType::OMPArrayShaping:
6084   case BuiltinType::OMPIterator:
6085     return true;
6086 
6087   }
6088   llvm_unreachable("bad builtin type kind");
6089 }
6090 
6091 /// Check an argument list for placeholders that we won't try to
6092 /// handle later.
6093 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6094   // Apply this processing to all the arguments at once instead of
6095   // dying at the first failure.
6096   bool hasInvalid = false;
6097   for (size_t i = 0, e = args.size(); i != e; i++) {
6098     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6099       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6100       if (result.isInvalid()) hasInvalid = true;
6101       else args[i] = result.get();
6102     } else if (hasInvalid) {
6103       (void)S.CorrectDelayedTyposInExpr(args[i]);
6104     }
6105   }
6106   return hasInvalid;
6107 }
6108 
6109 /// If a builtin function has a pointer argument with no explicit address
6110 /// space, then it should be able to accept a pointer to any address
6111 /// space as input.  In order to do this, we need to replace the
6112 /// standard builtin declaration with one that uses the same address space
6113 /// as the call.
6114 ///
6115 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6116 ///                  it does not contain any pointer arguments without
6117 ///                  an address space qualifer.  Otherwise the rewritten
6118 ///                  FunctionDecl is returned.
6119 /// TODO: Handle pointer return types.
6120 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6121                                                 FunctionDecl *FDecl,
6122                                                 MultiExprArg ArgExprs) {
6123 
6124   QualType DeclType = FDecl->getType();
6125   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6126 
6127   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6128       ArgExprs.size() < FT->getNumParams())
6129     return nullptr;
6130 
6131   bool NeedsNewDecl = false;
6132   unsigned i = 0;
6133   SmallVector<QualType, 8> OverloadParams;
6134 
6135   for (QualType ParamType : FT->param_types()) {
6136 
6137     // Convert array arguments to pointer to simplify type lookup.
6138     ExprResult ArgRes =
6139         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6140     if (ArgRes.isInvalid())
6141       return nullptr;
6142     Expr *Arg = ArgRes.get();
6143     QualType ArgType = Arg->getType();
6144     if (!ParamType->isPointerType() ||
6145         ParamType.hasAddressSpace() ||
6146         !ArgType->isPointerType() ||
6147         !ArgType->getPointeeType().hasAddressSpace()) {
6148       OverloadParams.push_back(ParamType);
6149       continue;
6150     }
6151 
6152     QualType PointeeType = ParamType->getPointeeType();
6153     if (PointeeType.hasAddressSpace())
6154       continue;
6155 
6156     NeedsNewDecl = true;
6157     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6158 
6159     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6160     OverloadParams.push_back(Context.getPointerType(PointeeType));
6161   }
6162 
6163   if (!NeedsNewDecl)
6164     return nullptr;
6165 
6166   FunctionProtoType::ExtProtoInfo EPI;
6167   EPI.Variadic = FT->isVariadic();
6168   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6169                                                 OverloadParams, EPI);
6170   DeclContext *Parent = FDecl->getParent();
6171   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6172                                                     FDecl->getLocation(),
6173                                                     FDecl->getLocation(),
6174                                                     FDecl->getIdentifier(),
6175                                                     OverloadTy,
6176                                                     /*TInfo=*/nullptr,
6177                                                     SC_Extern, false,
6178                                                     /*hasPrototype=*/true);
6179   SmallVector<ParmVarDecl*, 16> Params;
6180   FT = cast<FunctionProtoType>(OverloadTy);
6181   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6182     QualType ParamType = FT->getParamType(i);
6183     ParmVarDecl *Parm =
6184         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6185                                 SourceLocation(), nullptr, ParamType,
6186                                 /*TInfo=*/nullptr, SC_None, nullptr);
6187     Parm->setScopeInfo(0, i);
6188     Params.push_back(Parm);
6189   }
6190   OverloadDecl->setParams(Params);
6191   return OverloadDecl;
6192 }
6193 
6194 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6195                                     FunctionDecl *Callee,
6196                                     MultiExprArg ArgExprs) {
6197   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6198   // similar attributes) really don't like it when functions are called with an
6199   // invalid number of args.
6200   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6201                          /*PartialOverloading=*/false) &&
6202       !Callee->isVariadic())
6203     return;
6204   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6205     return;
6206 
6207   if (const EnableIfAttr *Attr =
6208           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6209     S.Diag(Fn->getBeginLoc(),
6210            isa<CXXMethodDecl>(Callee)
6211                ? diag::err_ovl_no_viable_member_function_in_call
6212                : diag::err_ovl_no_viable_function_in_call)
6213         << Callee << Callee->getSourceRange();
6214     S.Diag(Callee->getLocation(),
6215            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6216         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6217     return;
6218   }
6219 }
6220 
6221 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6222     const UnresolvedMemberExpr *const UME, Sema &S) {
6223 
6224   const auto GetFunctionLevelDCIfCXXClass =
6225       [](Sema &S) -> const CXXRecordDecl * {
6226     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6227     if (!DC || !DC->getParent())
6228       return nullptr;
6229 
6230     // If the call to some member function was made from within a member
6231     // function body 'M' return return 'M's parent.
6232     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6233       return MD->getParent()->getCanonicalDecl();
6234     // else the call was made from within a default member initializer of a
6235     // class, so return the class.
6236     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6237       return RD->getCanonicalDecl();
6238     return nullptr;
6239   };
6240   // If our DeclContext is neither a member function nor a class (in the
6241   // case of a lambda in a default member initializer), we can't have an
6242   // enclosing 'this'.
6243 
6244   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6245   if (!CurParentClass)
6246     return false;
6247 
6248   // The naming class for implicit member functions call is the class in which
6249   // name lookup starts.
6250   const CXXRecordDecl *const NamingClass =
6251       UME->getNamingClass()->getCanonicalDecl();
6252   assert(NamingClass && "Must have naming class even for implicit access");
6253 
6254   // If the unresolved member functions were found in a 'naming class' that is
6255   // related (either the same or derived from) to the class that contains the
6256   // member function that itself contained the implicit member access.
6257 
6258   return CurParentClass == NamingClass ||
6259          CurParentClass->isDerivedFrom(NamingClass);
6260 }
6261 
6262 static void
6263 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6264     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6265 
6266   if (!UME)
6267     return;
6268 
6269   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6270   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6271   // already been captured, or if this is an implicit member function call (if
6272   // it isn't, an attempt to capture 'this' should already have been made).
6273   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6274       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6275     return;
6276 
6277   // Check if the naming class in which the unresolved members were found is
6278   // related (same as or is a base of) to the enclosing class.
6279 
6280   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6281     return;
6282 
6283 
6284   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6285   // If the enclosing function is not dependent, then this lambda is
6286   // capture ready, so if we can capture this, do so.
6287   if (!EnclosingFunctionCtx->isDependentContext()) {
6288     // If the current lambda and all enclosing lambdas can capture 'this' -
6289     // then go ahead and capture 'this' (since our unresolved overload set
6290     // contains at least one non-static member function).
6291     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6292       S.CheckCXXThisCapture(CallLoc);
6293   } else if (S.CurContext->isDependentContext()) {
6294     // ... since this is an implicit member reference, that might potentially
6295     // involve a 'this' capture, mark 'this' for potential capture in
6296     // enclosing lambdas.
6297     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6298       CurLSI->addPotentialThisCapture(CallLoc);
6299   }
6300 }
6301 
6302 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6303                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6304                                Expr *ExecConfig) {
6305   ExprResult Call =
6306       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6307   if (Call.isInvalid())
6308     return Call;
6309 
6310   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6311   // language modes.
6312   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6313     if (ULE->hasExplicitTemplateArgs() &&
6314         ULE->decls_begin() == ULE->decls_end()) {
6315       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6316                                  ? diag::warn_cxx17_compat_adl_only_template_id
6317                                  : diag::ext_adl_only_template_id)
6318           << ULE->getName();
6319     }
6320   }
6321 
6322   if (LangOpts.OpenMP)
6323     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6324                            ExecConfig);
6325 
6326   return Call;
6327 }
6328 
6329 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6330 /// This provides the location of the left/right parens and a list of comma
6331 /// locations.
6332 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6333                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6334                                Expr *ExecConfig, bool IsExecConfig) {
6335   // Since this might be a postfix expression, get rid of ParenListExprs.
6336   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6337   if (Result.isInvalid()) return ExprError();
6338   Fn = Result.get();
6339 
6340   if (checkArgsForPlaceholders(*this, ArgExprs))
6341     return ExprError();
6342 
6343   if (getLangOpts().CPlusPlus) {
6344     // If this is a pseudo-destructor expression, build the call immediately.
6345     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6346       if (!ArgExprs.empty()) {
6347         // Pseudo-destructor calls should not have any arguments.
6348         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6349             << FixItHint::CreateRemoval(
6350                    SourceRange(ArgExprs.front()->getBeginLoc(),
6351                                ArgExprs.back()->getEndLoc()));
6352       }
6353 
6354       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6355                               VK_RValue, RParenLoc);
6356     }
6357     if (Fn->getType() == Context.PseudoObjectTy) {
6358       ExprResult result = CheckPlaceholderExpr(Fn);
6359       if (result.isInvalid()) return ExprError();
6360       Fn = result.get();
6361     }
6362 
6363     // Determine whether this is a dependent call inside a C++ template,
6364     // in which case we won't do any semantic analysis now.
6365     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6366       if (ExecConfig) {
6367         return CUDAKernelCallExpr::Create(
6368             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6369             Context.DependentTy, VK_RValue, RParenLoc);
6370       } else {
6371 
6372         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6373             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6374             Fn->getBeginLoc());
6375 
6376         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6377                                 VK_RValue, RParenLoc);
6378       }
6379     }
6380 
6381     // Determine whether this is a call to an object (C++ [over.call.object]).
6382     if (Fn->getType()->isRecordType())
6383       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6384                                           RParenLoc);
6385 
6386     if (Fn->getType() == Context.UnknownAnyTy) {
6387       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6388       if (result.isInvalid()) return ExprError();
6389       Fn = result.get();
6390     }
6391 
6392     if (Fn->getType() == Context.BoundMemberTy) {
6393       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6394                                        RParenLoc);
6395     }
6396   }
6397 
6398   // Check for overloaded calls.  This can happen even in C due to extensions.
6399   if (Fn->getType() == Context.OverloadTy) {
6400     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6401 
6402     // We aren't supposed to apply this logic if there's an '&' involved.
6403     if (!find.HasFormOfMemberPointer) {
6404       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6405         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6406                                 VK_RValue, RParenLoc);
6407       OverloadExpr *ovl = find.Expression;
6408       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6409         return BuildOverloadedCallExpr(
6410             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6411             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6412       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6413                                        RParenLoc);
6414     }
6415   }
6416 
6417   // If we're directly calling a function, get the appropriate declaration.
6418   if (Fn->getType() == Context.UnknownAnyTy) {
6419     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6420     if (result.isInvalid()) return ExprError();
6421     Fn = result.get();
6422   }
6423 
6424   Expr *NakedFn = Fn->IgnoreParens();
6425 
6426   bool CallingNDeclIndirectly = false;
6427   NamedDecl *NDecl = nullptr;
6428   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6429     if (UnOp->getOpcode() == UO_AddrOf) {
6430       CallingNDeclIndirectly = true;
6431       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6432     }
6433   }
6434 
6435   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6436     NDecl = DRE->getDecl();
6437 
6438     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6439     if (FDecl && FDecl->getBuiltinID()) {
6440       // Rewrite the function decl for this builtin by replacing parameters
6441       // with no explicit address space with the address space of the arguments
6442       // in ArgExprs.
6443       if ((FDecl =
6444                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6445         NDecl = FDecl;
6446         Fn = DeclRefExpr::Create(
6447             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6448             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6449             nullptr, DRE->isNonOdrUse());
6450       }
6451     }
6452   } else if (isa<MemberExpr>(NakedFn))
6453     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6454 
6455   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6456     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6457                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6458       return ExprError();
6459 
6460     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6461       return ExprError();
6462 
6463     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6464   }
6465 
6466   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6467                                ExecConfig, IsExecConfig);
6468 }
6469 
6470 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6471 ///
6472 /// __builtin_astype( value, dst type )
6473 ///
6474 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6475                                  SourceLocation BuiltinLoc,
6476                                  SourceLocation RParenLoc) {
6477   ExprValueKind VK = VK_RValue;
6478   ExprObjectKind OK = OK_Ordinary;
6479   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6480   QualType SrcTy = E->getType();
6481   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6482     return ExprError(Diag(BuiltinLoc,
6483                           diag::err_invalid_astype_of_different_size)
6484                      << DstTy
6485                      << SrcTy
6486                      << E->getSourceRange());
6487   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6488 }
6489 
6490 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6491 /// provided arguments.
6492 ///
6493 /// __builtin_convertvector( value, dst type )
6494 ///
6495 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6496                                         SourceLocation BuiltinLoc,
6497                                         SourceLocation RParenLoc) {
6498   TypeSourceInfo *TInfo;
6499   GetTypeFromParser(ParsedDestTy, &TInfo);
6500   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6501 }
6502 
6503 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6504 /// i.e. an expression not of \p OverloadTy.  The expression should
6505 /// unary-convert to an expression of function-pointer or
6506 /// block-pointer type.
6507 ///
6508 /// \param NDecl the declaration being called, if available
6509 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6510                                        SourceLocation LParenLoc,
6511                                        ArrayRef<Expr *> Args,
6512                                        SourceLocation RParenLoc, Expr *Config,
6513                                        bool IsExecConfig, ADLCallKind UsesADL) {
6514   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6515   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6516 
6517   // Functions with 'interrupt' attribute cannot be called directly.
6518   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6519     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6520     return ExprError();
6521   }
6522 
6523   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6524   // so there's some risk when calling out to non-interrupt handler functions
6525   // that the callee might not preserve them. This is easy to diagnose here,
6526   // but can be very challenging to debug.
6527   if (auto *Caller = getCurFunctionDecl())
6528     if (Caller->hasAttr<ARMInterruptAttr>()) {
6529       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6530       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6531         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6532     }
6533 
6534   // Promote the function operand.
6535   // We special-case function promotion here because we only allow promoting
6536   // builtin functions to function pointers in the callee of a call.
6537   ExprResult Result;
6538   QualType ResultTy;
6539   if (BuiltinID &&
6540       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6541     // Extract the return type from the (builtin) function pointer type.
6542     // FIXME Several builtins still have setType in
6543     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6544     // Builtins.def to ensure they are correct before removing setType calls.
6545     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6546     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6547     ResultTy = FDecl->getCallResultType();
6548   } else {
6549     Result = CallExprUnaryConversions(Fn);
6550     ResultTy = Context.BoolTy;
6551   }
6552   if (Result.isInvalid())
6553     return ExprError();
6554   Fn = Result.get();
6555 
6556   // Check for a valid function type, but only if it is not a builtin which
6557   // requires custom type checking. These will be handled by
6558   // CheckBuiltinFunctionCall below just after creation of the call expression.
6559   const FunctionType *FuncT = nullptr;
6560   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6561   retry:
6562     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6563       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6564       // have type pointer to function".
6565       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6566       if (!FuncT)
6567         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6568                          << Fn->getType() << Fn->getSourceRange());
6569     } else if (const BlockPointerType *BPT =
6570                    Fn->getType()->getAs<BlockPointerType>()) {
6571       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6572     } else {
6573       // Handle calls to expressions of unknown-any type.
6574       if (Fn->getType() == Context.UnknownAnyTy) {
6575         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6576         if (rewrite.isInvalid())
6577           return ExprError();
6578         Fn = rewrite.get();
6579         goto retry;
6580       }
6581 
6582       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6583                        << Fn->getType() << Fn->getSourceRange());
6584     }
6585   }
6586 
6587   // Get the number of parameters in the function prototype, if any.
6588   // We will allocate space for max(Args.size(), NumParams) arguments
6589   // in the call expression.
6590   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6591   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6592 
6593   CallExpr *TheCall;
6594   if (Config) {
6595     assert(UsesADL == ADLCallKind::NotADL &&
6596            "CUDAKernelCallExpr should not use ADL");
6597     TheCall =
6598         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6599                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6600   } else {
6601     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6602                                RParenLoc, NumParams, UsesADL);
6603   }
6604 
6605   if (!getLangOpts().CPlusPlus) {
6606     // Forget about the nulled arguments since typo correction
6607     // do not handle them well.
6608     TheCall->shrinkNumArgs(Args.size());
6609     // C cannot always handle TypoExpr nodes in builtin calls and direct
6610     // function calls as their argument checking don't necessarily handle
6611     // dependent types properly, so make sure any TypoExprs have been
6612     // dealt with.
6613     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6614     if (!Result.isUsable()) return ExprError();
6615     CallExpr *TheOldCall = TheCall;
6616     TheCall = dyn_cast<CallExpr>(Result.get());
6617     bool CorrectedTypos = TheCall != TheOldCall;
6618     if (!TheCall) return Result;
6619     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6620 
6621     // A new call expression node was created if some typos were corrected.
6622     // However it may not have been constructed with enough storage. In this
6623     // case, rebuild the node with enough storage. The waste of space is
6624     // immaterial since this only happens when some typos were corrected.
6625     if (CorrectedTypos && Args.size() < NumParams) {
6626       if (Config)
6627         TheCall = CUDAKernelCallExpr::Create(
6628             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6629             RParenLoc, NumParams);
6630       else
6631         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6632                                    RParenLoc, NumParams, UsesADL);
6633     }
6634     // We can now handle the nulled arguments for the default arguments.
6635     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6636   }
6637 
6638   // Bail out early if calling a builtin with custom type checking.
6639   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6640     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6641 
6642   if (getLangOpts().CUDA) {
6643     if (Config) {
6644       // CUDA: Kernel calls must be to global functions
6645       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6646         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6647             << FDecl << Fn->getSourceRange());
6648 
6649       // CUDA: Kernel function must have 'void' return type
6650       if (!FuncT->getReturnType()->isVoidType() &&
6651           !FuncT->getReturnType()->getAs<AutoType>() &&
6652           !FuncT->getReturnType()->isInstantiationDependentType())
6653         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6654             << Fn->getType() << Fn->getSourceRange());
6655     } else {
6656       // CUDA: Calls to global functions must be configured
6657       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6658         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6659             << FDecl << Fn->getSourceRange());
6660     }
6661   }
6662 
6663   // Check for a valid return type
6664   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6665                           FDecl))
6666     return ExprError();
6667 
6668   // We know the result type of the call, set it.
6669   TheCall->setType(FuncT->getCallResultType(Context));
6670   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6671 
6672   if (Proto) {
6673     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6674                                 IsExecConfig))
6675       return ExprError();
6676   } else {
6677     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6678 
6679     if (FDecl) {
6680       // Check if we have too few/too many template arguments, based
6681       // on our knowledge of the function definition.
6682       const FunctionDecl *Def = nullptr;
6683       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6684         Proto = Def->getType()->getAs<FunctionProtoType>();
6685        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6686           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6687           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6688       }
6689 
6690       // If the function we're calling isn't a function prototype, but we have
6691       // a function prototype from a prior declaratiom, use that prototype.
6692       if (!FDecl->hasPrototype())
6693         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6694     }
6695 
6696     // Promote the arguments (C99 6.5.2.2p6).
6697     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6698       Expr *Arg = Args[i];
6699 
6700       if (Proto && i < Proto->getNumParams()) {
6701         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6702             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6703         ExprResult ArgE =
6704             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6705         if (ArgE.isInvalid())
6706           return true;
6707 
6708         Arg = ArgE.getAs<Expr>();
6709 
6710       } else {
6711         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6712 
6713         if (ArgE.isInvalid())
6714           return true;
6715 
6716         Arg = ArgE.getAs<Expr>();
6717       }
6718 
6719       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6720                               diag::err_call_incomplete_argument, Arg))
6721         return ExprError();
6722 
6723       TheCall->setArg(i, Arg);
6724     }
6725   }
6726 
6727   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6728     if (!Method->isStatic())
6729       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6730         << Fn->getSourceRange());
6731 
6732   // Check for sentinels
6733   if (NDecl)
6734     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6735 
6736   // Warn for unions passing across security boundary (CMSE).
6737   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6738     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6739       if (const auto *RT =
6740               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6741         if (RT->getDecl()->isOrContainsUnion())
6742           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6743               << 0 << i;
6744       }
6745     }
6746   }
6747 
6748   // Do special checking on direct calls to functions.
6749   if (FDecl) {
6750     if (CheckFunctionCall(FDecl, TheCall, Proto))
6751       return ExprError();
6752 
6753     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6754 
6755     if (BuiltinID)
6756       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6757   } else if (NDecl) {
6758     if (CheckPointerCall(NDecl, TheCall, Proto))
6759       return ExprError();
6760   } else {
6761     if (CheckOtherCall(TheCall, Proto))
6762       return ExprError();
6763   }
6764 
6765   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6766 }
6767 
6768 ExprResult
6769 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6770                            SourceLocation RParenLoc, Expr *InitExpr) {
6771   assert(Ty && "ActOnCompoundLiteral(): missing type");
6772   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6773 
6774   TypeSourceInfo *TInfo;
6775   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6776   if (!TInfo)
6777     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6778 
6779   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6780 }
6781 
6782 ExprResult
6783 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6784                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6785   QualType literalType = TInfo->getType();
6786 
6787   if (literalType->isArrayType()) {
6788     if (RequireCompleteSizedType(
6789             LParenLoc, Context.getBaseElementType(literalType),
6790             diag::err_array_incomplete_or_sizeless_type,
6791             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6792       return ExprError();
6793     if (literalType->isVariableArrayType())
6794       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6795         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6796   } else if (!literalType->isDependentType() &&
6797              RequireCompleteType(LParenLoc, literalType,
6798                diag::err_typecheck_decl_incomplete_type,
6799                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6800     return ExprError();
6801 
6802   InitializedEntity Entity
6803     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6804   InitializationKind Kind
6805     = InitializationKind::CreateCStyleCast(LParenLoc,
6806                                            SourceRange(LParenLoc, RParenLoc),
6807                                            /*InitList=*/true);
6808   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6809   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6810                                       &literalType);
6811   if (Result.isInvalid())
6812     return ExprError();
6813   LiteralExpr = Result.get();
6814 
6815   bool isFileScope = !CurContext->isFunctionOrMethod();
6816 
6817   // In C, compound literals are l-values for some reason.
6818   // For GCC compatibility, in C++, file-scope array compound literals with
6819   // constant initializers are also l-values, and compound literals are
6820   // otherwise prvalues.
6821   //
6822   // (GCC also treats C++ list-initialized file-scope array prvalues with
6823   // constant initializers as l-values, but that's non-conforming, so we don't
6824   // follow it there.)
6825   //
6826   // FIXME: It would be better to handle the lvalue cases as materializing and
6827   // lifetime-extending a temporary object, but our materialized temporaries
6828   // representation only supports lifetime extension from a variable, not "out
6829   // of thin air".
6830   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6831   // is bound to the result of applying array-to-pointer decay to the compound
6832   // literal.
6833   // FIXME: GCC supports compound literals of reference type, which should
6834   // obviously have a value kind derived from the kind of reference involved.
6835   ExprValueKind VK =
6836       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6837           ? VK_RValue
6838           : VK_LValue;
6839 
6840   if (isFileScope)
6841     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6842       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6843         Expr *Init = ILE->getInit(i);
6844         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6845       }
6846 
6847   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6848                                               VK, LiteralExpr, isFileScope);
6849   if (isFileScope) {
6850     if (!LiteralExpr->isTypeDependent() &&
6851         !LiteralExpr->isValueDependent() &&
6852         !literalType->isDependentType()) // C99 6.5.2.5p3
6853       if (CheckForConstantInitializer(LiteralExpr, literalType))
6854         return ExprError();
6855   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6856              literalType.getAddressSpace() != LangAS::Default) {
6857     // Embedded-C extensions to C99 6.5.2.5:
6858     //   "If the compound literal occurs inside the body of a function, the
6859     //   type name shall not be qualified by an address-space qualifier."
6860     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6861       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6862     return ExprError();
6863   }
6864 
6865   if (!isFileScope && !getLangOpts().CPlusPlus) {
6866     // Compound literals that have automatic storage duration are destroyed at
6867     // the end of the scope in C; in C++, they're just temporaries.
6868 
6869     // Emit diagnostics if it is or contains a C union type that is non-trivial
6870     // to destruct.
6871     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6872       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6873                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6874 
6875     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6876     if (literalType.isDestructedType()) {
6877       Cleanup.setExprNeedsCleanups(true);
6878       ExprCleanupObjects.push_back(E);
6879       getCurFunction()->setHasBranchProtectedScope();
6880     }
6881   }
6882 
6883   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6884       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6885     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6886                                        E->getInitializer()->getExprLoc());
6887 
6888   return MaybeBindToTemporary(E);
6889 }
6890 
6891 ExprResult
6892 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6893                     SourceLocation RBraceLoc) {
6894   // Only produce each kind of designated initialization diagnostic once.
6895   SourceLocation FirstDesignator;
6896   bool DiagnosedArrayDesignator = false;
6897   bool DiagnosedNestedDesignator = false;
6898   bool DiagnosedMixedDesignator = false;
6899 
6900   // Check that any designated initializers are syntactically valid in the
6901   // current language mode.
6902   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6903     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6904       if (FirstDesignator.isInvalid())
6905         FirstDesignator = DIE->getBeginLoc();
6906 
6907       if (!getLangOpts().CPlusPlus)
6908         break;
6909 
6910       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6911         DiagnosedNestedDesignator = true;
6912         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6913           << DIE->getDesignatorsSourceRange();
6914       }
6915 
6916       for (auto &Desig : DIE->designators()) {
6917         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6918           DiagnosedArrayDesignator = true;
6919           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6920             << Desig.getSourceRange();
6921         }
6922       }
6923 
6924       if (!DiagnosedMixedDesignator &&
6925           !isa<DesignatedInitExpr>(InitArgList[0])) {
6926         DiagnosedMixedDesignator = true;
6927         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6928           << DIE->getSourceRange();
6929         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6930           << InitArgList[0]->getSourceRange();
6931       }
6932     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6933                isa<DesignatedInitExpr>(InitArgList[0])) {
6934       DiagnosedMixedDesignator = true;
6935       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6936       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6937         << DIE->getSourceRange();
6938       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6939         << InitArgList[I]->getSourceRange();
6940     }
6941   }
6942 
6943   if (FirstDesignator.isValid()) {
6944     // Only diagnose designated initiaization as a C++20 extension if we didn't
6945     // already diagnose use of (non-C++20) C99 designator syntax.
6946     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6947         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6948       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6949                                 ? diag::warn_cxx17_compat_designated_init
6950                                 : diag::ext_cxx_designated_init);
6951     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6952       Diag(FirstDesignator, diag::ext_designated_init);
6953     }
6954   }
6955 
6956   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6957 }
6958 
6959 ExprResult
6960 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6961                     SourceLocation RBraceLoc) {
6962   // Semantic analysis for initializers is done by ActOnDeclarator() and
6963   // CheckInitializer() - it requires knowledge of the object being initialized.
6964 
6965   // Immediately handle non-overload placeholders.  Overloads can be
6966   // resolved contextually, but everything else here can't.
6967   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6968     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6969       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6970 
6971       // Ignore failures; dropping the entire initializer list because
6972       // of one failure would be terrible for indexing/etc.
6973       if (result.isInvalid()) continue;
6974 
6975       InitArgList[I] = result.get();
6976     }
6977   }
6978 
6979   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6980                                                RBraceLoc);
6981   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6982   return E;
6983 }
6984 
6985 /// Do an explicit extend of the given block pointer if we're in ARC.
6986 void Sema::maybeExtendBlockObject(ExprResult &E) {
6987   assert(E.get()->getType()->isBlockPointerType());
6988   assert(E.get()->isRValue());
6989 
6990   // Only do this in an r-value context.
6991   if (!getLangOpts().ObjCAutoRefCount) return;
6992 
6993   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6994                                CK_ARCExtendBlockObject, E.get(),
6995                                /*base path*/ nullptr, VK_RValue);
6996   Cleanup.setExprNeedsCleanups(true);
6997 }
6998 
6999 /// Prepare a conversion of the given expression to an ObjC object
7000 /// pointer type.
7001 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7002   QualType type = E.get()->getType();
7003   if (type->isObjCObjectPointerType()) {
7004     return CK_BitCast;
7005   } else if (type->isBlockPointerType()) {
7006     maybeExtendBlockObject(E);
7007     return CK_BlockPointerToObjCPointerCast;
7008   } else {
7009     assert(type->isPointerType());
7010     return CK_CPointerToObjCPointerCast;
7011   }
7012 }
7013 
7014 /// Prepares for a scalar cast, performing all the necessary stages
7015 /// except the final cast and returning the kind required.
7016 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7017   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7018   // Also, callers should have filtered out the invalid cases with
7019   // pointers.  Everything else should be possible.
7020 
7021   QualType SrcTy = Src.get()->getType();
7022   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7023     return CK_NoOp;
7024 
7025   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7026   case Type::STK_MemberPointer:
7027     llvm_unreachable("member pointer type in C");
7028 
7029   case Type::STK_CPointer:
7030   case Type::STK_BlockPointer:
7031   case Type::STK_ObjCObjectPointer:
7032     switch (DestTy->getScalarTypeKind()) {
7033     case Type::STK_CPointer: {
7034       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7035       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7036       if (SrcAS != DestAS)
7037         return CK_AddressSpaceConversion;
7038       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7039         return CK_NoOp;
7040       return CK_BitCast;
7041     }
7042     case Type::STK_BlockPointer:
7043       return (SrcKind == Type::STK_BlockPointer
7044                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7045     case Type::STK_ObjCObjectPointer:
7046       if (SrcKind == Type::STK_ObjCObjectPointer)
7047         return CK_BitCast;
7048       if (SrcKind == Type::STK_CPointer)
7049         return CK_CPointerToObjCPointerCast;
7050       maybeExtendBlockObject(Src);
7051       return CK_BlockPointerToObjCPointerCast;
7052     case Type::STK_Bool:
7053       return CK_PointerToBoolean;
7054     case Type::STK_Integral:
7055       return CK_PointerToIntegral;
7056     case Type::STK_Floating:
7057     case Type::STK_FloatingComplex:
7058     case Type::STK_IntegralComplex:
7059     case Type::STK_MemberPointer:
7060     case Type::STK_FixedPoint:
7061       llvm_unreachable("illegal cast from pointer");
7062     }
7063     llvm_unreachable("Should have returned before this");
7064 
7065   case Type::STK_FixedPoint:
7066     switch (DestTy->getScalarTypeKind()) {
7067     case Type::STK_FixedPoint:
7068       return CK_FixedPointCast;
7069     case Type::STK_Bool:
7070       return CK_FixedPointToBoolean;
7071     case Type::STK_Integral:
7072       return CK_FixedPointToIntegral;
7073     case Type::STK_Floating:
7074     case Type::STK_IntegralComplex:
7075     case Type::STK_FloatingComplex:
7076       Diag(Src.get()->getExprLoc(),
7077            diag::err_unimplemented_conversion_with_fixed_point_type)
7078           << DestTy;
7079       return CK_IntegralCast;
7080     case Type::STK_CPointer:
7081     case Type::STK_ObjCObjectPointer:
7082     case Type::STK_BlockPointer:
7083     case Type::STK_MemberPointer:
7084       llvm_unreachable("illegal cast to pointer type");
7085     }
7086     llvm_unreachable("Should have returned before this");
7087 
7088   case Type::STK_Bool: // casting from bool is like casting from an integer
7089   case Type::STK_Integral:
7090     switch (DestTy->getScalarTypeKind()) {
7091     case Type::STK_CPointer:
7092     case Type::STK_ObjCObjectPointer:
7093     case Type::STK_BlockPointer:
7094       if (Src.get()->isNullPointerConstant(Context,
7095                                            Expr::NPC_ValueDependentIsNull))
7096         return CK_NullToPointer;
7097       return CK_IntegralToPointer;
7098     case Type::STK_Bool:
7099       return CK_IntegralToBoolean;
7100     case Type::STK_Integral:
7101       return CK_IntegralCast;
7102     case Type::STK_Floating:
7103       return CK_IntegralToFloating;
7104     case Type::STK_IntegralComplex:
7105       Src = ImpCastExprToType(Src.get(),
7106                       DestTy->castAs<ComplexType>()->getElementType(),
7107                       CK_IntegralCast);
7108       return CK_IntegralRealToComplex;
7109     case Type::STK_FloatingComplex:
7110       Src = ImpCastExprToType(Src.get(),
7111                       DestTy->castAs<ComplexType>()->getElementType(),
7112                       CK_IntegralToFloating);
7113       return CK_FloatingRealToComplex;
7114     case Type::STK_MemberPointer:
7115       llvm_unreachable("member pointer type in C");
7116     case Type::STK_FixedPoint:
7117       return CK_IntegralToFixedPoint;
7118     }
7119     llvm_unreachable("Should have returned before this");
7120 
7121   case Type::STK_Floating:
7122     switch (DestTy->getScalarTypeKind()) {
7123     case Type::STK_Floating:
7124       return CK_FloatingCast;
7125     case Type::STK_Bool:
7126       return CK_FloatingToBoolean;
7127     case Type::STK_Integral:
7128       return CK_FloatingToIntegral;
7129     case Type::STK_FloatingComplex:
7130       Src = ImpCastExprToType(Src.get(),
7131                               DestTy->castAs<ComplexType>()->getElementType(),
7132                               CK_FloatingCast);
7133       return CK_FloatingRealToComplex;
7134     case Type::STK_IntegralComplex:
7135       Src = ImpCastExprToType(Src.get(),
7136                               DestTy->castAs<ComplexType>()->getElementType(),
7137                               CK_FloatingToIntegral);
7138       return CK_IntegralRealToComplex;
7139     case Type::STK_CPointer:
7140     case Type::STK_ObjCObjectPointer:
7141     case Type::STK_BlockPointer:
7142       llvm_unreachable("valid float->pointer cast?");
7143     case Type::STK_MemberPointer:
7144       llvm_unreachable("member pointer type in C");
7145     case Type::STK_FixedPoint:
7146       Diag(Src.get()->getExprLoc(),
7147            diag::err_unimplemented_conversion_with_fixed_point_type)
7148           << SrcTy;
7149       return CK_IntegralCast;
7150     }
7151     llvm_unreachable("Should have returned before this");
7152 
7153   case Type::STK_FloatingComplex:
7154     switch (DestTy->getScalarTypeKind()) {
7155     case Type::STK_FloatingComplex:
7156       return CK_FloatingComplexCast;
7157     case Type::STK_IntegralComplex:
7158       return CK_FloatingComplexToIntegralComplex;
7159     case Type::STK_Floating: {
7160       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7161       if (Context.hasSameType(ET, DestTy))
7162         return CK_FloatingComplexToReal;
7163       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7164       return CK_FloatingCast;
7165     }
7166     case Type::STK_Bool:
7167       return CK_FloatingComplexToBoolean;
7168     case Type::STK_Integral:
7169       Src = ImpCastExprToType(Src.get(),
7170                               SrcTy->castAs<ComplexType>()->getElementType(),
7171                               CK_FloatingComplexToReal);
7172       return CK_FloatingToIntegral;
7173     case Type::STK_CPointer:
7174     case Type::STK_ObjCObjectPointer:
7175     case Type::STK_BlockPointer:
7176       llvm_unreachable("valid complex float->pointer cast?");
7177     case Type::STK_MemberPointer:
7178       llvm_unreachable("member pointer type in C");
7179     case Type::STK_FixedPoint:
7180       Diag(Src.get()->getExprLoc(),
7181            diag::err_unimplemented_conversion_with_fixed_point_type)
7182           << SrcTy;
7183       return CK_IntegralCast;
7184     }
7185     llvm_unreachable("Should have returned before this");
7186 
7187   case Type::STK_IntegralComplex:
7188     switch (DestTy->getScalarTypeKind()) {
7189     case Type::STK_FloatingComplex:
7190       return CK_IntegralComplexToFloatingComplex;
7191     case Type::STK_IntegralComplex:
7192       return CK_IntegralComplexCast;
7193     case Type::STK_Integral: {
7194       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7195       if (Context.hasSameType(ET, DestTy))
7196         return CK_IntegralComplexToReal;
7197       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7198       return CK_IntegralCast;
7199     }
7200     case Type::STK_Bool:
7201       return CK_IntegralComplexToBoolean;
7202     case Type::STK_Floating:
7203       Src = ImpCastExprToType(Src.get(),
7204                               SrcTy->castAs<ComplexType>()->getElementType(),
7205                               CK_IntegralComplexToReal);
7206       return CK_IntegralToFloating;
7207     case Type::STK_CPointer:
7208     case Type::STK_ObjCObjectPointer:
7209     case Type::STK_BlockPointer:
7210       llvm_unreachable("valid complex int->pointer cast?");
7211     case Type::STK_MemberPointer:
7212       llvm_unreachable("member pointer type in C");
7213     case Type::STK_FixedPoint:
7214       Diag(Src.get()->getExprLoc(),
7215            diag::err_unimplemented_conversion_with_fixed_point_type)
7216           << SrcTy;
7217       return CK_IntegralCast;
7218     }
7219     llvm_unreachable("Should have returned before this");
7220   }
7221 
7222   llvm_unreachable("Unhandled scalar cast");
7223 }
7224 
7225 static bool breakDownVectorType(QualType type, uint64_t &len,
7226                                 QualType &eltType) {
7227   // Vectors are simple.
7228   if (const VectorType *vecType = type->getAs<VectorType>()) {
7229     len = vecType->getNumElements();
7230     eltType = vecType->getElementType();
7231     assert(eltType->isScalarType());
7232     return true;
7233   }
7234 
7235   // We allow lax conversion to and from non-vector types, but only if
7236   // they're real types (i.e. non-complex, non-pointer scalar types).
7237   if (!type->isRealType()) return false;
7238 
7239   len = 1;
7240   eltType = type;
7241   return true;
7242 }
7243 
7244 /// Are the two types lax-compatible vector types?  That is, given
7245 /// that one of them is a vector, do they have equal storage sizes,
7246 /// where the storage size is the number of elements times the element
7247 /// size?
7248 ///
7249 /// This will also return false if either of the types is neither a
7250 /// vector nor a real type.
7251 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7252   assert(destTy->isVectorType() || srcTy->isVectorType());
7253 
7254   // Disallow lax conversions between scalars and ExtVectors (these
7255   // conversions are allowed for other vector types because common headers
7256   // depend on them).  Most scalar OP ExtVector cases are handled by the
7257   // splat path anyway, which does what we want (convert, not bitcast).
7258   // What this rules out for ExtVectors is crazy things like char4*float.
7259   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7260   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7261 
7262   uint64_t srcLen, destLen;
7263   QualType srcEltTy, destEltTy;
7264   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7265   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7266 
7267   // ASTContext::getTypeSize will return the size rounded up to a
7268   // power of 2, so instead of using that, we need to use the raw
7269   // element size multiplied by the element count.
7270   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7271   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7272 
7273   return (srcLen * srcEltSize == destLen * destEltSize);
7274 }
7275 
7276 /// Is this a legal conversion between two types, one of which is
7277 /// known to be a vector type?
7278 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7279   assert(destTy->isVectorType() || srcTy->isVectorType());
7280 
7281   switch (Context.getLangOpts().getLaxVectorConversions()) {
7282   case LangOptions::LaxVectorConversionKind::None:
7283     return false;
7284 
7285   case LangOptions::LaxVectorConversionKind::Integer:
7286     if (!srcTy->isIntegralOrEnumerationType()) {
7287       auto *Vec = srcTy->getAs<VectorType>();
7288       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7289         return false;
7290     }
7291     if (!destTy->isIntegralOrEnumerationType()) {
7292       auto *Vec = destTy->getAs<VectorType>();
7293       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7294         return false;
7295     }
7296     // OK, integer (vector) -> integer (vector) bitcast.
7297     break;
7298 
7299     case LangOptions::LaxVectorConversionKind::All:
7300     break;
7301   }
7302 
7303   return areLaxCompatibleVectorTypes(srcTy, destTy);
7304 }
7305 
7306 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7307                            CastKind &Kind) {
7308   assert(VectorTy->isVectorType() && "Not a vector type!");
7309 
7310   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7311     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7312       return Diag(R.getBegin(),
7313                   Ty->isVectorType() ?
7314                   diag::err_invalid_conversion_between_vectors :
7315                   diag::err_invalid_conversion_between_vector_and_integer)
7316         << VectorTy << Ty << R;
7317   } else
7318     return Diag(R.getBegin(),
7319                 diag::err_invalid_conversion_between_vector_and_scalar)
7320       << VectorTy << Ty << R;
7321 
7322   Kind = CK_BitCast;
7323   return false;
7324 }
7325 
7326 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7327   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7328 
7329   if (DestElemTy == SplattedExpr->getType())
7330     return SplattedExpr;
7331 
7332   assert(DestElemTy->isFloatingType() ||
7333          DestElemTy->isIntegralOrEnumerationType());
7334 
7335   CastKind CK;
7336   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7337     // OpenCL requires that we convert `true` boolean expressions to -1, but
7338     // only when splatting vectors.
7339     if (DestElemTy->isFloatingType()) {
7340       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7341       // in two steps: boolean to signed integral, then to floating.
7342       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7343                                                  CK_BooleanToSignedIntegral);
7344       SplattedExpr = CastExprRes.get();
7345       CK = CK_IntegralToFloating;
7346     } else {
7347       CK = CK_BooleanToSignedIntegral;
7348     }
7349   } else {
7350     ExprResult CastExprRes = SplattedExpr;
7351     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7352     if (CastExprRes.isInvalid())
7353       return ExprError();
7354     SplattedExpr = CastExprRes.get();
7355   }
7356   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7357 }
7358 
7359 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7360                                     Expr *CastExpr, CastKind &Kind) {
7361   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7362 
7363   QualType SrcTy = CastExpr->getType();
7364 
7365   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7366   // an ExtVectorType.
7367   // In OpenCL, casts between vectors of different types are not allowed.
7368   // (See OpenCL 6.2).
7369   if (SrcTy->isVectorType()) {
7370     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7371         (getLangOpts().OpenCL &&
7372          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7373       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7374         << DestTy << SrcTy << R;
7375       return ExprError();
7376     }
7377     Kind = CK_BitCast;
7378     return CastExpr;
7379   }
7380 
7381   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7382   // conversion will take place first from scalar to elt type, and then
7383   // splat from elt type to vector.
7384   if (SrcTy->isPointerType())
7385     return Diag(R.getBegin(),
7386                 diag::err_invalid_conversion_between_vector_and_scalar)
7387       << DestTy << SrcTy << R;
7388 
7389   Kind = CK_VectorSplat;
7390   return prepareVectorSplat(DestTy, CastExpr);
7391 }
7392 
7393 ExprResult
7394 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7395                     Declarator &D, ParsedType &Ty,
7396                     SourceLocation RParenLoc, Expr *CastExpr) {
7397   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7398          "ActOnCastExpr(): missing type or expr");
7399 
7400   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7401   if (D.isInvalidType())
7402     return ExprError();
7403 
7404   if (getLangOpts().CPlusPlus) {
7405     // Check that there are no default arguments (C++ only).
7406     CheckExtraCXXDefaultArguments(D);
7407   } else {
7408     // Make sure any TypoExprs have been dealt with.
7409     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7410     if (!Res.isUsable())
7411       return ExprError();
7412     CastExpr = Res.get();
7413   }
7414 
7415   checkUnusedDeclAttributes(D);
7416 
7417   QualType castType = castTInfo->getType();
7418   Ty = CreateParsedType(castType, castTInfo);
7419 
7420   bool isVectorLiteral = false;
7421 
7422   // Check for an altivec or OpenCL literal,
7423   // i.e. all the elements are integer constants.
7424   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7425   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7426   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7427        && castType->isVectorType() && (PE || PLE)) {
7428     if (PLE && PLE->getNumExprs() == 0) {
7429       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7430       return ExprError();
7431     }
7432     if (PE || PLE->getNumExprs() == 1) {
7433       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7434       if (!E->getType()->isVectorType())
7435         isVectorLiteral = true;
7436     }
7437     else
7438       isVectorLiteral = true;
7439   }
7440 
7441   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7442   // then handle it as such.
7443   if (isVectorLiteral)
7444     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7445 
7446   // If the Expr being casted is a ParenListExpr, handle it specially.
7447   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7448   // sequence of BinOp comma operators.
7449   if (isa<ParenListExpr>(CastExpr)) {
7450     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7451     if (Result.isInvalid()) return ExprError();
7452     CastExpr = Result.get();
7453   }
7454 
7455   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7456       !getSourceManager().isInSystemMacro(LParenLoc))
7457     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7458 
7459   CheckTollFreeBridgeCast(castType, CastExpr);
7460 
7461   CheckObjCBridgeRelatedCast(castType, CastExpr);
7462 
7463   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7464 
7465   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7466 }
7467 
7468 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7469                                     SourceLocation RParenLoc, Expr *E,
7470                                     TypeSourceInfo *TInfo) {
7471   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7472          "Expected paren or paren list expression");
7473 
7474   Expr **exprs;
7475   unsigned numExprs;
7476   Expr *subExpr;
7477   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7478   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7479     LiteralLParenLoc = PE->getLParenLoc();
7480     LiteralRParenLoc = PE->getRParenLoc();
7481     exprs = PE->getExprs();
7482     numExprs = PE->getNumExprs();
7483   } else { // isa<ParenExpr> by assertion at function entrance
7484     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7485     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7486     subExpr = cast<ParenExpr>(E)->getSubExpr();
7487     exprs = &subExpr;
7488     numExprs = 1;
7489   }
7490 
7491   QualType Ty = TInfo->getType();
7492   assert(Ty->isVectorType() && "Expected vector type");
7493 
7494   SmallVector<Expr *, 8> initExprs;
7495   const VectorType *VTy = Ty->castAs<VectorType>();
7496   unsigned numElems = VTy->getNumElements();
7497 
7498   // '(...)' form of vector initialization in AltiVec: the number of
7499   // initializers must be one or must match the size of the vector.
7500   // If a single value is specified in the initializer then it will be
7501   // replicated to all the components of the vector
7502   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7503     // The number of initializers must be one or must match the size of the
7504     // vector. If a single value is specified in the initializer then it will
7505     // be replicated to all the components of the vector
7506     if (numExprs == 1) {
7507       QualType ElemTy = VTy->getElementType();
7508       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7509       if (Literal.isInvalid())
7510         return ExprError();
7511       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7512                                   PrepareScalarCast(Literal, ElemTy));
7513       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7514     }
7515     else if (numExprs < numElems) {
7516       Diag(E->getExprLoc(),
7517            diag::err_incorrect_number_of_vector_initializers);
7518       return ExprError();
7519     }
7520     else
7521       initExprs.append(exprs, exprs + numExprs);
7522   }
7523   else {
7524     // For OpenCL, when the number of initializers is a single value,
7525     // it will be replicated to all components of the vector.
7526     if (getLangOpts().OpenCL &&
7527         VTy->getVectorKind() == VectorType::GenericVector &&
7528         numExprs == 1) {
7529         QualType ElemTy = VTy->getElementType();
7530         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7531         if (Literal.isInvalid())
7532           return ExprError();
7533         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7534                                     PrepareScalarCast(Literal, ElemTy));
7535         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7536     }
7537 
7538     initExprs.append(exprs, exprs + numExprs);
7539   }
7540   // FIXME: This means that pretty-printing the final AST will produce curly
7541   // braces instead of the original commas.
7542   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7543                                                    initExprs, LiteralRParenLoc);
7544   initE->setType(Ty);
7545   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7546 }
7547 
7548 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7549 /// the ParenListExpr into a sequence of comma binary operators.
7550 ExprResult
7551 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7552   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7553   if (!E)
7554     return OrigExpr;
7555 
7556   ExprResult Result(E->getExpr(0));
7557 
7558   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7559     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7560                         E->getExpr(i));
7561 
7562   if (Result.isInvalid()) return ExprError();
7563 
7564   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7565 }
7566 
7567 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7568                                     SourceLocation R,
7569                                     MultiExprArg Val) {
7570   return ParenListExpr::Create(Context, L, Val, R);
7571 }
7572 
7573 /// Emit a specialized diagnostic when one expression is a null pointer
7574 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7575 /// emitted.
7576 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7577                                       SourceLocation QuestionLoc) {
7578   Expr *NullExpr = LHSExpr;
7579   Expr *NonPointerExpr = RHSExpr;
7580   Expr::NullPointerConstantKind NullKind =
7581       NullExpr->isNullPointerConstant(Context,
7582                                       Expr::NPC_ValueDependentIsNotNull);
7583 
7584   if (NullKind == Expr::NPCK_NotNull) {
7585     NullExpr = RHSExpr;
7586     NonPointerExpr = LHSExpr;
7587     NullKind =
7588         NullExpr->isNullPointerConstant(Context,
7589                                         Expr::NPC_ValueDependentIsNotNull);
7590   }
7591 
7592   if (NullKind == Expr::NPCK_NotNull)
7593     return false;
7594 
7595   if (NullKind == Expr::NPCK_ZeroExpression)
7596     return false;
7597 
7598   if (NullKind == Expr::NPCK_ZeroLiteral) {
7599     // In this case, check to make sure that we got here from a "NULL"
7600     // string in the source code.
7601     NullExpr = NullExpr->IgnoreParenImpCasts();
7602     SourceLocation loc = NullExpr->getExprLoc();
7603     if (!findMacroSpelling(loc, "NULL"))
7604       return false;
7605   }
7606 
7607   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7608   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7609       << NonPointerExpr->getType() << DiagType
7610       << NonPointerExpr->getSourceRange();
7611   return true;
7612 }
7613 
7614 /// Return false if the condition expression is valid, true otherwise.
7615 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7616   QualType CondTy = Cond->getType();
7617 
7618   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7619   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7620     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7621       << CondTy << Cond->getSourceRange();
7622     return true;
7623   }
7624 
7625   // C99 6.5.15p2
7626   if (CondTy->isScalarType()) return false;
7627 
7628   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7629     << CondTy << Cond->getSourceRange();
7630   return true;
7631 }
7632 
7633 /// Handle when one or both operands are void type.
7634 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7635                                          ExprResult &RHS) {
7636     Expr *LHSExpr = LHS.get();
7637     Expr *RHSExpr = RHS.get();
7638 
7639     if (!LHSExpr->getType()->isVoidType())
7640       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7641           << RHSExpr->getSourceRange();
7642     if (!RHSExpr->getType()->isVoidType())
7643       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7644           << LHSExpr->getSourceRange();
7645     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7646     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7647     return S.Context.VoidTy;
7648 }
7649 
7650 /// Return false if the NullExpr can be promoted to PointerTy,
7651 /// true otherwise.
7652 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7653                                         QualType PointerTy) {
7654   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7655       !NullExpr.get()->isNullPointerConstant(S.Context,
7656                                             Expr::NPC_ValueDependentIsNull))
7657     return true;
7658 
7659   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7660   return false;
7661 }
7662 
7663 /// Checks compatibility between two pointers and return the resulting
7664 /// type.
7665 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7666                                                      ExprResult &RHS,
7667                                                      SourceLocation Loc) {
7668   QualType LHSTy = LHS.get()->getType();
7669   QualType RHSTy = RHS.get()->getType();
7670 
7671   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7672     // Two identical pointers types are always compatible.
7673     return LHSTy;
7674   }
7675 
7676   QualType lhptee, rhptee;
7677 
7678   // Get the pointee types.
7679   bool IsBlockPointer = false;
7680   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7681     lhptee = LHSBTy->getPointeeType();
7682     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7683     IsBlockPointer = true;
7684   } else {
7685     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7686     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7687   }
7688 
7689   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7690   // differently qualified versions of compatible types, the result type is
7691   // a pointer to an appropriately qualified version of the composite
7692   // type.
7693 
7694   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7695   // clause doesn't make sense for our extensions. E.g. address space 2 should
7696   // be incompatible with address space 3: they may live on different devices or
7697   // anything.
7698   Qualifiers lhQual = lhptee.getQualifiers();
7699   Qualifiers rhQual = rhptee.getQualifiers();
7700 
7701   LangAS ResultAddrSpace = LangAS::Default;
7702   LangAS LAddrSpace = lhQual.getAddressSpace();
7703   LangAS RAddrSpace = rhQual.getAddressSpace();
7704 
7705   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7706   // spaces is disallowed.
7707   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7708     ResultAddrSpace = LAddrSpace;
7709   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7710     ResultAddrSpace = RAddrSpace;
7711   else {
7712     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7713         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7714         << RHS.get()->getSourceRange();
7715     return QualType();
7716   }
7717 
7718   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7719   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7720   lhQual.removeCVRQualifiers();
7721   rhQual.removeCVRQualifiers();
7722 
7723   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7724   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7725   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7726   // qual types are compatible iff
7727   //  * corresponded types are compatible
7728   //  * CVR qualifiers are equal
7729   //  * address spaces are equal
7730   // Thus for conditional operator we merge CVR and address space unqualified
7731   // pointees and if there is a composite type we return a pointer to it with
7732   // merged qualifiers.
7733   LHSCastKind =
7734       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7735   RHSCastKind =
7736       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7737   lhQual.removeAddressSpace();
7738   rhQual.removeAddressSpace();
7739 
7740   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7741   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7742 
7743   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7744 
7745   if (CompositeTy.isNull()) {
7746     // In this situation, we assume void* type. No especially good
7747     // reason, but this is what gcc does, and we do have to pick
7748     // to get a consistent AST.
7749     QualType incompatTy;
7750     incompatTy = S.Context.getPointerType(
7751         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7752     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7753     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7754 
7755     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7756     // for casts between types with incompatible address space qualifiers.
7757     // For the following code the compiler produces casts between global and
7758     // local address spaces of the corresponded innermost pointees:
7759     // local int *global *a;
7760     // global int *global *b;
7761     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7762     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7763         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7764         << RHS.get()->getSourceRange();
7765 
7766     return incompatTy;
7767   }
7768 
7769   // The pointer types are compatible.
7770   // In case of OpenCL ResultTy should have the address space qualifier
7771   // which is a superset of address spaces of both the 2nd and the 3rd
7772   // operands of the conditional operator.
7773   QualType ResultTy = [&, ResultAddrSpace]() {
7774     if (S.getLangOpts().OpenCL) {
7775       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7776       CompositeQuals.setAddressSpace(ResultAddrSpace);
7777       return S.Context
7778           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7779           .withCVRQualifiers(MergedCVRQual);
7780     }
7781     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7782   }();
7783   if (IsBlockPointer)
7784     ResultTy = S.Context.getBlockPointerType(ResultTy);
7785   else
7786     ResultTy = S.Context.getPointerType(ResultTy);
7787 
7788   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7789   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7790   return ResultTy;
7791 }
7792 
7793 /// Return the resulting type when the operands are both block pointers.
7794 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7795                                                           ExprResult &LHS,
7796                                                           ExprResult &RHS,
7797                                                           SourceLocation Loc) {
7798   QualType LHSTy = LHS.get()->getType();
7799   QualType RHSTy = RHS.get()->getType();
7800 
7801   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7802     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7803       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7804       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7805       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7806       return destType;
7807     }
7808     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7809       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7810       << RHS.get()->getSourceRange();
7811     return QualType();
7812   }
7813 
7814   // We have 2 block pointer types.
7815   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7816 }
7817 
7818 /// Return the resulting type when the operands are both pointers.
7819 static QualType
7820 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7821                                             ExprResult &RHS,
7822                                             SourceLocation Loc) {
7823   // get the pointer types
7824   QualType LHSTy = LHS.get()->getType();
7825   QualType RHSTy = RHS.get()->getType();
7826 
7827   // get the "pointed to" types
7828   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7829   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7830 
7831   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7832   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7833     // Figure out necessary qualifiers (C99 6.5.15p6)
7834     QualType destPointee
7835       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7836     QualType destType = S.Context.getPointerType(destPointee);
7837     // Add qualifiers if necessary.
7838     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7839     // Promote to void*.
7840     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7841     return destType;
7842   }
7843   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7844     QualType destPointee
7845       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7846     QualType destType = S.Context.getPointerType(destPointee);
7847     // Add qualifiers if necessary.
7848     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7849     // Promote to void*.
7850     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7851     return destType;
7852   }
7853 
7854   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7855 }
7856 
7857 /// Return false if the first expression is not an integer and the second
7858 /// expression is not a pointer, true otherwise.
7859 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7860                                         Expr* PointerExpr, SourceLocation Loc,
7861                                         bool IsIntFirstExpr) {
7862   if (!PointerExpr->getType()->isPointerType() ||
7863       !Int.get()->getType()->isIntegerType())
7864     return false;
7865 
7866   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7867   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7868 
7869   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7870     << Expr1->getType() << Expr2->getType()
7871     << Expr1->getSourceRange() << Expr2->getSourceRange();
7872   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7873                             CK_IntegralToPointer);
7874   return true;
7875 }
7876 
7877 /// Simple conversion between integer and floating point types.
7878 ///
7879 /// Used when handling the OpenCL conditional operator where the
7880 /// condition is a vector while the other operands are scalar.
7881 ///
7882 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7883 /// types are either integer or floating type. Between the two
7884 /// operands, the type with the higher rank is defined as the "result
7885 /// type". The other operand needs to be promoted to the same type. No
7886 /// other type promotion is allowed. We cannot use
7887 /// UsualArithmeticConversions() for this purpose, since it always
7888 /// promotes promotable types.
7889 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7890                                             ExprResult &RHS,
7891                                             SourceLocation QuestionLoc) {
7892   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7893   if (LHS.isInvalid())
7894     return QualType();
7895   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7896   if (RHS.isInvalid())
7897     return QualType();
7898 
7899   // For conversion purposes, we ignore any qualifiers.
7900   // For example, "const float" and "float" are equivalent.
7901   QualType LHSType =
7902     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7903   QualType RHSType =
7904     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7905 
7906   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7907     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7908       << LHSType << LHS.get()->getSourceRange();
7909     return QualType();
7910   }
7911 
7912   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7913     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7914       << RHSType << RHS.get()->getSourceRange();
7915     return QualType();
7916   }
7917 
7918   // If both types are identical, no conversion is needed.
7919   if (LHSType == RHSType)
7920     return LHSType;
7921 
7922   // Now handle "real" floating types (i.e. float, double, long double).
7923   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7924     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7925                                  /*IsCompAssign = */ false);
7926 
7927   // Finally, we have two differing integer types.
7928   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7929   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7930 }
7931 
7932 /// Convert scalar operands to a vector that matches the
7933 ///        condition in length.
7934 ///
7935 /// Used when handling the OpenCL conditional operator where the
7936 /// condition is a vector while the other operands are scalar.
7937 ///
7938 /// We first compute the "result type" for the scalar operands
7939 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7940 /// into a vector of that type where the length matches the condition
7941 /// vector type. s6.11.6 requires that the element types of the result
7942 /// and the condition must have the same number of bits.
7943 static QualType
7944 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7945                               QualType CondTy, SourceLocation QuestionLoc) {
7946   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7947   if (ResTy.isNull()) return QualType();
7948 
7949   const VectorType *CV = CondTy->getAs<VectorType>();
7950   assert(CV);
7951 
7952   // Determine the vector result type
7953   unsigned NumElements = CV->getNumElements();
7954   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7955 
7956   // Ensure that all types have the same number of bits
7957   if (S.Context.getTypeSize(CV->getElementType())
7958       != S.Context.getTypeSize(ResTy)) {
7959     // Since VectorTy is created internally, it does not pretty print
7960     // with an OpenCL name. Instead, we just print a description.
7961     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7962     SmallString<64> Str;
7963     llvm::raw_svector_ostream OS(Str);
7964     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7965     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7966       << CondTy << OS.str();
7967     return QualType();
7968   }
7969 
7970   // Convert operands to the vector result type
7971   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7972   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7973 
7974   return VectorTy;
7975 }
7976 
7977 /// Return false if this is a valid OpenCL condition vector
7978 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7979                                        SourceLocation QuestionLoc) {
7980   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7981   // integral type.
7982   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7983   assert(CondTy);
7984   QualType EleTy = CondTy->getElementType();
7985   if (EleTy->isIntegerType()) return false;
7986 
7987   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7988     << Cond->getType() << Cond->getSourceRange();
7989   return true;
7990 }
7991 
7992 /// Return false if the vector condition type and the vector
7993 ///        result type are compatible.
7994 ///
7995 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7996 /// number of elements, and their element types have the same number
7997 /// of bits.
7998 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7999                               SourceLocation QuestionLoc) {
8000   const VectorType *CV = CondTy->getAs<VectorType>();
8001   const VectorType *RV = VecResTy->getAs<VectorType>();
8002   assert(CV && RV);
8003 
8004   if (CV->getNumElements() != RV->getNumElements()) {
8005     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8006       << CondTy << VecResTy;
8007     return true;
8008   }
8009 
8010   QualType CVE = CV->getElementType();
8011   QualType RVE = RV->getElementType();
8012 
8013   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8014     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8015       << CondTy << VecResTy;
8016     return true;
8017   }
8018 
8019   return false;
8020 }
8021 
8022 /// Return the resulting type for the conditional operator in
8023 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8024 ///        s6.3.i) when the condition is a vector type.
8025 static QualType
8026 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8027                              ExprResult &LHS, ExprResult &RHS,
8028                              SourceLocation QuestionLoc) {
8029   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8030   if (Cond.isInvalid())
8031     return QualType();
8032   QualType CondTy = Cond.get()->getType();
8033 
8034   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8035     return QualType();
8036 
8037   // If either operand is a vector then find the vector type of the
8038   // result as specified in OpenCL v1.1 s6.3.i.
8039   if (LHS.get()->getType()->isVectorType() ||
8040       RHS.get()->getType()->isVectorType()) {
8041     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8042                                               /*isCompAssign*/false,
8043                                               /*AllowBothBool*/true,
8044                                               /*AllowBoolConversions*/false);
8045     if (VecResTy.isNull()) return QualType();
8046     // The result type must match the condition type as specified in
8047     // OpenCL v1.1 s6.11.6.
8048     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8049       return QualType();
8050     return VecResTy;
8051   }
8052 
8053   // Both operands are scalar.
8054   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8055 }
8056 
8057 /// Return true if the Expr is block type
8058 static bool checkBlockType(Sema &S, const Expr *E) {
8059   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8060     QualType Ty = CE->getCallee()->getType();
8061     if (Ty->isBlockPointerType()) {
8062       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8063       return true;
8064     }
8065   }
8066   return false;
8067 }
8068 
8069 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8070 /// In that case, LHS = cond.
8071 /// C99 6.5.15
8072 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8073                                         ExprResult &RHS, ExprValueKind &VK,
8074                                         ExprObjectKind &OK,
8075                                         SourceLocation QuestionLoc) {
8076 
8077   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8078   if (!LHSResult.isUsable()) return QualType();
8079   LHS = LHSResult;
8080 
8081   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8082   if (!RHSResult.isUsable()) return QualType();
8083   RHS = RHSResult;
8084 
8085   // C++ is sufficiently different to merit its own checker.
8086   if (getLangOpts().CPlusPlus)
8087     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8088 
8089   VK = VK_RValue;
8090   OK = OK_Ordinary;
8091 
8092   // The OpenCL operator with a vector condition is sufficiently
8093   // different to merit its own checker.
8094   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8095       Cond.get()->getType()->isExtVectorType())
8096     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8097 
8098   // First, check the condition.
8099   Cond = UsualUnaryConversions(Cond.get());
8100   if (Cond.isInvalid())
8101     return QualType();
8102   if (checkCondition(*this, Cond.get(), QuestionLoc))
8103     return QualType();
8104 
8105   // Now check the two expressions.
8106   if (LHS.get()->getType()->isVectorType() ||
8107       RHS.get()->getType()->isVectorType())
8108     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8109                                /*AllowBothBool*/true,
8110                                /*AllowBoolConversions*/false);
8111 
8112   QualType ResTy =
8113       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8114   if (LHS.isInvalid() || RHS.isInvalid())
8115     return QualType();
8116 
8117   QualType LHSTy = LHS.get()->getType();
8118   QualType RHSTy = RHS.get()->getType();
8119 
8120   // Diagnose attempts to convert between __float128 and long double where
8121   // such conversions currently can't be handled.
8122   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8123     Diag(QuestionLoc,
8124          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8125       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8126     return QualType();
8127   }
8128 
8129   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8130   // selection operator (?:).
8131   if (getLangOpts().OpenCL &&
8132       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8133     return QualType();
8134   }
8135 
8136   // If both operands have arithmetic type, do the usual arithmetic conversions
8137   // to find a common type: C99 6.5.15p3,5.
8138   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8139     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8140     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8141 
8142     return ResTy;
8143   }
8144 
8145   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8146   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8147     return LHSTy;
8148   }
8149 
8150   // If both operands are the same structure or union type, the result is that
8151   // type.
8152   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8153     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8154       if (LHSRT->getDecl() == RHSRT->getDecl())
8155         // "If both the operands have structure or union type, the result has
8156         // that type."  This implies that CV qualifiers are dropped.
8157         return LHSTy.getUnqualifiedType();
8158     // FIXME: Type of conditional expression must be complete in C mode.
8159   }
8160 
8161   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8162   // The following || allows only one side to be void (a GCC-ism).
8163   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8164     return checkConditionalVoidType(*this, LHS, RHS);
8165   }
8166 
8167   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8168   // the type of the other operand."
8169   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8170   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8171 
8172   // All objective-c pointer type analysis is done here.
8173   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8174                                                         QuestionLoc);
8175   if (LHS.isInvalid() || RHS.isInvalid())
8176     return QualType();
8177   if (!compositeType.isNull())
8178     return compositeType;
8179 
8180 
8181   // Handle block pointer types.
8182   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8183     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8184                                                      QuestionLoc);
8185 
8186   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8187   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8188     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8189                                                        QuestionLoc);
8190 
8191   // GCC compatibility: soften pointer/integer mismatch.  Note that
8192   // null pointers have been filtered out by this point.
8193   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8194       /*IsIntFirstExpr=*/true))
8195     return RHSTy;
8196   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8197       /*IsIntFirstExpr=*/false))
8198     return LHSTy;
8199 
8200   // Allow ?: operations in which both operands have the same
8201   // built-in sizeless type.
8202   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8203     return LHSTy;
8204 
8205   // Emit a better diagnostic if one of the expressions is a null pointer
8206   // constant and the other is not a pointer type. In this case, the user most
8207   // likely forgot to take the address of the other expression.
8208   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8209     return QualType();
8210 
8211   // Otherwise, the operands are not compatible.
8212   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8213     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8214     << RHS.get()->getSourceRange();
8215   return QualType();
8216 }
8217 
8218 /// FindCompositeObjCPointerType - Helper method to find composite type of
8219 /// two objective-c pointer types of the two input expressions.
8220 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8221                                             SourceLocation QuestionLoc) {
8222   QualType LHSTy = LHS.get()->getType();
8223   QualType RHSTy = RHS.get()->getType();
8224 
8225   // Handle things like Class and struct objc_class*.  Here we case the result
8226   // to the pseudo-builtin, because that will be implicitly cast back to the
8227   // redefinition type if an attempt is made to access its fields.
8228   if (LHSTy->isObjCClassType() &&
8229       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8230     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8231     return LHSTy;
8232   }
8233   if (RHSTy->isObjCClassType() &&
8234       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8235     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8236     return RHSTy;
8237   }
8238   // And the same for struct objc_object* / id
8239   if (LHSTy->isObjCIdType() &&
8240       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8241     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8242     return LHSTy;
8243   }
8244   if (RHSTy->isObjCIdType() &&
8245       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8246     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8247     return RHSTy;
8248   }
8249   // And the same for struct objc_selector* / SEL
8250   if (Context.isObjCSelType(LHSTy) &&
8251       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8252     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8253     return LHSTy;
8254   }
8255   if (Context.isObjCSelType(RHSTy) &&
8256       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8257     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8258     return RHSTy;
8259   }
8260   // Check constraints for Objective-C object pointers types.
8261   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8262 
8263     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8264       // Two identical object pointer types are always compatible.
8265       return LHSTy;
8266     }
8267     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8268     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8269     QualType compositeType = LHSTy;
8270 
8271     // If both operands are interfaces and either operand can be
8272     // assigned to the other, use that type as the composite
8273     // type. This allows
8274     //   xxx ? (A*) a : (B*) b
8275     // where B is a subclass of A.
8276     //
8277     // Additionally, as for assignment, if either type is 'id'
8278     // allow silent coercion. Finally, if the types are
8279     // incompatible then make sure to use 'id' as the composite
8280     // type so the result is acceptable for sending messages to.
8281 
8282     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8283     // It could return the composite type.
8284     if (!(compositeType =
8285           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8286       // Nothing more to do.
8287     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8288       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8289     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8290       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8291     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8292                 RHSOPT->isObjCQualifiedIdType()) &&
8293                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8294                                                          true)) {
8295       // Need to handle "id<xx>" explicitly.
8296       // GCC allows qualified id and any Objective-C type to devolve to
8297       // id. Currently localizing to here until clear this should be
8298       // part of ObjCQualifiedIdTypesAreCompatible.
8299       compositeType = Context.getObjCIdType();
8300     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8301       compositeType = Context.getObjCIdType();
8302     } else {
8303       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8304       << LHSTy << RHSTy
8305       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8306       QualType incompatTy = Context.getObjCIdType();
8307       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8308       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8309       return incompatTy;
8310     }
8311     // The object pointer types are compatible.
8312     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8313     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8314     return compositeType;
8315   }
8316   // Check Objective-C object pointer types and 'void *'
8317   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8318     if (getLangOpts().ObjCAutoRefCount) {
8319       // ARC forbids the implicit conversion of object pointers to 'void *',
8320       // so these types are not compatible.
8321       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8322           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8323       LHS = RHS = true;
8324       return QualType();
8325     }
8326     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8327     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8328     QualType destPointee
8329     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8330     QualType destType = Context.getPointerType(destPointee);
8331     // Add qualifiers if necessary.
8332     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8333     // Promote to void*.
8334     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8335     return destType;
8336   }
8337   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8338     if (getLangOpts().ObjCAutoRefCount) {
8339       // ARC forbids the implicit conversion of object pointers to 'void *',
8340       // so these types are not compatible.
8341       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8342           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8343       LHS = RHS = true;
8344       return QualType();
8345     }
8346     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8347     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8348     QualType destPointee
8349     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8350     QualType destType = Context.getPointerType(destPointee);
8351     // Add qualifiers if necessary.
8352     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8353     // Promote to void*.
8354     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8355     return destType;
8356   }
8357   return QualType();
8358 }
8359 
8360 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8361 /// ParenRange in parentheses.
8362 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8363                                const PartialDiagnostic &Note,
8364                                SourceRange ParenRange) {
8365   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8366   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8367       EndLoc.isValid()) {
8368     Self.Diag(Loc, Note)
8369       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8370       << FixItHint::CreateInsertion(EndLoc, ")");
8371   } else {
8372     // We can't display the parentheses, so just show the bare note.
8373     Self.Diag(Loc, Note) << ParenRange;
8374   }
8375 }
8376 
8377 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8378   return BinaryOperator::isAdditiveOp(Opc) ||
8379          BinaryOperator::isMultiplicativeOp(Opc) ||
8380          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8381   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8382   // not any of the logical operators.  Bitwise-xor is commonly used as a
8383   // logical-xor because there is no logical-xor operator.  The logical
8384   // operators, including uses of xor, have a high false positive rate for
8385   // precedence warnings.
8386 }
8387 
8388 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8389 /// expression, either using a built-in or overloaded operator,
8390 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8391 /// expression.
8392 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8393                                    Expr **RHSExprs) {
8394   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8395   E = E->IgnoreImpCasts();
8396   E = E->IgnoreConversionOperator();
8397   E = E->IgnoreImpCasts();
8398   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8399     E = MTE->getSubExpr();
8400     E = E->IgnoreImpCasts();
8401   }
8402 
8403   // Built-in binary operator.
8404   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8405     if (IsArithmeticOp(OP->getOpcode())) {
8406       *Opcode = OP->getOpcode();
8407       *RHSExprs = OP->getRHS();
8408       return true;
8409     }
8410   }
8411 
8412   // Overloaded operator.
8413   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8414     if (Call->getNumArgs() != 2)
8415       return false;
8416 
8417     // Make sure this is really a binary operator that is safe to pass into
8418     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8419     OverloadedOperatorKind OO = Call->getOperator();
8420     if (OO < OO_Plus || OO > OO_Arrow ||
8421         OO == OO_PlusPlus || OO == OO_MinusMinus)
8422       return false;
8423 
8424     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8425     if (IsArithmeticOp(OpKind)) {
8426       *Opcode = OpKind;
8427       *RHSExprs = Call->getArg(1);
8428       return true;
8429     }
8430   }
8431 
8432   return false;
8433 }
8434 
8435 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8436 /// or is a logical expression such as (x==y) which has int type, but is
8437 /// commonly interpreted as boolean.
8438 static bool ExprLooksBoolean(Expr *E) {
8439   E = E->IgnoreParenImpCasts();
8440 
8441   if (E->getType()->isBooleanType())
8442     return true;
8443   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8444     return OP->isComparisonOp() || OP->isLogicalOp();
8445   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8446     return OP->getOpcode() == UO_LNot;
8447   if (E->getType()->isPointerType())
8448     return true;
8449   // FIXME: What about overloaded operator calls returning "unspecified boolean
8450   // type"s (commonly pointer-to-members)?
8451 
8452   return false;
8453 }
8454 
8455 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8456 /// and binary operator are mixed in a way that suggests the programmer assumed
8457 /// the conditional operator has higher precedence, for example:
8458 /// "int x = a + someBinaryCondition ? 1 : 2".
8459 static void DiagnoseConditionalPrecedence(Sema &Self,
8460                                           SourceLocation OpLoc,
8461                                           Expr *Condition,
8462                                           Expr *LHSExpr,
8463                                           Expr *RHSExpr) {
8464   BinaryOperatorKind CondOpcode;
8465   Expr *CondRHS;
8466 
8467   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8468     return;
8469   if (!ExprLooksBoolean(CondRHS))
8470     return;
8471 
8472   // The condition is an arithmetic binary expression, with a right-
8473   // hand side that looks boolean, so warn.
8474 
8475   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8476                         ? diag::warn_precedence_bitwise_conditional
8477                         : diag::warn_precedence_conditional;
8478 
8479   Self.Diag(OpLoc, DiagID)
8480       << Condition->getSourceRange()
8481       << BinaryOperator::getOpcodeStr(CondOpcode);
8482 
8483   SuggestParentheses(
8484       Self, OpLoc,
8485       Self.PDiag(diag::note_precedence_silence)
8486           << BinaryOperator::getOpcodeStr(CondOpcode),
8487       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8488 
8489   SuggestParentheses(Self, OpLoc,
8490                      Self.PDiag(diag::note_precedence_conditional_first),
8491                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8492 }
8493 
8494 /// Compute the nullability of a conditional expression.
8495 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8496                                               QualType LHSTy, QualType RHSTy,
8497                                               ASTContext &Ctx) {
8498   if (!ResTy->isAnyPointerType())
8499     return ResTy;
8500 
8501   auto GetNullability = [&Ctx](QualType Ty) {
8502     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8503     if (Kind)
8504       return *Kind;
8505     return NullabilityKind::Unspecified;
8506   };
8507 
8508   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8509   NullabilityKind MergedKind;
8510 
8511   // Compute nullability of a binary conditional expression.
8512   if (IsBin) {
8513     if (LHSKind == NullabilityKind::NonNull)
8514       MergedKind = NullabilityKind::NonNull;
8515     else
8516       MergedKind = RHSKind;
8517   // Compute nullability of a normal conditional expression.
8518   } else {
8519     if (LHSKind == NullabilityKind::Nullable ||
8520         RHSKind == NullabilityKind::Nullable)
8521       MergedKind = NullabilityKind::Nullable;
8522     else if (LHSKind == NullabilityKind::NonNull)
8523       MergedKind = RHSKind;
8524     else if (RHSKind == NullabilityKind::NonNull)
8525       MergedKind = LHSKind;
8526     else
8527       MergedKind = NullabilityKind::Unspecified;
8528   }
8529 
8530   // Return if ResTy already has the correct nullability.
8531   if (GetNullability(ResTy) == MergedKind)
8532     return ResTy;
8533 
8534   // Strip all nullability from ResTy.
8535   while (ResTy->getNullability(Ctx))
8536     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8537 
8538   // Create a new AttributedType with the new nullability kind.
8539   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8540   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8541 }
8542 
8543 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8544 /// in the case of a the GNU conditional expr extension.
8545 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8546                                     SourceLocation ColonLoc,
8547                                     Expr *CondExpr, Expr *LHSExpr,
8548                                     Expr *RHSExpr) {
8549   if (!getLangOpts().CPlusPlus) {
8550     // C cannot handle TypoExpr nodes in the condition because it
8551     // doesn't handle dependent types properly, so make sure any TypoExprs have
8552     // been dealt with before checking the operands.
8553     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8554     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8555     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8556 
8557     if (!CondResult.isUsable())
8558       return ExprError();
8559 
8560     if (LHSExpr) {
8561       if (!LHSResult.isUsable())
8562         return ExprError();
8563     }
8564 
8565     if (!RHSResult.isUsable())
8566       return ExprError();
8567 
8568     CondExpr = CondResult.get();
8569     LHSExpr = LHSResult.get();
8570     RHSExpr = RHSResult.get();
8571   }
8572 
8573   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8574   // was the condition.
8575   OpaqueValueExpr *opaqueValue = nullptr;
8576   Expr *commonExpr = nullptr;
8577   if (!LHSExpr) {
8578     commonExpr = CondExpr;
8579     // Lower out placeholder types first.  This is important so that we don't
8580     // try to capture a placeholder. This happens in few cases in C++; such
8581     // as Objective-C++'s dictionary subscripting syntax.
8582     if (commonExpr->hasPlaceholderType()) {
8583       ExprResult result = CheckPlaceholderExpr(commonExpr);
8584       if (!result.isUsable()) return ExprError();
8585       commonExpr = result.get();
8586     }
8587     // We usually want to apply unary conversions *before* saving, except
8588     // in the special case of a C++ l-value conditional.
8589     if (!(getLangOpts().CPlusPlus
8590           && !commonExpr->isTypeDependent()
8591           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8592           && commonExpr->isGLValue()
8593           && commonExpr->isOrdinaryOrBitFieldObject()
8594           && RHSExpr->isOrdinaryOrBitFieldObject()
8595           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8596       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8597       if (commonRes.isInvalid())
8598         return ExprError();
8599       commonExpr = commonRes.get();
8600     }
8601 
8602     // If the common expression is a class or array prvalue, materialize it
8603     // so that we can safely refer to it multiple times.
8604     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8605                                    commonExpr->getType()->isArrayType())) {
8606       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8607       if (MatExpr.isInvalid())
8608         return ExprError();
8609       commonExpr = MatExpr.get();
8610     }
8611 
8612     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8613                                                 commonExpr->getType(),
8614                                                 commonExpr->getValueKind(),
8615                                                 commonExpr->getObjectKind(),
8616                                                 commonExpr);
8617     LHSExpr = CondExpr = opaqueValue;
8618   }
8619 
8620   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8621   ExprValueKind VK = VK_RValue;
8622   ExprObjectKind OK = OK_Ordinary;
8623   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8624   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8625                                              VK, OK, QuestionLoc);
8626   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8627       RHS.isInvalid())
8628     return ExprError();
8629 
8630   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8631                                 RHS.get());
8632 
8633   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8634 
8635   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8636                                          Context);
8637 
8638   if (!commonExpr)
8639     return new (Context)
8640         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8641                             RHS.get(), result, VK, OK);
8642 
8643   return new (Context) BinaryConditionalOperator(
8644       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8645       ColonLoc, result, VK, OK);
8646 }
8647 
8648 // Check if we have a conversion between incompatible cmse function pointer
8649 // types, that is, a conversion between a function pointer with the
8650 // cmse_nonsecure_call attribute and one without.
8651 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8652                                           QualType ToType) {
8653   if (const auto *ToFn =
8654           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8655     if (const auto *FromFn =
8656             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8657       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8658       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8659 
8660       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8661     }
8662   }
8663   return false;
8664 }
8665 
8666 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8667 // being closely modeled after the C99 spec:-). The odd characteristic of this
8668 // routine is it effectively iqnores the qualifiers on the top level pointee.
8669 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8670 // FIXME: add a couple examples in this comment.
8671 static Sema::AssignConvertType
8672 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8673   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8674   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8675 
8676   // get the "pointed to" type (ignoring qualifiers at the top level)
8677   const Type *lhptee, *rhptee;
8678   Qualifiers lhq, rhq;
8679   std::tie(lhptee, lhq) =
8680       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8681   std::tie(rhptee, rhq) =
8682       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8683 
8684   Sema::AssignConvertType ConvTy = Sema::Compatible;
8685 
8686   // C99 6.5.16.1p1: This following citation is common to constraints
8687   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8688   // qualifiers of the type *pointed to* by the right;
8689 
8690   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8691   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8692       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8693     // Ignore lifetime for further calculation.
8694     lhq.removeObjCLifetime();
8695     rhq.removeObjCLifetime();
8696   }
8697 
8698   if (!lhq.compatiblyIncludes(rhq)) {
8699     // Treat address-space mismatches as fatal.
8700     if (!lhq.isAddressSpaceSupersetOf(rhq))
8701       return Sema::IncompatiblePointerDiscardsQualifiers;
8702 
8703     // It's okay to add or remove GC or lifetime qualifiers when converting to
8704     // and from void*.
8705     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8706                         .compatiblyIncludes(
8707                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8708              && (lhptee->isVoidType() || rhptee->isVoidType()))
8709       ; // keep old
8710 
8711     // Treat lifetime mismatches as fatal.
8712     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8713       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8714 
8715     // For GCC/MS compatibility, other qualifier mismatches are treated
8716     // as still compatible in C.
8717     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8718   }
8719 
8720   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8721   // incomplete type and the other is a pointer to a qualified or unqualified
8722   // version of void...
8723   if (lhptee->isVoidType()) {
8724     if (rhptee->isIncompleteOrObjectType())
8725       return ConvTy;
8726 
8727     // As an extension, we allow cast to/from void* to function pointer.
8728     assert(rhptee->isFunctionType());
8729     return Sema::FunctionVoidPointer;
8730   }
8731 
8732   if (rhptee->isVoidType()) {
8733     if (lhptee->isIncompleteOrObjectType())
8734       return ConvTy;
8735 
8736     // As an extension, we allow cast to/from void* to function pointer.
8737     assert(lhptee->isFunctionType());
8738     return Sema::FunctionVoidPointer;
8739   }
8740 
8741   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8742   // unqualified versions of compatible types, ...
8743   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8744   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8745     // Check if the pointee types are compatible ignoring the sign.
8746     // We explicitly check for char so that we catch "char" vs
8747     // "unsigned char" on systems where "char" is unsigned.
8748     if (lhptee->isCharType())
8749       ltrans = S.Context.UnsignedCharTy;
8750     else if (lhptee->hasSignedIntegerRepresentation())
8751       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8752 
8753     if (rhptee->isCharType())
8754       rtrans = S.Context.UnsignedCharTy;
8755     else if (rhptee->hasSignedIntegerRepresentation())
8756       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8757 
8758     if (ltrans == rtrans) {
8759       // Types are compatible ignoring the sign. Qualifier incompatibility
8760       // takes priority over sign incompatibility because the sign
8761       // warning can be disabled.
8762       if (ConvTy != Sema::Compatible)
8763         return ConvTy;
8764 
8765       return Sema::IncompatiblePointerSign;
8766     }
8767 
8768     // If we are a multi-level pointer, it's possible that our issue is simply
8769     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8770     // the eventual target type is the same and the pointers have the same
8771     // level of indirection, this must be the issue.
8772     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8773       do {
8774         std::tie(lhptee, lhq) =
8775           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8776         std::tie(rhptee, rhq) =
8777           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8778 
8779         // Inconsistent address spaces at this point is invalid, even if the
8780         // address spaces would be compatible.
8781         // FIXME: This doesn't catch address space mismatches for pointers of
8782         // different nesting levels, like:
8783         //   __local int *** a;
8784         //   int ** b = a;
8785         // It's not clear how to actually determine when such pointers are
8786         // invalidly incompatible.
8787         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8788           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8789 
8790       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8791 
8792       if (lhptee == rhptee)
8793         return Sema::IncompatibleNestedPointerQualifiers;
8794     }
8795 
8796     // General pointer incompatibility takes priority over qualifiers.
8797     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8798       return Sema::IncompatibleFunctionPointer;
8799     return Sema::IncompatiblePointer;
8800   }
8801   if (!S.getLangOpts().CPlusPlus &&
8802       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8803     return Sema::IncompatibleFunctionPointer;
8804   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8805     return Sema::IncompatibleFunctionPointer;
8806   return ConvTy;
8807 }
8808 
8809 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8810 /// block pointer types are compatible or whether a block and normal pointer
8811 /// are compatible. It is more restrict than comparing two function pointer
8812 // types.
8813 static Sema::AssignConvertType
8814 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8815                                     QualType RHSType) {
8816   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8817   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8818 
8819   QualType lhptee, rhptee;
8820 
8821   // get the "pointed to" type (ignoring qualifiers at the top level)
8822   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8823   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8824 
8825   // In C++, the types have to match exactly.
8826   if (S.getLangOpts().CPlusPlus)
8827     return Sema::IncompatibleBlockPointer;
8828 
8829   Sema::AssignConvertType ConvTy = Sema::Compatible;
8830 
8831   // For blocks we enforce that qualifiers are identical.
8832   Qualifiers LQuals = lhptee.getLocalQualifiers();
8833   Qualifiers RQuals = rhptee.getLocalQualifiers();
8834   if (S.getLangOpts().OpenCL) {
8835     LQuals.removeAddressSpace();
8836     RQuals.removeAddressSpace();
8837   }
8838   if (LQuals != RQuals)
8839     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8840 
8841   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8842   // assignment.
8843   // The current behavior is similar to C++ lambdas. A block might be
8844   // assigned to a variable iff its return type and parameters are compatible
8845   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8846   // an assignment. Presumably it should behave in way that a function pointer
8847   // assignment does in C, so for each parameter and return type:
8848   //  * CVR and address space of LHS should be a superset of CVR and address
8849   //  space of RHS.
8850   //  * unqualified types should be compatible.
8851   if (S.getLangOpts().OpenCL) {
8852     if (!S.Context.typesAreBlockPointerCompatible(
8853             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8854             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8855       return Sema::IncompatibleBlockPointer;
8856   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8857     return Sema::IncompatibleBlockPointer;
8858 
8859   return ConvTy;
8860 }
8861 
8862 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8863 /// for assignment compatibility.
8864 static Sema::AssignConvertType
8865 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8866                                    QualType RHSType) {
8867   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8868   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8869 
8870   if (LHSType->isObjCBuiltinType()) {
8871     // Class is not compatible with ObjC object pointers.
8872     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8873         !RHSType->isObjCQualifiedClassType())
8874       return Sema::IncompatiblePointer;
8875     return Sema::Compatible;
8876   }
8877   if (RHSType->isObjCBuiltinType()) {
8878     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8879         !LHSType->isObjCQualifiedClassType())
8880       return Sema::IncompatiblePointer;
8881     return Sema::Compatible;
8882   }
8883   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8884   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8885 
8886   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8887       // make an exception for id<P>
8888       !LHSType->isObjCQualifiedIdType())
8889     return Sema::CompatiblePointerDiscardsQualifiers;
8890 
8891   if (S.Context.typesAreCompatible(LHSType, RHSType))
8892     return Sema::Compatible;
8893   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8894     return Sema::IncompatibleObjCQualifiedId;
8895   return Sema::IncompatiblePointer;
8896 }
8897 
8898 Sema::AssignConvertType
8899 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8900                                  QualType LHSType, QualType RHSType) {
8901   // Fake up an opaque expression.  We don't actually care about what
8902   // cast operations are required, so if CheckAssignmentConstraints
8903   // adds casts to this they'll be wasted, but fortunately that doesn't
8904   // usually happen on valid code.
8905   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8906   ExprResult RHSPtr = &RHSExpr;
8907   CastKind K;
8908 
8909   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8910 }
8911 
8912 /// This helper function returns true if QT is a vector type that has element
8913 /// type ElementType.
8914 static bool isVector(QualType QT, QualType ElementType) {
8915   if (const VectorType *VT = QT->getAs<VectorType>())
8916     return VT->getElementType().getCanonicalType() == ElementType;
8917   return false;
8918 }
8919 
8920 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8921 /// has code to accommodate several GCC extensions when type checking
8922 /// pointers. Here are some objectionable examples that GCC considers warnings:
8923 ///
8924 ///  int a, *pint;
8925 ///  short *pshort;
8926 ///  struct foo *pfoo;
8927 ///
8928 ///  pint = pshort; // warning: assignment from incompatible pointer type
8929 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8930 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8931 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8932 ///
8933 /// As a result, the code for dealing with pointers is more complex than the
8934 /// C99 spec dictates.
8935 ///
8936 /// Sets 'Kind' for any result kind except Incompatible.
8937 Sema::AssignConvertType
8938 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8939                                  CastKind &Kind, bool ConvertRHS) {
8940   QualType RHSType = RHS.get()->getType();
8941   QualType OrigLHSType = LHSType;
8942 
8943   // Get canonical types.  We're not formatting these types, just comparing
8944   // them.
8945   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8946   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8947 
8948   // Common case: no conversion required.
8949   if (LHSType == RHSType) {
8950     Kind = CK_NoOp;
8951     return Compatible;
8952   }
8953 
8954   // If we have an atomic type, try a non-atomic assignment, then just add an
8955   // atomic qualification step.
8956   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8957     Sema::AssignConvertType result =
8958       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8959     if (result != Compatible)
8960       return result;
8961     if (Kind != CK_NoOp && ConvertRHS)
8962       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8963     Kind = CK_NonAtomicToAtomic;
8964     return Compatible;
8965   }
8966 
8967   // If the left-hand side is a reference type, then we are in a
8968   // (rare!) case where we've allowed the use of references in C,
8969   // e.g., as a parameter type in a built-in function. In this case,
8970   // just make sure that the type referenced is compatible with the
8971   // right-hand side type. The caller is responsible for adjusting
8972   // LHSType so that the resulting expression does not have reference
8973   // type.
8974   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8975     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8976       Kind = CK_LValueBitCast;
8977       return Compatible;
8978     }
8979     return Incompatible;
8980   }
8981 
8982   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8983   // to the same ExtVector type.
8984   if (LHSType->isExtVectorType()) {
8985     if (RHSType->isExtVectorType())
8986       return Incompatible;
8987     if (RHSType->isArithmeticType()) {
8988       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8989       if (ConvertRHS)
8990         RHS = prepareVectorSplat(LHSType, RHS.get());
8991       Kind = CK_VectorSplat;
8992       return Compatible;
8993     }
8994   }
8995 
8996   // Conversions to or from vector type.
8997   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8998     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8999       // Allow assignments of an AltiVec vector type to an equivalent GCC
9000       // vector type and vice versa
9001       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9002         Kind = CK_BitCast;
9003         return Compatible;
9004       }
9005 
9006       // If we are allowing lax vector conversions, and LHS and RHS are both
9007       // vectors, the total size only needs to be the same. This is a bitcast;
9008       // no bits are changed but the result type is different.
9009       if (isLaxVectorConversion(RHSType, LHSType)) {
9010         Kind = CK_BitCast;
9011         return IncompatibleVectors;
9012       }
9013     }
9014 
9015     // When the RHS comes from another lax conversion (e.g. binops between
9016     // scalars and vectors) the result is canonicalized as a vector. When the
9017     // LHS is also a vector, the lax is allowed by the condition above. Handle
9018     // the case where LHS is a scalar.
9019     if (LHSType->isScalarType()) {
9020       const VectorType *VecType = RHSType->getAs<VectorType>();
9021       if (VecType && VecType->getNumElements() == 1 &&
9022           isLaxVectorConversion(RHSType, LHSType)) {
9023         ExprResult *VecExpr = &RHS;
9024         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9025         Kind = CK_BitCast;
9026         return Compatible;
9027       }
9028     }
9029 
9030     return Incompatible;
9031   }
9032 
9033   // Diagnose attempts to convert between __float128 and long double where
9034   // such conversions currently can't be handled.
9035   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9036     return Incompatible;
9037 
9038   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9039   // discards the imaginary part.
9040   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9041       !LHSType->getAs<ComplexType>())
9042     return Incompatible;
9043 
9044   // Arithmetic conversions.
9045   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9046       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9047     if (ConvertRHS)
9048       Kind = PrepareScalarCast(RHS, LHSType);
9049     return Compatible;
9050   }
9051 
9052   // Conversions to normal pointers.
9053   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9054     // U* -> T*
9055     if (isa<PointerType>(RHSType)) {
9056       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9057       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9058       if (AddrSpaceL != AddrSpaceR)
9059         Kind = CK_AddressSpaceConversion;
9060       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9061         Kind = CK_NoOp;
9062       else
9063         Kind = CK_BitCast;
9064       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9065     }
9066 
9067     // int -> T*
9068     if (RHSType->isIntegerType()) {
9069       Kind = CK_IntegralToPointer; // FIXME: null?
9070       return IntToPointer;
9071     }
9072 
9073     // C pointers are not compatible with ObjC object pointers,
9074     // with two exceptions:
9075     if (isa<ObjCObjectPointerType>(RHSType)) {
9076       //  - conversions to void*
9077       if (LHSPointer->getPointeeType()->isVoidType()) {
9078         Kind = CK_BitCast;
9079         return Compatible;
9080       }
9081 
9082       //  - conversions from 'Class' to the redefinition type
9083       if (RHSType->isObjCClassType() &&
9084           Context.hasSameType(LHSType,
9085                               Context.getObjCClassRedefinitionType())) {
9086         Kind = CK_BitCast;
9087         return Compatible;
9088       }
9089 
9090       Kind = CK_BitCast;
9091       return IncompatiblePointer;
9092     }
9093 
9094     // U^ -> void*
9095     if (RHSType->getAs<BlockPointerType>()) {
9096       if (LHSPointer->getPointeeType()->isVoidType()) {
9097         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9098         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9099                                 ->getPointeeType()
9100                                 .getAddressSpace();
9101         Kind =
9102             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9103         return Compatible;
9104       }
9105     }
9106 
9107     return Incompatible;
9108   }
9109 
9110   // Conversions to block pointers.
9111   if (isa<BlockPointerType>(LHSType)) {
9112     // U^ -> T^
9113     if (RHSType->isBlockPointerType()) {
9114       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9115                               ->getPointeeType()
9116                               .getAddressSpace();
9117       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9118                               ->getPointeeType()
9119                               .getAddressSpace();
9120       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9121       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9122     }
9123 
9124     // int or null -> T^
9125     if (RHSType->isIntegerType()) {
9126       Kind = CK_IntegralToPointer; // FIXME: null
9127       return IntToBlockPointer;
9128     }
9129 
9130     // id -> T^
9131     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9132       Kind = CK_AnyPointerToBlockPointerCast;
9133       return Compatible;
9134     }
9135 
9136     // void* -> T^
9137     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9138       if (RHSPT->getPointeeType()->isVoidType()) {
9139         Kind = CK_AnyPointerToBlockPointerCast;
9140         return Compatible;
9141       }
9142 
9143     return Incompatible;
9144   }
9145 
9146   // Conversions to Objective-C pointers.
9147   if (isa<ObjCObjectPointerType>(LHSType)) {
9148     // A* -> B*
9149     if (RHSType->isObjCObjectPointerType()) {
9150       Kind = CK_BitCast;
9151       Sema::AssignConvertType result =
9152         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9153       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9154           result == Compatible &&
9155           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9156         result = IncompatibleObjCWeakRef;
9157       return result;
9158     }
9159 
9160     // int or null -> A*
9161     if (RHSType->isIntegerType()) {
9162       Kind = CK_IntegralToPointer; // FIXME: null
9163       return IntToPointer;
9164     }
9165 
9166     // In general, C pointers are not compatible with ObjC object pointers,
9167     // with two exceptions:
9168     if (isa<PointerType>(RHSType)) {
9169       Kind = CK_CPointerToObjCPointerCast;
9170 
9171       //  - conversions from 'void*'
9172       if (RHSType->isVoidPointerType()) {
9173         return Compatible;
9174       }
9175 
9176       //  - conversions to 'Class' from its redefinition type
9177       if (LHSType->isObjCClassType() &&
9178           Context.hasSameType(RHSType,
9179                               Context.getObjCClassRedefinitionType())) {
9180         return Compatible;
9181       }
9182 
9183       return IncompatiblePointer;
9184     }
9185 
9186     // Only under strict condition T^ is compatible with an Objective-C pointer.
9187     if (RHSType->isBlockPointerType() &&
9188         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9189       if (ConvertRHS)
9190         maybeExtendBlockObject(RHS);
9191       Kind = CK_BlockPointerToObjCPointerCast;
9192       return Compatible;
9193     }
9194 
9195     return Incompatible;
9196   }
9197 
9198   // Conversions from pointers that are not covered by the above.
9199   if (isa<PointerType>(RHSType)) {
9200     // T* -> _Bool
9201     if (LHSType == Context.BoolTy) {
9202       Kind = CK_PointerToBoolean;
9203       return Compatible;
9204     }
9205 
9206     // T* -> int
9207     if (LHSType->isIntegerType()) {
9208       Kind = CK_PointerToIntegral;
9209       return PointerToInt;
9210     }
9211 
9212     return Incompatible;
9213   }
9214 
9215   // Conversions from Objective-C pointers that are not covered by the above.
9216   if (isa<ObjCObjectPointerType>(RHSType)) {
9217     // T* -> _Bool
9218     if (LHSType == Context.BoolTy) {
9219       Kind = CK_PointerToBoolean;
9220       return Compatible;
9221     }
9222 
9223     // T* -> int
9224     if (LHSType->isIntegerType()) {
9225       Kind = CK_PointerToIntegral;
9226       return PointerToInt;
9227     }
9228 
9229     return Incompatible;
9230   }
9231 
9232   // struct A -> struct B
9233   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9234     if (Context.typesAreCompatible(LHSType, RHSType)) {
9235       Kind = CK_NoOp;
9236       return Compatible;
9237     }
9238   }
9239 
9240   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9241     Kind = CK_IntToOCLSampler;
9242     return Compatible;
9243   }
9244 
9245   return Incompatible;
9246 }
9247 
9248 /// Constructs a transparent union from an expression that is
9249 /// used to initialize the transparent union.
9250 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9251                                       ExprResult &EResult, QualType UnionType,
9252                                       FieldDecl *Field) {
9253   // Build an initializer list that designates the appropriate member
9254   // of the transparent union.
9255   Expr *E = EResult.get();
9256   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9257                                                    E, SourceLocation());
9258   Initializer->setType(UnionType);
9259   Initializer->setInitializedFieldInUnion(Field);
9260 
9261   // Build a compound literal constructing a value of the transparent
9262   // union type from this initializer list.
9263   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9264   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9265                                         VK_RValue, Initializer, false);
9266 }
9267 
9268 Sema::AssignConvertType
9269 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9270                                                ExprResult &RHS) {
9271   QualType RHSType = RHS.get()->getType();
9272 
9273   // If the ArgType is a Union type, we want to handle a potential
9274   // transparent_union GCC extension.
9275   const RecordType *UT = ArgType->getAsUnionType();
9276   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9277     return Incompatible;
9278 
9279   // The field to initialize within the transparent union.
9280   RecordDecl *UD = UT->getDecl();
9281   FieldDecl *InitField = nullptr;
9282   // It's compatible if the expression matches any of the fields.
9283   for (auto *it : UD->fields()) {
9284     if (it->getType()->isPointerType()) {
9285       // If the transparent union contains a pointer type, we allow:
9286       // 1) void pointer
9287       // 2) null pointer constant
9288       if (RHSType->isPointerType())
9289         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9290           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9291           InitField = it;
9292           break;
9293         }
9294 
9295       if (RHS.get()->isNullPointerConstant(Context,
9296                                            Expr::NPC_ValueDependentIsNull)) {
9297         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9298                                 CK_NullToPointer);
9299         InitField = it;
9300         break;
9301       }
9302     }
9303 
9304     CastKind Kind;
9305     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9306           == Compatible) {
9307       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9308       InitField = it;
9309       break;
9310     }
9311   }
9312 
9313   if (!InitField)
9314     return Incompatible;
9315 
9316   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9317   return Compatible;
9318 }
9319 
9320 Sema::AssignConvertType
9321 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9322                                        bool Diagnose,
9323                                        bool DiagnoseCFAudited,
9324                                        bool ConvertRHS) {
9325   // We need to be able to tell the caller whether we diagnosed a problem, if
9326   // they ask us to issue diagnostics.
9327   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9328 
9329   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9330   // we can't avoid *all* modifications at the moment, so we need some somewhere
9331   // to put the updated value.
9332   ExprResult LocalRHS = CallerRHS;
9333   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9334 
9335   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9336     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9337       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9338           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9339         Diag(RHS.get()->getExprLoc(),
9340              diag::warn_noderef_to_dereferenceable_pointer)
9341             << RHS.get()->getSourceRange();
9342       }
9343     }
9344   }
9345 
9346   if (getLangOpts().CPlusPlus) {
9347     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9348       // C++ 5.17p3: If the left operand is not of class type, the
9349       // expression is implicitly converted (C++ 4) to the
9350       // cv-unqualified type of the left operand.
9351       QualType RHSType = RHS.get()->getType();
9352       if (Diagnose) {
9353         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9354                                         AA_Assigning);
9355       } else {
9356         ImplicitConversionSequence ICS =
9357             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9358                                   /*SuppressUserConversions=*/false,
9359                                   AllowedExplicit::None,
9360                                   /*InOverloadResolution=*/false,
9361                                   /*CStyle=*/false,
9362                                   /*AllowObjCWritebackConversion=*/false);
9363         if (ICS.isFailure())
9364           return Incompatible;
9365         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9366                                         ICS, AA_Assigning);
9367       }
9368       if (RHS.isInvalid())
9369         return Incompatible;
9370       Sema::AssignConvertType result = Compatible;
9371       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9372           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9373         result = IncompatibleObjCWeakRef;
9374       return result;
9375     }
9376 
9377     // FIXME: Currently, we fall through and treat C++ classes like C
9378     // structures.
9379     // FIXME: We also fall through for atomics; not sure what should
9380     // happen there, though.
9381   } else if (RHS.get()->getType() == Context.OverloadTy) {
9382     // As a set of extensions to C, we support overloading on functions. These
9383     // functions need to be resolved here.
9384     DeclAccessPair DAP;
9385     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9386             RHS.get(), LHSType, /*Complain=*/false, DAP))
9387       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9388     else
9389       return Incompatible;
9390   }
9391 
9392   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9393   // a null pointer constant.
9394   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9395        LHSType->isBlockPointerType()) &&
9396       RHS.get()->isNullPointerConstant(Context,
9397                                        Expr::NPC_ValueDependentIsNull)) {
9398     if (Diagnose || ConvertRHS) {
9399       CastKind Kind;
9400       CXXCastPath Path;
9401       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9402                              /*IgnoreBaseAccess=*/false, Diagnose);
9403       if (ConvertRHS)
9404         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9405     }
9406     return Compatible;
9407   }
9408 
9409   // OpenCL queue_t type assignment.
9410   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9411                                  Context, Expr::NPC_ValueDependentIsNull)) {
9412     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9413     return Compatible;
9414   }
9415 
9416   // This check seems unnatural, however it is necessary to ensure the proper
9417   // conversion of functions/arrays. If the conversion were done for all
9418   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9419   // expressions that suppress this implicit conversion (&, sizeof).
9420   //
9421   // Suppress this for references: C++ 8.5.3p5.
9422   if (!LHSType->isReferenceType()) {
9423     // FIXME: We potentially allocate here even if ConvertRHS is false.
9424     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9425     if (RHS.isInvalid())
9426       return Incompatible;
9427   }
9428   CastKind Kind;
9429   Sema::AssignConvertType result =
9430     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9431 
9432   // C99 6.5.16.1p2: The value of the right operand is converted to the
9433   // type of the assignment expression.
9434   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9435   // so that we can use references in built-in functions even in C.
9436   // The getNonReferenceType() call makes sure that the resulting expression
9437   // does not have reference type.
9438   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9439     QualType Ty = LHSType.getNonLValueExprType(Context);
9440     Expr *E = RHS.get();
9441 
9442     // Check for various Objective-C errors. If we are not reporting
9443     // diagnostics and just checking for errors, e.g., during overload
9444     // resolution, return Incompatible to indicate the failure.
9445     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9446         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9447                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9448       if (!Diagnose)
9449         return Incompatible;
9450     }
9451     if (getLangOpts().ObjC &&
9452         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9453                                            E->getType(), E, Diagnose) ||
9454          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9455       if (!Diagnose)
9456         return Incompatible;
9457       // Replace the expression with a corrected version and continue so we
9458       // can find further errors.
9459       RHS = E;
9460       return Compatible;
9461     }
9462 
9463     if (ConvertRHS)
9464       RHS = ImpCastExprToType(E, Ty, Kind);
9465   }
9466 
9467   return result;
9468 }
9469 
9470 namespace {
9471 /// The original operand to an operator, prior to the application of the usual
9472 /// arithmetic conversions and converting the arguments of a builtin operator
9473 /// candidate.
9474 struct OriginalOperand {
9475   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9476     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9477       Op = MTE->getSubExpr();
9478     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9479       Op = BTE->getSubExpr();
9480     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9481       Orig = ICE->getSubExprAsWritten();
9482       Conversion = ICE->getConversionFunction();
9483     }
9484   }
9485 
9486   QualType getType() const { return Orig->getType(); }
9487 
9488   Expr *Orig;
9489   NamedDecl *Conversion;
9490 };
9491 }
9492 
9493 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9494                                ExprResult &RHS) {
9495   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9496 
9497   Diag(Loc, diag::err_typecheck_invalid_operands)
9498     << OrigLHS.getType() << OrigRHS.getType()
9499     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9500 
9501   // If a user-defined conversion was applied to either of the operands prior
9502   // to applying the built-in operator rules, tell the user about it.
9503   if (OrigLHS.Conversion) {
9504     Diag(OrigLHS.Conversion->getLocation(),
9505          diag::note_typecheck_invalid_operands_converted)
9506       << 0 << LHS.get()->getType();
9507   }
9508   if (OrigRHS.Conversion) {
9509     Diag(OrigRHS.Conversion->getLocation(),
9510          diag::note_typecheck_invalid_operands_converted)
9511       << 1 << RHS.get()->getType();
9512   }
9513 
9514   return QualType();
9515 }
9516 
9517 // Diagnose cases where a scalar was implicitly converted to a vector and
9518 // diagnose the underlying types. Otherwise, diagnose the error
9519 // as invalid vector logical operands for non-C++ cases.
9520 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9521                                             ExprResult &RHS) {
9522   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9523   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9524 
9525   bool LHSNatVec = LHSType->isVectorType();
9526   bool RHSNatVec = RHSType->isVectorType();
9527 
9528   if (!(LHSNatVec && RHSNatVec)) {
9529     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9530     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9531     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9532         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9533         << Vector->getSourceRange();
9534     return QualType();
9535   }
9536 
9537   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9538       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9539       << RHS.get()->getSourceRange();
9540 
9541   return QualType();
9542 }
9543 
9544 /// Try to convert a value of non-vector type to a vector type by converting
9545 /// the type to the element type of the vector and then performing a splat.
9546 /// If the language is OpenCL, we only use conversions that promote scalar
9547 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9548 /// for float->int.
9549 ///
9550 /// OpenCL V2.0 6.2.6.p2:
9551 /// An error shall occur if any scalar operand type has greater rank
9552 /// than the type of the vector element.
9553 ///
9554 /// \param scalar - if non-null, actually perform the conversions
9555 /// \return true if the operation fails (but without diagnosing the failure)
9556 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9557                                      QualType scalarTy,
9558                                      QualType vectorEltTy,
9559                                      QualType vectorTy,
9560                                      unsigned &DiagID) {
9561   // The conversion to apply to the scalar before splatting it,
9562   // if necessary.
9563   CastKind scalarCast = CK_NoOp;
9564 
9565   if (vectorEltTy->isIntegralType(S.Context)) {
9566     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9567         (scalarTy->isIntegerType() &&
9568          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9569       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9570       return true;
9571     }
9572     if (!scalarTy->isIntegralType(S.Context))
9573       return true;
9574     scalarCast = CK_IntegralCast;
9575   } else if (vectorEltTy->isRealFloatingType()) {
9576     if (scalarTy->isRealFloatingType()) {
9577       if (S.getLangOpts().OpenCL &&
9578           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9579         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9580         return true;
9581       }
9582       scalarCast = CK_FloatingCast;
9583     }
9584     else if (scalarTy->isIntegralType(S.Context))
9585       scalarCast = CK_IntegralToFloating;
9586     else
9587       return true;
9588   } else {
9589     return true;
9590   }
9591 
9592   // Adjust scalar if desired.
9593   if (scalar) {
9594     if (scalarCast != CK_NoOp)
9595       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9596     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9597   }
9598   return false;
9599 }
9600 
9601 /// Convert vector E to a vector with the same number of elements but different
9602 /// element type.
9603 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9604   const auto *VecTy = E->getType()->getAs<VectorType>();
9605   assert(VecTy && "Expression E must be a vector");
9606   QualType NewVecTy = S.Context.getVectorType(ElementType,
9607                                               VecTy->getNumElements(),
9608                                               VecTy->getVectorKind());
9609 
9610   // Look through the implicit cast. Return the subexpression if its type is
9611   // NewVecTy.
9612   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9613     if (ICE->getSubExpr()->getType() == NewVecTy)
9614       return ICE->getSubExpr();
9615 
9616   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9617   return S.ImpCastExprToType(E, NewVecTy, Cast);
9618 }
9619 
9620 /// Test if a (constant) integer Int can be casted to another integer type
9621 /// IntTy without losing precision.
9622 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9623                                       QualType OtherIntTy) {
9624   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9625 
9626   // Reject cases where the value of the Int is unknown as that would
9627   // possibly cause truncation, but accept cases where the scalar can be
9628   // demoted without loss of precision.
9629   Expr::EvalResult EVResult;
9630   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9631   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9632   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9633   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9634 
9635   if (CstInt) {
9636     // If the scalar is constant and is of a higher order and has more active
9637     // bits that the vector element type, reject it.
9638     llvm::APSInt Result = EVResult.Val.getInt();
9639     unsigned NumBits = IntSigned
9640                            ? (Result.isNegative() ? Result.getMinSignedBits()
9641                                                   : Result.getActiveBits())
9642                            : Result.getActiveBits();
9643     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9644       return true;
9645 
9646     // If the signedness of the scalar type and the vector element type
9647     // differs and the number of bits is greater than that of the vector
9648     // element reject it.
9649     return (IntSigned != OtherIntSigned &&
9650             NumBits > S.Context.getIntWidth(OtherIntTy));
9651   }
9652 
9653   // Reject cases where the value of the scalar is not constant and it's
9654   // order is greater than that of the vector element type.
9655   return (Order < 0);
9656 }
9657 
9658 /// Test if a (constant) integer Int can be casted to floating point type
9659 /// FloatTy without losing precision.
9660 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9661                                      QualType FloatTy) {
9662   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9663 
9664   // Determine if the integer constant can be expressed as a floating point
9665   // number of the appropriate type.
9666   Expr::EvalResult EVResult;
9667   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9668 
9669   uint64_t Bits = 0;
9670   if (CstInt) {
9671     // Reject constants that would be truncated if they were converted to
9672     // the floating point type. Test by simple to/from conversion.
9673     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9674     //        could be avoided if there was a convertFromAPInt method
9675     //        which could signal back if implicit truncation occurred.
9676     llvm::APSInt Result = EVResult.Val.getInt();
9677     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9678     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9679                            llvm::APFloat::rmTowardZero);
9680     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9681                              !IntTy->hasSignedIntegerRepresentation());
9682     bool Ignored = false;
9683     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9684                            &Ignored);
9685     if (Result != ConvertBack)
9686       return true;
9687   } else {
9688     // Reject types that cannot be fully encoded into the mantissa of
9689     // the float.
9690     Bits = S.Context.getTypeSize(IntTy);
9691     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9692         S.Context.getFloatTypeSemantics(FloatTy));
9693     if (Bits > FloatPrec)
9694       return true;
9695   }
9696 
9697   return false;
9698 }
9699 
9700 /// Attempt to convert and splat Scalar into a vector whose types matches
9701 /// Vector following GCC conversion rules. The rule is that implicit
9702 /// conversion can occur when Scalar can be casted to match Vector's element
9703 /// type without causing truncation of Scalar.
9704 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9705                                         ExprResult *Vector) {
9706   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9707   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9708   const VectorType *VT = VectorTy->getAs<VectorType>();
9709 
9710   assert(!isa<ExtVectorType>(VT) &&
9711          "ExtVectorTypes should not be handled here!");
9712 
9713   QualType VectorEltTy = VT->getElementType();
9714 
9715   // Reject cases where the vector element type or the scalar element type are
9716   // not integral or floating point types.
9717   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9718     return true;
9719 
9720   // The conversion to apply to the scalar before splatting it,
9721   // if necessary.
9722   CastKind ScalarCast = CK_NoOp;
9723 
9724   // Accept cases where the vector elements are integers and the scalar is
9725   // an integer.
9726   // FIXME: Notionally if the scalar was a floating point value with a precise
9727   //        integral representation, we could cast it to an appropriate integer
9728   //        type and then perform the rest of the checks here. GCC will perform
9729   //        this conversion in some cases as determined by the input language.
9730   //        We should accept it on a language independent basis.
9731   if (VectorEltTy->isIntegralType(S.Context) &&
9732       ScalarTy->isIntegralType(S.Context) &&
9733       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9734 
9735     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9736       return true;
9737 
9738     ScalarCast = CK_IntegralCast;
9739   } else if (VectorEltTy->isIntegralType(S.Context) &&
9740              ScalarTy->isRealFloatingType()) {
9741     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9742       ScalarCast = CK_FloatingToIntegral;
9743     else
9744       return true;
9745   } else if (VectorEltTy->isRealFloatingType()) {
9746     if (ScalarTy->isRealFloatingType()) {
9747 
9748       // Reject cases where the scalar type is not a constant and has a higher
9749       // Order than the vector element type.
9750       llvm::APFloat Result(0.0);
9751 
9752       // Determine whether this is a constant scalar. In the event that the
9753       // value is dependent (and thus cannot be evaluated by the constant
9754       // evaluator), skip the evaluation. This will then diagnose once the
9755       // expression is instantiated.
9756       bool CstScalar = Scalar->get()->isValueDependent() ||
9757                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9758       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9759       if (!CstScalar && Order < 0)
9760         return true;
9761 
9762       // If the scalar cannot be safely casted to the vector element type,
9763       // reject it.
9764       if (CstScalar) {
9765         bool Truncated = false;
9766         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9767                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9768         if (Truncated)
9769           return true;
9770       }
9771 
9772       ScalarCast = CK_FloatingCast;
9773     } else if (ScalarTy->isIntegralType(S.Context)) {
9774       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9775         return true;
9776 
9777       ScalarCast = CK_IntegralToFloating;
9778     } else
9779       return true;
9780   } else if (ScalarTy->isEnumeralType())
9781     return true;
9782 
9783   // Adjust scalar if desired.
9784   if (Scalar) {
9785     if (ScalarCast != CK_NoOp)
9786       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9787     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9788   }
9789   return false;
9790 }
9791 
9792 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9793                                    SourceLocation Loc, bool IsCompAssign,
9794                                    bool AllowBothBool,
9795                                    bool AllowBoolConversions) {
9796   if (!IsCompAssign) {
9797     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9798     if (LHS.isInvalid())
9799       return QualType();
9800   }
9801   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9802   if (RHS.isInvalid())
9803     return QualType();
9804 
9805   // For conversion purposes, we ignore any qualifiers.
9806   // For example, "const float" and "float" are equivalent.
9807   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9808   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9809 
9810   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9811   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9812   assert(LHSVecType || RHSVecType);
9813 
9814   // AltiVec-style "vector bool op vector bool" combinations are allowed
9815   // for some operators but not others.
9816   if (!AllowBothBool &&
9817       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9818       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9819     return InvalidOperands(Loc, LHS, RHS);
9820 
9821   // If the vector types are identical, return.
9822   if (Context.hasSameType(LHSType, RHSType))
9823     return LHSType;
9824 
9825   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9826   if (LHSVecType && RHSVecType &&
9827       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9828     if (isa<ExtVectorType>(LHSVecType)) {
9829       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9830       return LHSType;
9831     }
9832 
9833     if (!IsCompAssign)
9834       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9835     return RHSType;
9836   }
9837 
9838   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9839   // can be mixed, with the result being the non-bool type.  The non-bool
9840   // operand must have integer element type.
9841   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9842       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9843       (Context.getTypeSize(LHSVecType->getElementType()) ==
9844        Context.getTypeSize(RHSVecType->getElementType()))) {
9845     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9846         LHSVecType->getElementType()->isIntegerType() &&
9847         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9848       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9849       return LHSType;
9850     }
9851     if (!IsCompAssign &&
9852         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9853         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9854         RHSVecType->getElementType()->isIntegerType()) {
9855       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9856       return RHSType;
9857     }
9858   }
9859 
9860   // If there's a vector type and a scalar, try to convert the scalar to
9861   // the vector element type and splat.
9862   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9863   if (!RHSVecType) {
9864     if (isa<ExtVectorType>(LHSVecType)) {
9865       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9866                                     LHSVecType->getElementType(), LHSType,
9867                                     DiagID))
9868         return LHSType;
9869     } else {
9870       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9871         return LHSType;
9872     }
9873   }
9874   if (!LHSVecType) {
9875     if (isa<ExtVectorType>(RHSVecType)) {
9876       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9877                                     LHSType, RHSVecType->getElementType(),
9878                                     RHSType, DiagID))
9879         return RHSType;
9880     } else {
9881       if (LHS.get()->getValueKind() == VK_LValue ||
9882           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9883         return RHSType;
9884     }
9885   }
9886 
9887   // FIXME: The code below also handles conversion between vectors and
9888   // non-scalars, we should break this down into fine grained specific checks
9889   // and emit proper diagnostics.
9890   QualType VecType = LHSVecType ? LHSType : RHSType;
9891   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9892   QualType OtherType = LHSVecType ? RHSType : LHSType;
9893   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9894   if (isLaxVectorConversion(OtherType, VecType)) {
9895     // If we're allowing lax vector conversions, only the total (data) size
9896     // needs to be the same. For non compound assignment, if one of the types is
9897     // scalar, the result is always the vector type.
9898     if (!IsCompAssign) {
9899       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9900       return VecType;
9901     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9902     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9903     // type. Note that this is already done by non-compound assignments in
9904     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9905     // <1 x T> -> T. The result is also a vector type.
9906     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9907                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9908       ExprResult *RHSExpr = &RHS;
9909       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9910       return VecType;
9911     }
9912   }
9913 
9914   // Okay, the expression is invalid.
9915 
9916   // If there's a non-vector, non-real operand, diagnose that.
9917   if ((!RHSVecType && !RHSType->isRealType()) ||
9918       (!LHSVecType && !LHSType->isRealType())) {
9919     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9920       << LHSType << RHSType
9921       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9922     return QualType();
9923   }
9924 
9925   // OpenCL V1.1 6.2.6.p1:
9926   // If the operands are of more than one vector type, then an error shall
9927   // occur. Implicit conversions between vector types are not permitted, per
9928   // section 6.2.1.
9929   if (getLangOpts().OpenCL &&
9930       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9931       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9932     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9933                                                            << RHSType;
9934     return QualType();
9935   }
9936 
9937 
9938   // If there is a vector type that is not a ExtVector and a scalar, we reach
9939   // this point if scalar could not be converted to the vector's element type
9940   // without truncation.
9941   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9942       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9943     QualType Scalar = LHSVecType ? RHSType : LHSType;
9944     QualType Vector = LHSVecType ? LHSType : RHSType;
9945     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9946     Diag(Loc,
9947          diag::err_typecheck_vector_not_convertable_implict_truncation)
9948         << ScalarOrVector << Scalar << Vector;
9949 
9950     return QualType();
9951   }
9952 
9953   // Otherwise, use the generic diagnostic.
9954   Diag(Loc, DiagID)
9955     << LHSType << RHSType
9956     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9957   return QualType();
9958 }
9959 
9960 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9961 // expression.  These are mainly cases where the null pointer is used as an
9962 // integer instead of a pointer.
9963 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9964                                 SourceLocation Loc, bool IsCompare) {
9965   // The canonical way to check for a GNU null is with isNullPointerConstant,
9966   // but we use a bit of a hack here for speed; this is a relatively
9967   // hot path, and isNullPointerConstant is slow.
9968   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9969   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9970 
9971   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9972 
9973   // Avoid analyzing cases where the result will either be invalid (and
9974   // diagnosed as such) or entirely valid and not something to warn about.
9975   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9976       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9977     return;
9978 
9979   // Comparison operations would not make sense with a null pointer no matter
9980   // what the other expression is.
9981   if (!IsCompare) {
9982     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9983         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9984         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9985     return;
9986   }
9987 
9988   // The rest of the operations only make sense with a null pointer
9989   // if the other expression is a pointer.
9990   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9991       NonNullType->canDecayToPointerType())
9992     return;
9993 
9994   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9995       << LHSNull /* LHS is NULL */ << NonNullType
9996       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9997 }
9998 
9999 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10000                                           SourceLocation Loc) {
10001   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10002   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10003   if (!LUE || !RUE)
10004     return;
10005   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10006       RUE->getKind() != UETT_SizeOf)
10007     return;
10008 
10009   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10010   QualType LHSTy = LHSArg->getType();
10011   QualType RHSTy;
10012 
10013   if (RUE->isArgumentType())
10014     RHSTy = RUE->getArgumentType();
10015   else
10016     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10017 
10018   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10019     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10020       return;
10021 
10022     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10023     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10024       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10025         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10026             << LHSArgDecl;
10027     }
10028   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10029     QualType ArrayElemTy = ArrayTy->getElementType();
10030     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10031         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10032         ArrayElemTy->isCharType() ||
10033         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10034       return;
10035     S.Diag(Loc, diag::warn_division_sizeof_array)
10036         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10037     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10038       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10039         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10040             << LHSArgDecl;
10041     }
10042 
10043     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10044   }
10045 }
10046 
10047 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10048                                                ExprResult &RHS,
10049                                                SourceLocation Loc, bool IsDiv) {
10050   // Check for division/remainder by zero.
10051   Expr::EvalResult RHSValue;
10052   if (!RHS.get()->isValueDependent() &&
10053       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10054       RHSValue.Val.getInt() == 0)
10055     S.DiagRuntimeBehavior(Loc, RHS.get(),
10056                           S.PDiag(diag::warn_remainder_division_by_zero)
10057                             << IsDiv << RHS.get()->getSourceRange());
10058 }
10059 
10060 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10061                                            SourceLocation Loc,
10062                                            bool IsCompAssign, bool IsDiv) {
10063   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10064 
10065   if (LHS.get()->getType()->isVectorType() ||
10066       RHS.get()->getType()->isVectorType())
10067     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10068                                /*AllowBothBool*/getLangOpts().AltiVec,
10069                                /*AllowBoolConversions*/false);
10070   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10071                  RHS.get()->getType()->isConstantMatrixType()))
10072     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10073 
10074   QualType compType = UsualArithmeticConversions(
10075       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10076   if (LHS.isInvalid() || RHS.isInvalid())
10077     return QualType();
10078 
10079 
10080   if (compType.isNull() || !compType->isArithmeticType())
10081     return InvalidOperands(Loc, LHS, RHS);
10082   if (IsDiv) {
10083     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10084     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10085   }
10086   return compType;
10087 }
10088 
10089 QualType Sema::CheckRemainderOperands(
10090   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10091   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10092 
10093   if (LHS.get()->getType()->isVectorType() ||
10094       RHS.get()->getType()->isVectorType()) {
10095     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10096         RHS.get()->getType()->hasIntegerRepresentation())
10097       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10098                                  /*AllowBothBool*/getLangOpts().AltiVec,
10099                                  /*AllowBoolConversions*/false);
10100     return InvalidOperands(Loc, LHS, RHS);
10101   }
10102 
10103   QualType compType = UsualArithmeticConversions(
10104       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10105   if (LHS.isInvalid() || RHS.isInvalid())
10106     return QualType();
10107 
10108   if (compType.isNull() || !compType->isIntegerType())
10109     return InvalidOperands(Loc, LHS, RHS);
10110   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10111   return compType;
10112 }
10113 
10114 /// Diagnose invalid arithmetic on two void pointers.
10115 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10116                                                 Expr *LHSExpr, Expr *RHSExpr) {
10117   S.Diag(Loc, S.getLangOpts().CPlusPlus
10118                 ? diag::err_typecheck_pointer_arith_void_type
10119                 : diag::ext_gnu_void_ptr)
10120     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10121                             << RHSExpr->getSourceRange();
10122 }
10123 
10124 /// Diagnose invalid arithmetic on a void pointer.
10125 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10126                                             Expr *Pointer) {
10127   S.Diag(Loc, S.getLangOpts().CPlusPlus
10128                 ? diag::err_typecheck_pointer_arith_void_type
10129                 : diag::ext_gnu_void_ptr)
10130     << 0 /* one pointer */ << Pointer->getSourceRange();
10131 }
10132 
10133 /// Diagnose invalid arithmetic on a null pointer.
10134 ///
10135 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10136 /// idiom, which we recognize as a GNU extension.
10137 ///
10138 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10139                                             Expr *Pointer, bool IsGNUIdiom) {
10140   if (IsGNUIdiom)
10141     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10142       << Pointer->getSourceRange();
10143   else
10144     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10145       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10146 }
10147 
10148 /// Diagnose invalid arithmetic on two function pointers.
10149 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10150                                                     Expr *LHS, Expr *RHS) {
10151   assert(LHS->getType()->isAnyPointerType());
10152   assert(RHS->getType()->isAnyPointerType());
10153   S.Diag(Loc, S.getLangOpts().CPlusPlus
10154                 ? diag::err_typecheck_pointer_arith_function_type
10155                 : diag::ext_gnu_ptr_func_arith)
10156     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10157     // We only show the second type if it differs from the first.
10158     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10159                                                    RHS->getType())
10160     << RHS->getType()->getPointeeType()
10161     << LHS->getSourceRange() << RHS->getSourceRange();
10162 }
10163 
10164 /// Diagnose invalid arithmetic on a function pointer.
10165 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10166                                                 Expr *Pointer) {
10167   assert(Pointer->getType()->isAnyPointerType());
10168   S.Diag(Loc, S.getLangOpts().CPlusPlus
10169                 ? diag::err_typecheck_pointer_arith_function_type
10170                 : diag::ext_gnu_ptr_func_arith)
10171     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10172     << 0 /* one pointer, so only one type */
10173     << Pointer->getSourceRange();
10174 }
10175 
10176 /// Emit error if Operand is incomplete pointer type
10177 ///
10178 /// \returns True if pointer has incomplete type
10179 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10180                                                  Expr *Operand) {
10181   QualType ResType = Operand->getType();
10182   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10183     ResType = ResAtomicType->getValueType();
10184 
10185   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10186   QualType PointeeTy = ResType->getPointeeType();
10187   return S.RequireCompleteSizedType(
10188       Loc, PointeeTy,
10189       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10190       Operand->getSourceRange());
10191 }
10192 
10193 /// Check the validity of an arithmetic pointer operand.
10194 ///
10195 /// If the operand has pointer type, this code will check for pointer types
10196 /// which are invalid in arithmetic operations. These will be diagnosed
10197 /// appropriately, including whether or not the use is supported as an
10198 /// extension.
10199 ///
10200 /// \returns True when the operand is valid to use (even if as an extension).
10201 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10202                                             Expr *Operand) {
10203   QualType ResType = Operand->getType();
10204   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10205     ResType = ResAtomicType->getValueType();
10206 
10207   if (!ResType->isAnyPointerType()) return true;
10208 
10209   QualType PointeeTy = ResType->getPointeeType();
10210   if (PointeeTy->isVoidType()) {
10211     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10212     return !S.getLangOpts().CPlusPlus;
10213   }
10214   if (PointeeTy->isFunctionType()) {
10215     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10216     return !S.getLangOpts().CPlusPlus;
10217   }
10218 
10219   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10220 
10221   return true;
10222 }
10223 
10224 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10225 /// operands.
10226 ///
10227 /// This routine will diagnose any invalid arithmetic on pointer operands much
10228 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10229 /// for emitting a single diagnostic even for operations where both LHS and RHS
10230 /// are (potentially problematic) pointers.
10231 ///
10232 /// \returns True when the operand is valid to use (even if as an extension).
10233 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10234                                                 Expr *LHSExpr, Expr *RHSExpr) {
10235   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10236   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10237   if (!isLHSPointer && !isRHSPointer) return true;
10238 
10239   QualType LHSPointeeTy, RHSPointeeTy;
10240   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10241   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10242 
10243   // if both are pointers check if operation is valid wrt address spaces
10244   if (isLHSPointer && isRHSPointer) {
10245     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10246       S.Diag(Loc,
10247              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10248           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10249           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10250       return false;
10251     }
10252   }
10253 
10254   // Check for arithmetic on pointers to incomplete types.
10255   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10256   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10257   if (isLHSVoidPtr || isRHSVoidPtr) {
10258     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10259     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10260     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10261 
10262     return !S.getLangOpts().CPlusPlus;
10263   }
10264 
10265   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10266   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10267   if (isLHSFuncPtr || isRHSFuncPtr) {
10268     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10269     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10270                                                                 RHSExpr);
10271     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10272 
10273     return !S.getLangOpts().CPlusPlus;
10274   }
10275 
10276   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10277     return false;
10278   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10279     return false;
10280 
10281   return true;
10282 }
10283 
10284 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10285 /// literal.
10286 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10287                                   Expr *LHSExpr, Expr *RHSExpr) {
10288   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10289   Expr* IndexExpr = RHSExpr;
10290   if (!StrExpr) {
10291     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10292     IndexExpr = LHSExpr;
10293   }
10294 
10295   bool IsStringPlusInt = StrExpr &&
10296       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10297   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10298     return;
10299 
10300   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10301   Self.Diag(OpLoc, diag::warn_string_plus_int)
10302       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10303 
10304   // Only print a fixit for "str" + int, not for int + "str".
10305   if (IndexExpr == RHSExpr) {
10306     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10307     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10308         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10309         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10310         << FixItHint::CreateInsertion(EndLoc, "]");
10311   } else
10312     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10313 }
10314 
10315 /// Emit a warning when adding a char literal to a string.
10316 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10317                                    Expr *LHSExpr, Expr *RHSExpr) {
10318   const Expr *StringRefExpr = LHSExpr;
10319   const CharacterLiteral *CharExpr =
10320       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10321 
10322   if (!CharExpr) {
10323     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10324     StringRefExpr = RHSExpr;
10325   }
10326 
10327   if (!CharExpr || !StringRefExpr)
10328     return;
10329 
10330   const QualType StringType = StringRefExpr->getType();
10331 
10332   // Return if not a PointerType.
10333   if (!StringType->isAnyPointerType())
10334     return;
10335 
10336   // Return if not a CharacterType.
10337   if (!StringType->getPointeeType()->isAnyCharacterType())
10338     return;
10339 
10340   ASTContext &Ctx = Self.getASTContext();
10341   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10342 
10343   const QualType CharType = CharExpr->getType();
10344   if (!CharType->isAnyCharacterType() &&
10345       CharType->isIntegerType() &&
10346       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10347     Self.Diag(OpLoc, diag::warn_string_plus_char)
10348         << DiagRange << Ctx.CharTy;
10349   } else {
10350     Self.Diag(OpLoc, diag::warn_string_plus_char)
10351         << DiagRange << CharExpr->getType();
10352   }
10353 
10354   // Only print a fixit for str + char, not for char + str.
10355   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10356     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10357     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10358         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10359         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10360         << FixItHint::CreateInsertion(EndLoc, "]");
10361   } else {
10362     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10363   }
10364 }
10365 
10366 /// Emit error when two pointers are incompatible.
10367 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10368                                            Expr *LHSExpr, Expr *RHSExpr) {
10369   assert(LHSExpr->getType()->isAnyPointerType());
10370   assert(RHSExpr->getType()->isAnyPointerType());
10371   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10372     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10373     << RHSExpr->getSourceRange();
10374 }
10375 
10376 // C99 6.5.6
10377 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10378                                      SourceLocation Loc, BinaryOperatorKind Opc,
10379                                      QualType* CompLHSTy) {
10380   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10381 
10382   if (LHS.get()->getType()->isVectorType() ||
10383       RHS.get()->getType()->isVectorType()) {
10384     QualType compType = CheckVectorOperands(
10385         LHS, RHS, Loc, CompLHSTy,
10386         /*AllowBothBool*/getLangOpts().AltiVec,
10387         /*AllowBoolConversions*/getLangOpts().ZVector);
10388     if (CompLHSTy) *CompLHSTy = compType;
10389     return compType;
10390   }
10391 
10392   if (LHS.get()->getType()->isConstantMatrixType() ||
10393       RHS.get()->getType()->isConstantMatrixType()) {
10394     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10395   }
10396 
10397   QualType compType = UsualArithmeticConversions(
10398       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10399   if (LHS.isInvalid() || RHS.isInvalid())
10400     return QualType();
10401 
10402   // Diagnose "string literal" '+' int and string '+' "char literal".
10403   if (Opc == BO_Add) {
10404     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10405     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10406   }
10407 
10408   // handle the common case first (both operands are arithmetic).
10409   if (!compType.isNull() && compType->isArithmeticType()) {
10410     if (CompLHSTy) *CompLHSTy = compType;
10411     return compType;
10412   }
10413 
10414   // Type-checking.  Ultimately the pointer's going to be in PExp;
10415   // note that we bias towards the LHS being the pointer.
10416   Expr *PExp = LHS.get(), *IExp = RHS.get();
10417 
10418   bool isObjCPointer;
10419   if (PExp->getType()->isPointerType()) {
10420     isObjCPointer = false;
10421   } else if (PExp->getType()->isObjCObjectPointerType()) {
10422     isObjCPointer = true;
10423   } else {
10424     std::swap(PExp, IExp);
10425     if (PExp->getType()->isPointerType()) {
10426       isObjCPointer = false;
10427     } else if (PExp->getType()->isObjCObjectPointerType()) {
10428       isObjCPointer = true;
10429     } else {
10430       return InvalidOperands(Loc, LHS, RHS);
10431     }
10432   }
10433   assert(PExp->getType()->isAnyPointerType());
10434 
10435   if (!IExp->getType()->isIntegerType())
10436     return InvalidOperands(Loc, LHS, RHS);
10437 
10438   // Adding to a null pointer results in undefined behavior.
10439   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10440           Context, Expr::NPC_ValueDependentIsNotNull)) {
10441     // In C++ adding zero to a null pointer is defined.
10442     Expr::EvalResult KnownVal;
10443     if (!getLangOpts().CPlusPlus ||
10444         (!IExp->isValueDependent() &&
10445          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10446           KnownVal.Val.getInt() != 0))) {
10447       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10448       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10449           Context, BO_Add, PExp, IExp);
10450       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10451     }
10452   }
10453 
10454   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10455     return QualType();
10456 
10457   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10458     return QualType();
10459 
10460   // Check array bounds for pointer arithemtic
10461   CheckArrayAccess(PExp, IExp);
10462 
10463   if (CompLHSTy) {
10464     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10465     if (LHSTy.isNull()) {
10466       LHSTy = LHS.get()->getType();
10467       if (LHSTy->isPromotableIntegerType())
10468         LHSTy = Context.getPromotedIntegerType(LHSTy);
10469     }
10470     *CompLHSTy = LHSTy;
10471   }
10472 
10473   return PExp->getType();
10474 }
10475 
10476 // C99 6.5.6
10477 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10478                                         SourceLocation Loc,
10479                                         QualType* CompLHSTy) {
10480   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10481 
10482   if (LHS.get()->getType()->isVectorType() ||
10483       RHS.get()->getType()->isVectorType()) {
10484     QualType compType = CheckVectorOperands(
10485         LHS, RHS, Loc, CompLHSTy,
10486         /*AllowBothBool*/getLangOpts().AltiVec,
10487         /*AllowBoolConversions*/getLangOpts().ZVector);
10488     if (CompLHSTy) *CompLHSTy = compType;
10489     return compType;
10490   }
10491 
10492   if (LHS.get()->getType()->isConstantMatrixType() ||
10493       RHS.get()->getType()->isConstantMatrixType()) {
10494     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10495   }
10496 
10497   QualType compType = UsualArithmeticConversions(
10498       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10499   if (LHS.isInvalid() || RHS.isInvalid())
10500     return QualType();
10501 
10502   // Enforce type constraints: C99 6.5.6p3.
10503 
10504   // Handle the common case first (both operands are arithmetic).
10505   if (!compType.isNull() && compType->isArithmeticType()) {
10506     if (CompLHSTy) *CompLHSTy = compType;
10507     return compType;
10508   }
10509 
10510   // Either ptr - int   or   ptr - ptr.
10511   if (LHS.get()->getType()->isAnyPointerType()) {
10512     QualType lpointee = LHS.get()->getType()->getPointeeType();
10513 
10514     // Diagnose bad cases where we step over interface counts.
10515     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10516         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10517       return QualType();
10518 
10519     // The result type of a pointer-int computation is the pointer type.
10520     if (RHS.get()->getType()->isIntegerType()) {
10521       // Subtracting from a null pointer should produce a warning.
10522       // The last argument to the diagnose call says this doesn't match the
10523       // GNU int-to-pointer idiom.
10524       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10525                                            Expr::NPC_ValueDependentIsNotNull)) {
10526         // In C++ adding zero to a null pointer is defined.
10527         Expr::EvalResult KnownVal;
10528         if (!getLangOpts().CPlusPlus ||
10529             (!RHS.get()->isValueDependent() &&
10530              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10531               KnownVal.Val.getInt() != 0))) {
10532           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10533         }
10534       }
10535 
10536       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10537         return QualType();
10538 
10539       // Check array bounds for pointer arithemtic
10540       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10541                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10542 
10543       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10544       return LHS.get()->getType();
10545     }
10546 
10547     // Handle pointer-pointer subtractions.
10548     if (const PointerType *RHSPTy
10549           = RHS.get()->getType()->getAs<PointerType>()) {
10550       QualType rpointee = RHSPTy->getPointeeType();
10551 
10552       if (getLangOpts().CPlusPlus) {
10553         // Pointee types must be the same: C++ [expr.add]
10554         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10555           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10556         }
10557       } else {
10558         // Pointee types must be compatible C99 6.5.6p3
10559         if (!Context.typesAreCompatible(
10560                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10561                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10562           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10563           return QualType();
10564         }
10565       }
10566 
10567       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10568                                                LHS.get(), RHS.get()))
10569         return QualType();
10570 
10571       // FIXME: Add warnings for nullptr - ptr.
10572 
10573       // The pointee type may have zero size.  As an extension, a structure or
10574       // union may have zero size or an array may have zero length.  In this
10575       // case subtraction does not make sense.
10576       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10577         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10578         if (ElementSize.isZero()) {
10579           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10580             << rpointee.getUnqualifiedType()
10581             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10582         }
10583       }
10584 
10585       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10586       return Context.getPointerDiffType();
10587     }
10588   }
10589 
10590   return InvalidOperands(Loc, LHS, RHS);
10591 }
10592 
10593 static bool isScopedEnumerationType(QualType T) {
10594   if (const EnumType *ET = T->getAs<EnumType>())
10595     return ET->getDecl()->isScoped();
10596   return false;
10597 }
10598 
10599 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10600                                    SourceLocation Loc, BinaryOperatorKind Opc,
10601                                    QualType LHSType) {
10602   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10603   // so skip remaining warnings as we don't want to modify values within Sema.
10604   if (S.getLangOpts().OpenCL)
10605     return;
10606 
10607   // Check right/shifter operand
10608   Expr::EvalResult RHSResult;
10609   if (RHS.get()->isValueDependent() ||
10610       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10611     return;
10612   llvm::APSInt Right = RHSResult.Val.getInt();
10613 
10614   if (Right.isNegative()) {
10615     S.DiagRuntimeBehavior(Loc, RHS.get(),
10616                           S.PDiag(diag::warn_shift_negative)
10617                             << RHS.get()->getSourceRange());
10618     return;
10619   }
10620 
10621   QualType LHSExprType = LHS.get()->getType();
10622   uint64_t LeftSize = LHSExprType->isExtIntType()
10623                           ? S.Context.getIntWidth(LHSExprType)
10624                           : S.Context.getTypeSize(LHSExprType);
10625   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10626   if (Right.uge(LeftBits)) {
10627     S.DiagRuntimeBehavior(Loc, RHS.get(),
10628                           S.PDiag(diag::warn_shift_gt_typewidth)
10629                             << RHS.get()->getSourceRange());
10630     return;
10631   }
10632 
10633   if (Opc != BO_Shl)
10634     return;
10635 
10636   // When left shifting an ICE which is signed, we can check for overflow which
10637   // according to C++ standards prior to C++2a has undefined behavior
10638   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10639   // more than the maximum value representable in the result type, so never
10640   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10641   // expression is still probably a bug.)
10642   Expr::EvalResult LHSResult;
10643   if (LHS.get()->isValueDependent() ||
10644       LHSType->hasUnsignedIntegerRepresentation() ||
10645       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10646     return;
10647   llvm::APSInt Left = LHSResult.Val.getInt();
10648 
10649   // If LHS does not have a signed type and non-negative value
10650   // then, the behavior is undefined before C++2a. Warn about it.
10651   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10652       !S.getLangOpts().CPlusPlus20) {
10653     S.DiagRuntimeBehavior(Loc, LHS.get(),
10654                           S.PDiag(diag::warn_shift_lhs_negative)
10655                             << LHS.get()->getSourceRange());
10656     return;
10657   }
10658 
10659   llvm::APInt ResultBits =
10660       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10661   if (LeftBits.uge(ResultBits))
10662     return;
10663   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10664   Result = Result.shl(Right);
10665 
10666   // Print the bit representation of the signed integer as an unsigned
10667   // hexadecimal number.
10668   SmallString<40> HexResult;
10669   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10670 
10671   // If we are only missing a sign bit, this is less likely to result in actual
10672   // bugs -- if the result is cast back to an unsigned type, it will have the
10673   // expected value. Thus we place this behind a different warning that can be
10674   // turned off separately if needed.
10675   if (LeftBits == ResultBits - 1) {
10676     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10677         << HexResult << LHSType
10678         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10679     return;
10680   }
10681 
10682   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10683     << HexResult.str() << Result.getMinSignedBits() << LHSType
10684     << Left.getBitWidth() << LHS.get()->getSourceRange()
10685     << RHS.get()->getSourceRange();
10686 }
10687 
10688 /// Return the resulting type when a vector is shifted
10689 ///        by a scalar or vector shift amount.
10690 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10691                                  SourceLocation Loc, bool IsCompAssign) {
10692   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10693   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10694       !LHS.get()->getType()->isVectorType()) {
10695     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10696       << RHS.get()->getType() << LHS.get()->getType()
10697       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10698     return QualType();
10699   }
10700 
10701   if (!IsCompAssign) {
10702     LHS = S.UsualUnaryConversions(LHS.get());
10703     if (LHS.isInvalid()) return QualType();
10704   }
10705 
10706   RHS = S.UsualUnaryConversions(RHS.get());
10707   if (RHS.isInvalid()) return QualType();
10708 
10709   QualType LHSType = LHS.get()->getType();
10710   // Note that LHS might be a scalar because the routine calls not only in
10711   // OpenCL case.
10712   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10713   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10714 
10715   // Note that RHS might not be a vector.
10716   QualType RHSType = RHS.get()->getType();
10717   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10718   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10719 
10720   // The operands need to be integers.
10721   if (!LHSEleType->isIntegerType()) {
10722     S.Diag(Loc, diag::err_typecheck_expect_int)
10723       << LHS.get()->getType() << LHS.get()->getSourceRange();
10724     return QualType();
10725   }
10726 
10727   if (!RHSEleType->isIntegerType()) {
10728     S.Diag(Loc, diag::err_typecheck_expect_int)
10729       << RHS.get()->getType() << RHS.get()->getSourceRange();
10730     return QualType();
10731   }
10732 
10733   if (!LHSVecTy) {
10734     assert(RHSVecTy);
10735     if (IsCompAssign)
10736       return RHSType;
10737     if (LHSEleType != RHSEleType) {
10738       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10739       LHSEleType = RHSEleType;
10740     }
10741     QualType VecTy =
10742         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10743     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10744     LHSType = VecTy;
10745   } else if (RHSVecTy) {
10746     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10747     // are applied component-wise. So if RHS is a vector, then ensure
10748     // that the number of elements is the same as LHS...
10749     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10750       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10751         << LHS.get()->getType() << RHS.get()->getType()
10752         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10753       return QualType();
10754     }
10755     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10756       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10757       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10758       if (LHSBT != RHSBT &&
10759           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10760         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10761             << LHS.get()->getType() << RHS.get()->getType()
10762             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10763       }
10764     }
10765   } else {
10766     // ...else expand RHS to match the number of elements in LHS.
10767     QualType VecTy =
10768       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10769     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10770   }
10771 
10772   return LHSType;
10773 }
10774 
10775 // C99 6.5.7
10776 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10777                                   SourceLocation Loc, BinaryOperatorKind Opc,
10778                                   bool IsCompAssign) {
10779   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10780 
10781   // Vector shifts promote their scalar inputs to vector type.
10782   if (LHS.get()->getType()->isVectorType() ||
10783       RHS.get()->getType()->isVectorType()) {
10784     if (LangOpts.ZVector) {
10785       // The shift operators for the z vector extensions work basically
10786       // like general shifts, except that neither the LHS nor the RHS is
10787       // allowed to be a "vector bool".
10788       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10789         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10790           return InvalidOperands(Loc, LHS, RHS);
10791       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10792         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10793           return InvalidOperands(Loc, LHS, RHS);
10794     }
10795     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10796   }
10797 
10798   // Shifts don't perform usual arithmetic conversions, they just do integer
10799   // promotions on each operand. C99 6.5.7p3
10800 
10801   // For the LHS, do usual unary conversions, but then reset them away
10802   // if this is a compound assignment.
10803   ExprResult OldLHS = LHS;
10804   LHS = UsualUnaryConversions(LHS.get());
10805   if (LHS.isInvalid())
10806     return QualType();
10807   QualType LHSType = LHS.get()->getType();
10808   if (IsCompAssign) LHS = OldLHS;
10809 
10810   // The RHS is simpler.
10811   RHS = UsualUnaryConversions(RHS.get());
10812   if (RHS.isInvalid())
10813     return QualType();
10814   QualType RHSType = RHS.get()->getType();
10815 
10816   // C99 6.5.7p2: Each of the operands shall have integer type.
10817   if (!LHSType->hasIntegerRepresentation() ||
10818       !RHSType->hasIntegerRepresentation())
10819     return InvalidOperands(Loc, LHS, RHS);
10820 
10821   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10822   // hasIntegerRepresentation() above instead of this.
10823   if (isScopedEnumerationType(LHSType) ||
10824       isScopedEnumerationType(RHSType)) {
10825     return InvalidOperands(Loc, LHS, RHS);
10826   }
10827   // Sanity-check shift operands
10828   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10829 
10830   // "The type of the result is that of the promoted left operand."
10831   return LHSType;
10832 }
10833 
10834 /// Diagnose bad pointer comparisons.
10835 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10836                                               ExprResult &LHS, ExprResult &RHS,
10837                                               bool IsError) {
10838   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10839                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10840     << LHS.get()->getType() << RHS.get()->getType()
10841     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10842 }
10843 
10844 /// Returns false if the pointers are converted to a composite type,
10845 /// true otherwise.
10846 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10847                                            ExprResult &LHS, ExprResult &RHS) {
10848   // C++ [expr.rel]p2:
10849   //   [...] Pointer conversions (4.10) and qualification
10850   //   conversions (4.4) are performed on pointer operands (or on
10851   //   a pointer operand and a null pointer constant) to bring
10852   //   them to their composite pointer type. [...]
10853   //
10854   // C++ [expr.eq]p1 uses the same notion for (in)equality
10855   // comparisons of pointers.
10856 
10857   QualType LHSType = LHS.get()->getType();
10858   QualType RHSType = RHS.get()->getType();
10859   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10860          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10861 
10862   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10863   if (T.isNull()) {
10864     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10865         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10866       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10867     else
10868       S.InvalidOperands(Loc, LHS, RHS);
10869     return true;
10870   }
10871 
10872   return false;
10873 }
10874 
10875 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10876                                                     ExprResult &LHS,
10877                                                     ExprResult &RHS,
10878                                                     bool IsError) {
10879   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10880                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10881     << LHS.get()->getType() << RHS.get()->getType()
10882     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10883 }
10884 
10885 static bool isObjCObjectLiteral(ExprResult &E) {
10886   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10887   case Stmt::ObjCArrayLiteralClass:
10888   case Stmt::ObjCDictionaryLiteralClass:
10889   case Stmt::ObjCStringLiteralClass:
10890   case Stmt::ObjCBoxedExprClass:
10891     return true;
10892   default:
10893     // Note that ObjCBoolLiteral is NOT an object literal!
10894     return false;
10895   }
10896 }
10897 
10898 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10899   const ObjCObjectPointerType *Type =
10900     LHS->getType()->getAs<ObjCObjectPointerType>();
10901 
10902   // If this is not actually an Objective-C object, bail out.
10903   if (!Type)
10904     return false;
10905 
10906   // Get the LHS object's interface type.
10907   QualType InterfaceType = Type->getPointeeType();
10908 
10909   // If the RHS isn't an Objective-C object, bail out.
10910   if (!RHS->getType()->isObjCObjectPointerType())
10911     return false;
10912 
10913   // Try to find the -isEqual: method.
10914   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10915   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10916                                                       InterfaceType,
10917                                                       /*IsInstance=*/true);
10918   if (!Method) {
10919     if (Type->isObjCIdType()) {
10920       // For 'id', just check the global pool.
10921       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10922                                                   /*receiverId=*/true);
10923     } else {
10924       // Check protocols.
10925       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10926                                              /*IsInstance=*/true);
10927     }
10928   }
10929 
10930   if (!Method)
10931     return false;
10932 
10933   QualType T = Method->parameters()[0]->getType();
10934   if (!T->isObjCObjectPointerType())
10935     return false;
10936 
10937   QualType R = Method->getReturnType();
10938   if (!R->isScalarType())
10939     return false;
10940 
10941   return true;
10942 }
10943 
10944 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10945   FromE = FromE->IgnoreParenImpCasts();
10946   switch (FromE->getStmtClass()) {
10947     default:
10948       break;
10949     case Stmt::ObjCStringLiteralClass:
10950       // "string literal"
10951       return LK_String;
10952     case Stmt::ObjCArrayLiteralClass:
10953       // "array literal"
10954       return LK_Array;
10955     case Stmt::ObjCDictionaryLiteralClass:
10956       // "dictionary literal"
10957       return LK_Dictionary;
10958     case Stmt::BlockExprClass:
10959       return LK_Block;
10960     case Stmt::ObjCBoxedExprClass: {
10961       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10962       switch (Inner->getStmtClass()) {
10963         case Stmt::IntegerLiteralClass:
10964         case Stmt::FloatingLiteralClass:
10965         case Stmt::CharacterLiteralClass:
10966         case Stmt::ObjCBoolLiteralExprClass:
10967         case Stmt::CXXBoolLiteralExprClass:
10968           // "numeric literal"
10969           return LK_Numeric;
10970         case Stmt::ImplicitCastExprClass: {
10971           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10972           // Boolean literals can be represented by implicit casts.
10973           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10974             return LK_Numeric;
10975           break;
10976         }
10977         default:
10978           break;
10979       }
10980       return LK_Boxed;
10981     }
10982   }
10983   return LK_None;
10984 }
10985 
10986 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10987                                           ExprResult &LHS, ExprResult &RHS,
10988                                           BinaryOperator::Opcode Opc){
10989   Expr *Literal;
10990   Expr *Other;
10991   if (isObjCObjectLiteral(LHS)) {
10992     Literal = LHS.get();
10993     Other = RHS.get();
10994   } else {
10995     Literal = RHS.get();
10996     Other = LHS.get();
10997   }
10998 
10999   // Don't warn on comparisons against nil.
11000   Other = Other->IgnoreParenCasts();
11001   if (Other->isNullPointerConstant(S.getASTContext(),
11002                                    Expr::NPC_ValueDependentIsNotNull))
11003     return;
11004 
11005   // This should be kept in sync with warn_objc_literal_comparison.
11006   // LK_String should always be after the other literals, since it has its own
11007   // warning flag.
11008   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11009   assert(LiteralKind != Sema::LK_Block);
11010   if (LiteralKind == Sema::LK_None) {
11011     llvm_unreachable("Unknown Objective-C object literal kind");
11012   }
11013 
11014   if (LiteralKind == Sema::LK_String)
11015     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11016       << Literal->getSourceRange();
11017   else
11018     S.Diag(Loc, diag::warn_objc_literal_comparison)
11019       << LiteralKind << Literal->getSourceRange();
11020 
11021   if (BinaryOperator::isEqualityOp(Opc) &&
11022       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11023     SourceLocation Start = LHS.get()->getBeginLoc();
11024     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11025     CharSourceRange OpRange =
11026       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11027 
11028     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11029       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11030       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11031       << FixItHint::CreateInsertion(End, "]");
11032   }
11033 }
11034 
11035 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11036 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11037                                            ExprResult &RHS, SourceLocation Loc,
11038                                            BinaryOperatorKind Opc) {
11039   // Check that left hand side is !something.
11040   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11041   if (!UO || UO->getOpcode() != UO_LNot) return;
11042 
11043   // Only check if the right hand side is non-bool arithmetic type.
11044   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11045 
11046   // Make sure that the something in !something is not bool.
11047   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11048   if (SubExpr->isKnownToHaveBooleanValue()) return;
11049 
11050   // Emit warning.
11051   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11052   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11053       << Loc << IsBitwiseOp;
11054 
11055   // First note suggest !(x < y)
11056   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11057   SourceLocation FirstClose = RHS.get()->getEndLoc();
11058   FirstClose = S.getLocForEndOfToken(FirstClose);
11059   if (FirstClose.isInvalid())
11060     FirstOpen = SourceLocation();
11061   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11062       << IsBitwiseOp
11063       << FixItHint::CreateInsertion(FirstOpen, "(")
11064       << FixItHint::CreateInsertion(FirstClose, ")");
11065 
11066   // Second note suggests (!x) < y
11067   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11068   SourceLocation SecondClose = LHS.get()->getEndLoc();
11069   SecondClose = S.getLocForEndOfToken(SecondClose);
11070   if (SecondClose.isInvalid())
11071     SecondOpen = SourceLocation();
11072   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11073       << FixItHint::CreateInsertion(SecondOpen, "(")
11074       << FixItHint::CreateInsertion(SecondClose, ")");
11075 }
11076 
11077 // Returns true if E refers to a non-weak array.
11078 static bool checkForArray(const Expr *E) {
11079   const ValueDecl *D = nullptr;
11080   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11081     D = DR->getDecl();
11082   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11083     if (Mem->isImplicitAccess())
11084       D = Mem->getMemberDecl();
11085   }
11086   if (!D)
11087     return false;
11088   return D->getType()->isArrayType() && !D->isWeak();
11089 }
11090 
11091 /// Diagnose some forms of syntactically-obvious tautological comparison.
11092 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11093                                            Expr *LHS, Expr *RHS,
11094                                            BinaryOperatorKind Opc) {
11095   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11096   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11097 
11098   QualType LHSType = LHS->getType();
11099   QualType RHSType = RHS->getType();
11100   if (LHSType->hasFloatingRepresentation() ||
11101       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11102       S.inTemplateInstantiation())
11103     return;
11104 
11105   // Comparisons between two array types are ill-formed for operator<=>, so
11106   // we shouldn't emit any additional warnings about it.
11107   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11108     return;
11109 
11110   // For non-floating point types, check for self-comparisons of the form
11111   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11112   // often indicate logic errors in the program.
11113   //
11114   // NOTE: Don't warn about comparison expressions resulting from macro
11115   // expansion. Also don't warn about comparisons which are only self
11116   // comparisons within a template instantiation. The warnings should catch
11117   // obvious cases in the definition of the template anyways. The idea is to
11118   // warn when the typed comparison operator will always evaluate to the same
11119   // result.
11120 
11121   // Used for indexing into %select in warn_comparison_always
11122   enum {
11123     AlwaysConstant,
11124     AlwaysTrue,
11125     AlwaysFalse,
11126     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11127   };
11128 
11129   // C++2a [depr.array.comp]:
11130   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11131   //   operands of array type are deprecated.
11132   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11133       RHSStripped->getType()->isArrayType()) {
11134     S.Diag(Loc, diag::warn_depr_array_comparison)
11135         << LHS->getSourceRange() << RHS->getSourceRange()
11136         << LHSStripped->getType() << RHSStripped->getType();
11137     // Carry on to produce the tautological comparison warning, if this
11138     // expression is potentially-evaluated, we can resolve the array to a
11139     // non-weak declaration, and so on.
11140   }
11141 
11142   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11143     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11144       unsigned Result;
11145       switch (Opc) {
11146       case BO_EQ:
11147       case BO_LE:
11148       case BO_GE:
11149         Result = AlwaysTrue;
11150         break;
11151       case BO_NE:
11152       case BO_LT:
11153       case BO_GT:
11154         Result = AlwaysFalse;
11155         break;
11156       case BO_Cmp:
11157         Result = AlwaysEqual;
11158         break;
11159       default:
11160         Result = AlwaysConstant;
11161         break;
11162       }
11163       S.DiagRuntimeBehavior(Loc, nullptr,
11164                             S.PDiag(diag::warn_comparison_always)
11165                                 << 0 /*self-comparison*/
11166                                 << Result);
11167     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11168       // What is it always going to evaluate to?
11169       unsigned Result;
11170       switch (Opc) {
11171       case BO_EQ: // e.g. array1 == array2
11172         Result = AlwaysFalse;
11173         break;
11174       case BO_NE: // e.g. array1 != array2
11175         Result = AlwaysTrue;
11176         break;
11177       default: // e.g. array1 <= array2
11178         // The best we can say is 'a constant'
11179         Result = AlwaysConstant;
11180         break;
11181       }
11182       S.DiagRuntimeBehavior(Loc, nullptr,
11183                             S.PDiag(diag::warn_comparison_always)
11184                                 << 1 /*array comparison*/
11185                                 << Result);
11186     }
11187   }
11188 
11189   if (isa<CastExpr>(LHSStripped))
11190     LHSStripped = LHSStripped->IgnoreParenCasts();
11191   if (isa<CastExpr>(RHSStripped))
11192     RHSStripped = RHSStripped->IgnoreParenCasts();
11193 
11194   // Warn about comparisons against a string constant (unless the other
11195   // operand is null); the user probably wants string comparison function.
11196   Expr *LiteralString = nullptr;
11197   Expr *LiteralStringStripped = nullptr;
11198   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11199       !RHSStripped->isNullPointerConstant(S.Context,
11200                                           Expr::NPC_ValueDependentIsNull)) {
11201     LiteralString = LHS;
11202     LiteralStringStripped = LHSStripped;
11203   } else if ((isa<StringLiteral>(RHSStripped) ||
11204               isa<ObjCEncodeExpr>(RHSStripped)) &&
11205              !LHSStripped->isNullPointerConstant(S.Context,
11206                                           Expr::NPC_ValueDependentIsNull)) {
11207     LiteralString = RHS;
11208     LiteralStringStripped = RHSStripped;
11209   }
11210 
11211   if (LiteralString) {
11212     S.DiagRuntimeBehavior(Loc, nullptr,
11213                           S.PDiag(diag::warn_stringcompare)
11214                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11215                               << LiteralString->getSourceRange());
11216   }
11217 }
11218 
11219 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11220   switch (CK) {
11221   default: {
11222 #ifndef NDEBUG
11223     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11224                  << "\n";
11225 #endif
11226     llvm_unreachable("unhandled cast kind");
11227   }
11228   case CK_UserDefinedConversion:
11229     return ICK_Identity;
11230   case CK_LValueToRValue:
11231     return ICK_Lvalue_To_Rvalue;
11232   case CK_ArrayToPointerDecay:
11233     return ICK_Array_To_Pointer;
11234   case CK_FunctionToPointerDecay:
11235     return ICK_Function_To_Pointer;
11236   case CK_IntegralCast:
11237     return ICK_Integral_Conversion;
11238   case CK_FloatingCast:
11239     return ICK_Floating_Conversion;
11240   case CK_IntegralToFloating:
11241   case CK_FloatingToIntegral:
11242     return ICK_Floating_Integral;
11243   case CK_IntegralComplexCast:
11244   case CK_FloatingComplexCast:
11245   case CK_FloatingComplexToIntegralComplex:
11246   case CK_IntegralComplexToFloatingComplex:
11247     return ICK_Complex_Conversion;
11248   case CK_FloatingComplexToReal:
11249   case CK_FloatingRealToComplex:
11250   case CK_IntegralComplexToReal:
11251   case CK_IntegralRealToComplex:
11252     return ICK_Complex_Real;
11253   }
11254 }
11255 
11256 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11257                                              QualType FromType,
11258                                              SourceLocation Loc) {
11259   // Check for a narrowing implicit conversion.
11260   StandardConversionSequence SCS;
11261   SCS.setAsIdentityConversion();
11262   SCS.setToType(0, FromType);
11263   SCS.setToType(1, ToType);
11264   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11265     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11266 
11267   APValue PreNarrowingValue;
11268   QualType PreNarrowingType;
11269   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11270                                PreNarrowingType,
11271                                /*IgnoreFloatToIntegralConversion*/ true)) {
11272   case NK_Dependent_Narrowing:
11273     // Implicit conversion to a narrower type, but the expression is
11274     // value-dependent so we can't tell whether it's actually narrowing.
11275   case NK_Not_Narrowing:
11276     return false;
11277 
11278   case NK_Constant_Narrowing:
11279     // Implicit conversion to a narrower type, and the value is not a constant
11280     // expression.
11281     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11282         << /*Constant*/ 1
11283         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11284     return true;
11285 
11286   case NK_Variable_Narrowing:
11287     // Implicit conversion to a narrower type, and the value is not a constant
11288     // expression.
11289   case NK_Type_Narrowing:
11290     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11291         << /*Constant*/ 0 << FromType << ToType;
11292     // TODO: It's not a constant expression, but what if the user intended it
11293     // to be? Can we produce notes to help them figure out why it isn't?
11294     return true;
11295   }
11296   llvm_unreachable("unhandled case in switch");
11297 }
11298 
11299 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11300                                                          ExprResult &LHS,
11301                                                          ExprResult &RHS,
11302                                                          SourceLocation Loc) {
11303   QualType LHSType = LHS.get()->getType();
11304   QualType RHSType = RHS.get()->getType();
11305   // Dig out the original argument type and expression before implicit casts
11306   // were applied. These are the types/expressions we need to check the
11307   // [expr.spaceship] requirements against.
11308   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11309   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11310   QualType LHSStrippedType = LHSStripped.get()->getType();
11311   QualType RHSStrippedType = RHSStripped.get()->getType();
11312 
11313   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11314   // other is not, the program is ill-formed.
11315   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11316     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11317     return QualType();
11318   }
11319 
11320   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11321   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11322                     RHSStrippedType->isEnumeralType();
11323   if (NumEnumArgs == 1) {
11324     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11325     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11326     if (OtherTy->hasFloatingRepresentation()) {
11327       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11328       return QualType();
11329     }
11330   }
11331   if (NumEnumArgs == 2) {
11332     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11333     // type E, the operator yields the result of converting the operands
11334     // to the underlying type of E and applying <=> to the converted operands.
11335     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11336       S.InvalidOperands(Loc, LHS, RHS);
11337       return QualType();
11338     }
11339     QualType IntType =
11340         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11341     assert(IntType->isArithmeticType());
11342 
11343     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11344     // promote the boolean type, and all other promotable integer types, to
11345     // avoid this.
11346     if (IntType->isPromotableIntegerType())
11347       IntType = S.Context.getPromotedIntegerType(IntType);
11348 
11349     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11350     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11351     LHSType = RHSType = IntType;
11352   }
11353 
11354   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11355   // usual arithmetic conversions are applied to the operands.
11356   QualType Type =
11357       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11358   if (LHS.isInvalid() || RHS.isInvalid())
11359     return QualType();
11360   if (Type.isNull())
11361     return S.InvalidOperands(Loc, LHS, RHS);
11362 
11363   Optional<ComparisonCategoryType> CCT =
11364       getComparisonCategoryForBuiltinCmp(Type);
11365   if (!CCT)
11366     return S.InvalidOperands(Loc, LHS, RHS);
11367 
11368   bool HasNarrowing = checkThreeWayNarrowingConversion(
11369       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11370   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11371                                                    RHS.get()->getBeginLoc());
11372   if (HasNarrowing)
11373     return QualType();
11374 
11375   assert(!Type.isNull() && "composite type for <=> has not been set");
11376 
11377   return S.CheckComparisonCategoryType(
11378       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11379 }
11380 
11381 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11382                                                  ExprResult &RHS,
11383                                                  SourceLocation Loc,
11384                                                  BinaryOperatorKind Opc) {
11385   if (Opc == BO_Cmp)
11386     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11387 
11388   // C99 6.5.8p3 / C99 6.5.9p4
11389   QualType Type =
11390       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11391   if (LHS.isInvalid() || RHS.isInvalid())
11392     return QualType();
11393   if (Type.isNull())
11394     return S.InvalidOperands(Loc, LHS, RHS);
11395   assert(Type->isArithmeticType() || Type->isEnumeralType());
11396 
11397   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11398     return S.InvalidOperands(Loc, LHS, RHS);
11399 
11400   // Check for comparisons of floating point operands using != and ==.
11401   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11402     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11403 
11404   // The result of comparisons is 'bool' in C++, 'int' in C.
11405   return S.Context.getLogicalOperationType();
11406 }
11407 
11408 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11409   if (!NullE.get()->getType()->isAnyPointerType())
11410     return;
11411   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11412   if (!E.get()->getType()->isAnyPointerType() &&
11413       E.get()->isNullPointerConstant(Context,
11414                                      Expr::NPC_ValueDependentIsNotNull) ==
11415         Expr::NPCK_ZeroExpression) {
11416     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11417       if (CL->getValue() == 0)
11418         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11419             << NullValue
11420             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11421                                             NullValue ? "NULL" : "(void *)0");
11422     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11423         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11424         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11425         if (T == Context.CharTy)
11426           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11427               << NullValue
11428               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11429                                               NullValue ? "NULL" : "(void *)0");
11430       }
11431   }
11432 }
11433 
11434 // C99 6.5.8, C++ [expr.rel]
11435 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11436                                     SourceLocation Loc,
11437                                     BinaryOperatorKind Opc) {
11438   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11439   bool IsThreeWay = Opc == BO_Cmp;
11440   bool IsOrdered = IsRelational || IsThreeWay;
11441   auto IsAnyPointerType = [](ExprResult E) {
11442     QualType Ty = E.get()->getType();
11443     return Ty->isPointerType() || Ty->isMemberPointerType();
11444   };
11445 
11446   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11447   // type, array-to-pointer, ..., conversions are performed on both operands to
11448   // bring them to their composite type.
11449   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11450   // any type-related checks.
11451   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11452     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11453     if (LHS.isInvalid())
11454       return QualType();
11455     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11456     if (RHS.isInvalid())
11457       return QualType();
11458   } else {
11459     LHS = DefaultLvalueConversion(LHS.get());
11460     if (LHS.isInvalid())
11461       return QualType();
11462     RHS = DefaultLvalueConversion(RHS.get());
11463     if (RHS.isInvalid())
11464       return QualType();
11465   }
11466 
11467   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11468   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11469     CheckPtrComparisonWithNullChar(LHS, RHS);
11470     CheckPtrComparisonWithNullChar(RHS, LHS);
11471   }
11472 
11473   // Handle vector comparisons separately.
11474   if (LHS.get()->getType()->isVectorType() ||
11475       RHS.get()->getType()->isVectorType())
11476     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11477 
11478   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11479   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11480 
11481   QualType LHSType = LHS.get()->getType();
11482   QualType RHSType = RHS.get()->getType();
11483   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11484       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11485     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11486 
11487   const Expr::NullPointerConstantKind LHSNullKind =
11488       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11489   const Expr::NullPointerConstantKind RHSNullKind =
11490       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11491   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11492   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11493 
11494   auto computeResultTy = [&]() {
11495     if (Opc != BO_Cmp)
11496       return Context.getLogicalOperationType();
11497     assert(getLangOpts().CPlusPlus);
11498     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11499 
11500     QualType CompositeTy = LHS.get()->getType();
11501     assert(!CompositeTy->isReferenceType());
11502 
11503     Optional<ComparisonCategoryType> CCT =
11504         getComparisonCategoryForBuiltinCmp(CompositeTy);
11505     if (!CCT)
11506       return InvalidOperands(Loc, LHS, RHS);
11507 
11508     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11509       // P0946R0: Comparisons between a null pointer constant and an object
11510       // pointer result in std::strong_equality, which is ill-formed under
11511       // P1959R0.
11512       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11513           << (LHSIsNull ? LHS.get()->getSourceRange()
11514                         : RHS.get()->getSourceRange());
11515       return QualType();
11516     }
11517 
11518     return CheckComparisonCategoryType(
11519         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11520   };
11521 
11522   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11523     bool IsEquality = Opc == BO_EQ;
11524     if (RHSIsNull)
11525       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11526                                    RHS.get()->getSourceRange());
11527     else
11528       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11529                                    LHS.get()->getSourceRange());
11530   }
11531 
11532   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11533       (RHSType->isIntegerType() && !RHSIsNull)) {
11534     // Skip normal pointer conversion checks in this case; we have better
11535     // diagnostics for this below.
11536   } else if (getLangOpts().CPlusPlus) {
11537     // Equality comparison of a function pointer to a void pointer is invalid,
11538     // but we allow it as an extension.
11539     // FIXME: If we really want to allow this, should it be part of composite
11540     // pointer type computation so it works in conditionals too?
11541     if (!IsOrdered &&
11542         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11543          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11544       // This is a gcc extension compatibility comparison.
11545       // In a SFINAE context, we treat this as a hard error to maintain
11546       // conformance with the C++ standard.
11547       diagnoseFunctionPointerToVoidComparison(
11548           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11549 
11550       if (isSFINAEContext())
11551         return QualType();
11552 
11553       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11554       return computeResultTy();
11555     }
11556 
11557     // C++ [expr.eq]p2:
11558     //   If at least one operand is a pointer [...] bring them to their
11559     //   composite pointer type.
11560     // C++ [expr.spaceship]p6
11561     //  If at least one of the operands is of pointer type, [...] bring them
11562     //  to their composite pointer type.
11563     // C++ [expr.rel]p2:
11564     //   If both operands are pointers, [...] bring them to their composite
11565     //   pointer type.
11566     // For <=>, the only valid non-pointer types are arrays and functions, and
11567     // we already decayed those, so this is really the same as the relational
11568     // comparison rule.
11569     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11570             (IsOrdered ? 2 : 1) &&
11571         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11572                                          RHSType->isObjCObjectPointerType()))) {
11573       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11574         return QualType();
11575       return computeResultTy();
11576     }
11577   } else if (LHSType->isPointerType() &&
11578              RHSType->isPointerType()) { // C99 6.5.8p2
11579     // All of the following pointer-related warnings are GCC extensions, except
11580     // when handling null pointer constants.
11581     QualType LCanPointeeTy =
11582       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11583     QualType RCanPointeeTy =
11584       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11585 
11586     // C99 6.5.9p2 and C99 6.5.8p2
11587     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11588                                    RCanPointeeTy.getUnqualifiedType())) {
11589       if (IsRelational) {
11590         // Pointers both need to point to complete or incomplete types
11591         if ((LCanPointeeTy->isIncompleteType() !=
11592              RCanPointeeTy->isIncompleteType()) &&
11593             !getLangOpts().C11) {
11594           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11595               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11596               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11597               << RCanPointeeTy->isIncompleteType();
11598         }
11599         if (LCanPointeeTy->isFunctionType()) {
11600           // Valid unless a relational comparison of function pointers
11601           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11602               << LHSType << RHSType << LHS.get()->getSourceRange()
11603               << RHS.get()->getSourceRange();
11604         }
11605       }
11606     } else if (!IsRelational &&
11607                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11608       // Valid unless comparison between non-null pointer and function pointer
11609       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11610           && !LHSIsNull && !RHSIsNull)
11611         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11612                                                 /*isError*/false);
11613     } else {
11614       // Invalid
11615       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11616     }
11617     if (LCanPointeeTy != RCanPointeeTy) {
11618       // Treat NULL constant as a special case in OpenCL.
11619       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11620         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11621           Diag(Loc,
11622                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11623               << LHSType << RHSType << 0 /* comparison */
11624               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11625         }
11626       }
11627       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11628       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11629       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11630                                                : CK_BitCast;
11631       if (LHSIsNull && !RHSIsNull)
11632         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11633       else
11634         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11635     }
11636     return computeResultTy();
11637   }
11638 
11639   if (getLangOpts().CPlusPlus) {
11640     // C++ [expr.eq]p4:
11641     //   Two operands of type std::nullptr_t or one operand of type
11642     //   std::nullptr_t and the other a null pointer constant compare equal.
11643     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11644       if (LHSType->isNullPtrType()) {
11645         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11646         return computeResultTy();
11647       }
11648       if (RHSType->isNullPtrType()) {
11649         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11650         return computeResultTy();
11651       }
11652     }
11653 
11654     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11655     // These aren't covered by the composite pointer type rules.
11656     if (!IsOrdered && RHSType->isNullPtrType() &&
11657         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11658       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11659       return computeResultTy();
11660     }
11661     if (!IsOrdered && LHSType->isNullPtrType() &&
11662         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11663       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11664       return computeResultTy();
11665     }
11666 
11667     if (IsRelational &&
11668         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11669          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11670       // HACK: Relational comparison of nullptr_t against a pointer type is
11671       // invalid per DR583, but we allow it within std::less<> and friends,
11672       // since otherwise common uses of it break.
11673       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11674       // friends to have std::nullptr_t overload candidates.
11675       DeclContext *DC = CurContext;
11676       if (isa<FunctionDecl>(DC))
11677         DC = DC->getParent();
11678       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11679         if (CTSD->isInStdNamespace() &&
11680             llvm::StringSwitch<bool>(CTSD->getName())
11681                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11682                 .Default(false)) {
11683           if (RHSType->isNullPtrType())
11684             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11685           else
11686             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11687           return computeResultTy();
11688         }
11689       }
11690     }
11691 
11692     // C++ [expr.eq]p2:
11693     //   If at least one operand is a pointer to member, [...] bring them to
11694     //   their composite pointer type.
11695     if (!IsOrdered &&
11696         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11697       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11698         return QualType();
11699       else
11700         return computeResultTy();
11701     }
11702   }
11703 
11704   // Handle block pointer types.
11705   if (!IsOrdered && LHSType->isBlockPointerType() &&
11706       RHSType->isBlockPointerType()) {
11707     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11708     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11709 
11710     if (!LHSIsNull && !RHSIsNull &&
11711         !Context.typesAreCompatible(lpointee, rpointee)) {
11712       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11713         << LHSType << RHSType << LHS.get()->getSourceRange()
11714         << RHS.get()->getSourceRange();
11715     }
11716     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11717     return computeResultTy();
11718   }
11719 
11720   // Allow block pointers to be compared with null pointer constants.
11721   if (!IsOrdered
11722       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11723           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11724     if (!LHSIsNull && !RHSIsNull) {
11725       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11726              ->getPointeeType()->isVoidType())
11727             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11728                 ->getPointeeType()->isVoidType())))
11729         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11730           << LHSType << RHSType << LHS.get()->getSourceRange()
11731           << RHS.get()->getSourceRange();
11732     }
11733     if (LHSIsNull && !RHSIsNull)
11734       LHS = ImpCastExprToType(LHS.get(), RHSType,
11735                               RHSType->isPointerType() ? CK_BitCast
11736                                 : CK_AnyPointerToBlockPointerCast);
11737     else
11738       RHS = ImpCastExprToType(RHS.get(), LHSType,
11739                               LHSType->isPointerType() ? CK_BitCast
11740                                 : CK_AnyPointerToBlockPointerCast);
11741     return computeResultTy();
11742   }
11743 
11744   if (LHSType->isObjCObjectPointerType() ||
11745       RHSType->isObjCObjectPointerType()) {
11746     const PointerType *LPT = LHSType->getAs<PointerType>();
11747     const PointerType *RPT = RHSType->getAs<PointerType>();
11748     if (LPT || RPT) {
11749       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11750       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11751 
11752       if (!LPtrToVoid && !RPtrToVoid &&
11753           !Context.typesAreCompatible(LHSType, RHSType)) {
11754         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11755                                           /*isError*/false);
11756       }
11757       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11758       // the RHS, but we have test coverage for this behavior.
11759       // FIXME: Consider using convertPointersToCompositeType in C++.
11760       if (LHSIsNull && !RHSIsNull) {
11761         Expr *E = LHS.get();
11762         if (getLangOpts().ObjCAutoRefCount)
11763           CheckObjCConversion(SourceRange(), RHSType, E,
11764                               CCK_ImplicitConversion);
11765         LHS = ImpCastExprToType(E, RHSType,
11766                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11767       }
11768       else {
11769         Expr *E = RHS.get();
11770         if (getLangOpts().ObjCAutoRefCount)
11771           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11772                               /*Diagnose=*/true,
11773                               /*DiagnoseCFAudited=*/false, Opc);
11774         RHS = ImpCastExprToType(E, LHSType,
11775                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11776       }
11777       return computeResultTy();
11778     }
11779     if (LHSType->isObjCObjectPointerType() &&
11780         RHSType->isObjCObjectPointerType()) {
11781       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11782         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11783                                           /*isError*/false);
11784       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11785         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11786 
11787       if (LHSIsNull && !RHSIsNull)
11788         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11789       else
11790         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11791       return computeResultTy();
11792     }
11793 
11794     if (!IsOrdered && LHSType->isBlockPointerType() &&
11795         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11796       LHS = ImpCastExprToType(LHS.get(), RHSType,
11797                               CK_BlockPointerToObjCPointerCast);
11798       return computeResultTy();
11799     } else if (!IsOrdered &&
11800                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11801                RHSType->isBlockPointerType()) {
11802       RHS = ImpCastExprToType(RHS.get(), LHSType,
11803                               CK_BlockPointerToObjCPointerCast);
11804       return computeResultTy();
11805     }
11806   }
11807   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11808       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11809     unsigned DiagID = 0;
11810     bool isError = false;
11811     if (LangOpts.DebuggerSupport) {
11812       // Under a debugger, allow the comparison of pointers to integers,
11813       // since users tend to want to compare addresses.
11814     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11815                (RHSIsNull && RHSType->isIntegerType())) {
11816       if (IsOrdered) {
11817         isError = getLangOpts().CPlusPlus;
11818         DiagID =
11819           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11820                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11821       }
11822     } else if (getLangOpts().CPlusPlus) {
11823       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11824       isError = true;
11825     } else if (IsOrdered)
11826       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11827     else
11828       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11829 
11830     if (DiagID) {
11831       Diag(Loc, DiagID)
11832         << LHSType << RHSType << LHS.get()->getSourceRange()
11833         << RHS.get()->getSourceRange();
11834       if (isError)
11835         return QualType();
11836     }
11837 
11838     if (LHSType->isIntegerType())
11839       LHS = ImpCastExprToType(LHS.get(), RHSType,
11840                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11841     else
11842       RHS = ImpCastExprToType(RHS.get(), LHSType,
11843                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11844     return computeResultTy();
11845   }
11846 
11847   // Handle block pointers.
11848   if (!IsOrdered && RHSIsNull
11849       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11850     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11851     return computeResultTy();
11852   }
11853   if (!IsOrdered && LHSIsNull
11854       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11855     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11856     return computeResultTy();
11857   }
11858 
11859   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11860     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11861       return computeResultTy();
11862     }
11863 
11864     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11865       return computeResultTy();
11866     }
11867 
11868     if (LHSIsNull && RHSType->isQueueT()) {
11869       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11870       return computeResultTy();
11871     }
11872 
11873     if (LHSType->isQueueT() && RHSIsNull) {
11874       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11875       return computeResultTy();
11876     }
11877   }
11878 
11879   return InvalidOperands(Loc, LHS, RHS);
11880 }
11881 
11882 // Return a signed ext_vector_type that is of identical size and number of
11883 // elements. For floating point vectors, return an integer type of identical
11884 // size and number of elements. In the non ext_vector_type case, search from
11885 // the largest type to the smallest type to avoid cases where long long == long,
11886 // where long gets picked over long long.
11887 QualType Sema::GetSignedVectorType(QualType V) {
11888   const VectorType *VTy = V->castAs<VectorType>();
11889   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11890 
11891   if (isa<ExtVectorType>(VTy)) {
11892     if (TypeSize == Context.getTypeSize(Context.CharTy))
11893       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11894     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11895       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11896     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11897       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11898     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11899       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11900     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11901            "Unhandled vector element size in vector compare");
11902     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11903   }
11904 
11905   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11906     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11907                                  VectorType::GenericVector);
11908   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11909     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11910                                  VectorType::GenericVector);
11911   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11912     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11913                                  VectorType::GenericVector);
11914   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11915     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11916                                  VectorType::GenericVector);
11917   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11918          "Unhandled vector element size in vector compare");
11919   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11920                                VectorType::GenericVector);
11921 }
11922 
11923 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11924 /// operates on extended vector types.  Instead of producing an IntTy result,
11925 /// like a scalar comparison, a vector comparison produces a vector of integer
11926 /// types.
11927 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11928                                           SourceLocation Loc,
11929                                           BinaryOperatorKind Opc) {
11930   if (Opc == BO_Cmp) {
11931     Diag(Loc, diag::err_three_way_vector_comparison);
11932     return QualType();
11933   }
11934 
11935   // Check to make sure we're operating on vectors of the same type and width,
11936   // Allowing one side to be a scalar of element type.
11937   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11938                               /*AllowBothBool*/true,
11939                               /*AllowBoolConversions*/getLangOpts().ZVector);
11940   if (vType.isNull())
11941     return vType;
11942 
11943   QualType LHSType = LHS.get()->getType();
11944 
11945   // If AltiVec, the comparison results in a numeric type, i.e.
11946   // bool for C++, int for C
11947   if (getLangOpts().AltiVec &&
11948       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11949     return Context.getLogicalOperationType();
11950 
11951   // For non-floating point types, check for self-comparisons of the form
11952   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11953   // often indicate logic errors in the program.
11954   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11955 
11956   // Check for comparisons of floating point operands using != and ==.
11957   if (BinaryOperator::isEqualityOp(Opc) &&
11958       LHSType->hasFloatingRepresentation()) {
11959     assert(RHS.get()->getType()->hasFloatingRepresentation());
11960     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11961   }
11962 
11963   // Return a signed type for the vector.
11964   return GetSignedVectorType(vType);
11965 }
11966 
11967 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11968                                     const ExprResult &XorRHS,
11969                                     const SourceLocation Loc) {
11970   // Do not diagnose macros.
11971   if (Loc.isMacroID())
11972     return;
11973 
11974   bool Negative = false;
11975   bool ExplicitPlus = false;
11976   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11977   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11978 
11979   if (!LHSInt)
11980     return;
11981   if (!RHSInt) {
11982     // Check negative literals.
11983     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11984       UnaryOperatorKind Opc = UO->getOpcode();
11985       if (Opc != UO_Minus && Opc != UO_Plus)
11986         return;
11987       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11988       if (!RHSInt)
11989         return;
11990       Negative = (Opc == UO_Minus);
11991       ExplicitPlus = !Negative;
11992     } else {
11993       return;
11994     }
11995   }
11996 
11997   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11998   llvm::APInt RightSideValue = RHSInt->getValue();
11999   if (LeftSideValue != 2 && LeftSideValue != 10)
12000     return;
12001 
12002   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12003     return;
12004 
12005   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12006       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12007   llvm::StringRef ExprStr =
12008       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12009 
12010   CharSourceRange XorRange =
12011       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12012   llvm::StringRef XorStr =
12013       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12014   // Do not diagnose if xor keyword/macro is used.
12015   if (XorStr == "xor")
12016     return;
12017 
12018   std::string LHSStr = std::string(Lexer::getSourceText(
12019       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12020       S.getSourceManager(), S.getLangOpts()));
12021   std::string RHSStr = std::string(Lexer::getSourceText(
12022       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12023       S.getSourceManager(), S.getLangOpts()));
12024 
12025   if (Negative) {
12026     RightSideValue = -RightSideValue;
12027     RHSStr = "-" + RHSStr;
12028   } else if (ExplicitPlus) {
12029     RHSStr = "+" + RHSStr;
12030   }
12031 
12032   StringRef LHSStrRef = LHSStr;
12033   StringRef RHSStrRef = RHSStr;
12034   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12035   // literals.
12036   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12037       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12038       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12039       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12040       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12041       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12042       LHSStrRef.find('\'') != StringRef::npos ||
12043       RHSStrRef.find('\'') != StringRef::npos)
12044     return;
12045 
12046   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12047   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12048   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12049   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12050     std::string SuggestedExpr = "1 << " + RHSStr;
12051     bool Overflow = false;
12052     llvm::APInt One = (LeftSideValue - 1);
12053     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12054     if (Overflow) {
12055       if (RightSideIntValue < 64)
12056         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12057             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12058             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12059       else if (RightSideIntValue == 64)
12060         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12061       else
12062         return;
12063     } else {
12064       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12065           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12066           << PowValue.toString(10, true)
12067           << FixItHint::CreateReplacement(
12068                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12069     }
12070 
12071     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12072   } else if (LeftSideValue == 10) {
12073     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12074     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12075         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12076         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12077     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12078   }
12079 }
12080 
12081 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12082                                           SourceLocation Loc) {
12083   // Ensure that either both operands are of the same vector type, or
12084   // one operand is of a vector type and the other is of its element type.
12085   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12086                                        /*AllowBothBool*/true,
12087                                        /*AllowBoolConversions*/false);
12088   if (vType.isNull())
12089     return InvalidOperands(Loc, LHS, RHS);
12090   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12091       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12092     return InvalidOperands(Loc, LHS, RHS);
12093   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12094   //        usage of the logical operators && and || with vectors in C. This
12095   //        check could be notionally dropped.
12096   if (!getLangOpts().CPlusPlus &&
12097       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12098     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12099 
12100   return GetSignedVectorType(LHS.get()->getType());
12101 }
12102 
12103 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12104                                               SourceLocation Loc,
12105                                               bool IsCompAssign) {
12106   if (!IsCompAssign) {
12107     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12108     if (LHS.isInvalid())
12109       return QualType();
12110   }
12111   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12112   if (RHS.isInvalid())
12113     return QualType();
12114 
12115   // For conversion purposes, we ignore any qualifiers.
12116   // For example, "const float" and "float" are equivalent.
12117   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12118   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12119 
12120   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12121   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12122   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12123 
12124   if (Context.hasSameType(LHSType, RHSType))
12125     return LHSType;
12126 
12127   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12128   // case we have to return InvalidOperands.
12129   ExprResult OriginalLHS = LHS;
12130   ExprResult OriginalRHS = RHS;
12131   if (LHSMatType && !RHSMatType) {
12132     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12133     if (!RHS.isInvalid())
12134       return LHSType;
12135 
12136     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12137   }
12138 
12139   if (!LHSMatType && RHSMatType) {
12140     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12141     if (!LHS.isInvalid())
12142       return RHSType;
12143     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12144   }
12145 
12146   return InvalidOperands(Loc, LHS, RHS);
12147 }
12148 
12149 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12150                                            SourceLocation Loc,
12151                                            bool IsCompAssign) {
12152   if (!IsCompAssign) {
12153     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12154     if (LHS.isInvalid())
12155       return QualType();
12156   }
12157   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12158   if (RHS.isInvalid())
12159     return QualType();
12160 
12161   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12162   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12163   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12164 
12165   if (LHSMatType && RHSMatType) {
12166     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12167       return InvalidOperands(Loc, LHS, RHS);
12168 
12169     if (!Context.hasSameType(LHSMatType->getElementType(),
12170                              RHSMatType->getElementType()))
12171       return InvalidOperands(Loc, LHS, RHS);
12172 
12173     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12174                                          LHSMatType->getNumRows(),
12175                                          RHSMatType->getNumColumns());
12176   }
12177   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12178 }
12179 
12180 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12181                                            SourceLocation Loc,
12182                                            BinaryOperatorKind Opc) {
12183   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12184 
12185   bool IsCompAssign =
12186       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12187 
12188   if (LHS.get()->getType()->isVectorType() ||
12189       RHS.get()->getType()->isVectorType()) {
12190     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12191         RHS.get()->getType()->hasIntegerRepresentation())
12192       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12193                         /*AllowBothBool*/true,
12194                         /*AllowBoolConversions*/getLangOpts().ZVector);
12195     return InvalidOperands(Loc, LHS, RHS);
12196   }
12197 
12198   if (Opc == BO_And)
12199     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12200 
12201   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12202       RHS.get()->getType()->hasFloatingRepresentation())
12203     return InvalidOperands(Loc, LHS, RHS);
12204 
12205   ExprResult LHSResult = LHS, RHSResult = RHS;
12206   QualType compType = UsualArithmeticConversions(
12207       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12208   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12209     return QualType();
12210   LHS = LHSResult.get();
12211   RHS = RHSResult.get();
12212 
12213   if (Opc == BO_Xor)
12214     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12215 
12216   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12217     return compType;
12218   return InvalidOperands(Loc, LHS, RHS);
12219 }
12220 
12221 // C99 6.5.[13,14]
12222 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12223                                            SourceLocation Loc,
12224                                            BinaryOperatorKind Opc) {
12225   // Check vector operands differently.
12226   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12227     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12228 
12229   bool EnumConstantInBoolContext = false;
12230   for (const ExprResult &HS : {LHS, RHS}) {
12231     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12232       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12233       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12234         EnumConstantInBoolContext = true;
12235     }
12236   }
12237 
12238   if (EnumConstantInBoolContext)
12239     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12240 
12241   // Diagnose cases where the user write a logical and/or but probably meant a
12242   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12243   // is a constant.
12244   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12245       !LHS.get()->getType()->isBooleanType() &&
12246       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12247       // Don't warn in macros or template instantiations.
12248       !Loc.isMacroID() && !inTemplateInstantiation()) {
12249     // If the RHS can be constant folded, and if it constant folds to something
12250     // that isn't 0 or 1 (which indicate a potential logical operation that
12251     // happened to fold to true/false) then warn.
12252     // Parens on the RHS are ignored.
12253     Expr::EvalResult EVResult;
12254     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12255       llvm::APSInt Result = EVResult.Val.getInt();
12256       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12257            !RHS.get()->getExprLoc().isMacroID()) ||
12258           (Result != 0 && Result != 1)) {
12259         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12260           << RHS.get()->getSourceRange()
12261           << (Opc == BO_LAnd ? "&&" : "||");
12262         // Suggest replacing the logical operator with the bitwise version
12263         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12264             << (Opc == BO_LAnd ? "&" : "|")
12265             << FixItHint::CreateReplacement(SourceRange(
12266                                                  Loc, getLocForEndOfToken(Loc)),
12267                                             Opc == BO_LAnd ? "&" : "|");
12268         if (Opc == BO_LAnd)
12269           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12270           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12271               << FixItHint::CreateRemoval(
12272                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12273                                  RHS.get()->getEndLoc()));
12274       }
12275     }
12276   }
12277 
12278   if (!Context.getLangOpts().CPlusPlus) {
12279     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12280     // not operate on the built-in scalar and vector float types.
12281     if (Context.getLangOpts().OpenCL &&
12282         Context.getLangOpts().OpenCLVersion < 120) {
12283       if (LHS.get()->getType()->isFloatingType() ||
12284           RHS.get()->getType()->isFloatingType())
12285         return InvalidOperands(Loc, LHS, RHS);
12286     }
12287 
12288     LHS = UsualUnaryConversions(LHS.get());
12289     if (LHS.isInvalid())
12290       return QualType();
12291 
12292     RHS = UsualUnaryConversions(RHS.get());
12293     if (RHS.isInvalid())
12294       return QualType();
12295 
12296     if (!LHS.get()->getType()->isScalarType() ||
12297         !RHS.get()->getType()->isScalarType())
12298       return InvalidOperands(Loc, LHS, RHS);
12299 
12300     return Context.IntTy;
12301   }
12302 
12303   // The following is safe because we only use this method for
12304   // non-overloadable operands.
12305 
12306   // C++ [expr.log.and]p1
12307   // C++ [expr.log.or]p1
12308   // The operands are both contextually converted to type bool.
12309   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12310   if (LHSRes.isInvalid())
12311     return InvalidOperands(Loc, LHS, RHS);
12312   LHS = LHSRes;
12313 
12314   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12315   if (RHSRes.isInvalid())
12316     return InvalidOperands(Loc, LHS, RHS);
12317   RHS = RHSRes;
12318 
12319   // C++ [expr.log.and]p2
12320   // C++ [expr.log.or]p2
12321   // The result is a bool.
12322   return Context.BoolTy;
12323 }
12324 
12325 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12326   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12327   if (!ME) return false;
12328   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12329   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12330       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12331   if (!Base) return false;
12332   return Base->getMethodDecl() != nullptr;
12333 }
12334 
12335 /// Is the given expression (which must be 'const') a reference to a
12336 /// variable which was originally non-const, but which has become
12337 /// 'const' due to being captured within a block?
12338 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12339 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12340   assert(E->isLValue() && E->getType().isConstQualified());
12341   E = E->IgnoreParens();
12342 
12343   // Must be a reference to a declaration from an enclosing scope.
12344   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12345   if (!DRE) return NCCK_None;
12346   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12347 
12348   // The declaration must be a variable which is not declared 'const'.
12349   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12350   if (!var) return NCCK_None;
12351   if (var->getType().isConstQualified()) return NCCK_None;
12352   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12353 
12354   // Decide whether the first capture was for a block or a lambda.
12355   DeclContext *DC = S.CurContext, *Prev = nullptr;
12356   // Decide whether the first capture was for a block or a lambda.
12357   while (DC) {
12358     // For init-capture, it is possible that the variable belongs to the
12359     // template pattern of the current context.
12360     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12361       if (var->isInitCapture() &&
12362           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12363         break;
12364     if (DC == var->getDeclContext())
12365       break;
12366     Prev = DC;
12367     DC = DC->getParent();
12368   }
12369   // Unless we have an init-capture, we've gone one step too far.
12370   if (!var->isInitCapture())
12371     DC = Prev;
12372   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12373 }
12374 
12375 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12376   Ty = Ty.getNonReferenceType();
12377   if (IsDereference && Ty->isPointerType())
12378     Ty = Ty->getPointeeType();
12379   return !Ty.isConstQualified();
12380 }
12381 
12382 // Update err_typecheck_assign_const and note_typecheck_assign_const
12383 // when this enum is changed.
12384 enum {
12385   ConstFunction,
12386   ConstVariable,
12387   ConstMember,
12388   ConstMethod,
12389   NestedConstMember,
12390   ConstUnknown,  // Keep as last element
12391 };
12392 
12393 /// Emit the "read-only variable not assignable" error and print notes to give
12394 /// more information about why the variable is not assignable, such as pointing
12395 /// to the declaration of a const variable, showing that a method is const, or
12396 /// that the function is returning a const reference.
12397 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12398                                     SourceLocation Loc) {
12399   SourceRange ExprRange = E->getSourceRange();
12400 
12401   // Only emit one error on the first const found.  All other consts will emit
12402   // a note to the error.
12403   bool DiagnosticEmitted = false;
12404 
12405   // Track if the current expression is the result of a dereference, and if the
12406   // next checked expression is the result of a dereference.
12407   bool IsDereference = false;
12408   bool NextIsDereference = false;
12409 
12410   // Loop to process MemberExpr chains.
12411   while (true) {
12412     IsDereference = NextIsDereference;
12413 
12414     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12415     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12416       NextIsDereference = ME->isArrow();
12417       const ValueDecl *VD = ME->getMemberDecl();
12418       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12419         // Mutable fields can be modified even if the class is const.
12420         if (Field->isMutable()) {
12421           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12422           break;
12423         }
12424 
12425         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12426           if (!DiagnosticEmitted) {
12427             S.Diag(Loc, diag::err_typecheck_assign_const)
12428                 << ExprRange << ConstMember << false /*static*/ << Field
12429                 << Field->getType();
12430             DiagnosticEmitted = true;
12431           }
12432           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12433               << ConstMember << false /*static*/ << Field << Field->getType()
12434               << Field->getSourceRange();
12435         }
12436         E = ME->getBase();
12437         continue;
12438       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12439         if (VDecl->getType().isConstQualified()) {
12440           if (!DiagnosticEmitted) {
12441             S.Diag(Loc, diag::err_typecheck_assign_const)
12442                 << ExprRange << ConstMember << true /*static*/ << VDecl
12443                 << VDecl->getType();
12444             DiagnosticEmitted = true;
12445           }
12446           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12447               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12448               << VDecl->getSourceRange();
12449         }
12450         // Static fields do not inherit constness from parents.
12451         break;
12452       }
12453       break; // End MemberExpr
12454     } else if (const ArraySubscriptExpr *ASE =
12455                    dyn_cast<ArraySubscriptExpr>(E)) {
12456       E = ASE->getBase()->IgnoreParenImpCasts();
12457       continue;
12458     } else if (const ExtVectorElementExpr *EVE =
12459                    dyn_cast<ExtVectorElementExpr>(E)) {
12460       E = EVE->getBase()->IgnoreParenImpCasts();
12461       continue;
12462     }
12463     break;
12464   }
12465 
12466   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12467     // Function calls
12468     const FunctionDecl *FD = CE->getDirectCallee();
12469     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12470       if (!DiagnosticEmitted) {
12471         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12472                                                       << ConstFunction << FD;
12473         DiagnosticEmitted = true;
12474       }
12475       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12476              diag::note_typecheck_assign_const)
12477           << ConstFunction << FD << FD->getReturnType()
12478           << FD->getReturnTypeSourceRange();
12479     }
12480   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12481     // Point to variable declaration.
12482     if (const ValueDecl *VD = DRE->getDecl()) {
12483       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12484         if (!DiagnosticEmitted) {
12485           S.Diag(Loc, diag::err_typecheck_assign_const)
12486               << ExprRange << ConstVariable << VD << VD->getType();
12487           DiagnosticEmitted = true;
12488         }
12489         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12490             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12491       }
12492     }
12493   } else if (isa<CXXThisExpr>(E)) {
12494     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12495       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12496         if (MD->isConst()) {
12497           if (!DiagnosticEmitted) {
12498             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12499                                                           << ConstMethod << MD;
12500             DiagnosticEmitted = true;
12501           }
12502           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12503               << ConstMethod << MD << MD->getSourceRange();
12504         }
12505       }
12506     }
12507   }
12508 
12509   if (DiagnosticEmitted)
12510     return;
12511 
12512   // Can't determine a more specific message, so display the generic error.
12513   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12514 }
12515 
12516 enum OriginalExprKind {
12517   OEK_Variable,
12518   OEK_Member,
12519   OEK_LValue
12520 };
12521 
12522 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12523                                          const RecordType *Ty,
12524                                          SourceLocation Loc, SourceRange Range,
12525                                          OriginalExprKind OEK,
12526                                          bool &DiagnosticEmitted) {
12527   std::vector<const RecordType *> RecordTypeList;
12528   RecordTypeList.push_back(Ty);
12529   unsigned NextToCheckIndex = 0;
12530   // We walk the record hierarchy breadth-first to ensure that we print
12531   // diagnostics in field nesting order.
12532   while (RecordTypeList.size() > NextToCheckIndex) {
12533     bool IsNested = NextToCheckIndex > 0;
12534     for (const FieldDecl *Field :
12535          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12536       // First, check every field for constness.
12537       QualType FieldTy = Field->getType();
12538       if (FieldTy.isConstQualified()) {
12539         if (!DiagnosticEmitted) {
12540           S.Diag(Loc, diag::err_typecheck_assign_const)
12541               << Range << NestedConstMember << OEK << VD
12542               << IsNested << Field;
12543           DiagnosticEmitted = true;
12544         }
12545         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12546             << NestedConstMember << IsNested << Field
12547             << FieldTy << Field->getSourceRange();
12548       }
12549 
12550       // Then we append it to the list to check next in order.
12551       FieldTy = FieldTy.getCanonicalType();
12552       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12553         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12554           RecordTypeList.push_back(FieldRecTy);
12555       }
12556     }
12557     ++NextToCheckIndex;
12558   }
12559 }
12560 
12561 /// Emit an error for the case where a record we are trying to assign to has a
12562 /// const-qualified field somewhere in its hierarchy.
12563 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12564                                          SourceLocation Loc) {
12565   QualType Ty = E->getType();
12566   assert(Ty->isRecordType() && "lvalue was not record?");
12567   SourceRange Range = E->getSourceRange();
12568   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12569   bool DiagEmitted = false;
12570 
12571   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12572     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12573             Range, OEK_Member, DiagEmitted);
12574   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12575     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12576             Range, OEK_Variable, DiagEmitted);
12577   else
12578     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12579             Range, OEK_LValue, DiagEmitted);
12580   if (!DiagEmitted)
12581     DiagnoseConstAssignment(S, E, Loc);
12582 }
12583 
12584 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12585 /// emit an error and return true.  If so, return false.
12586 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12587   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12588 
12589   S.CheckShadowingDeclModification(E, Loc);
12590 
12591   SourceLocation OrigLoc = Loc;
12592   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12593                                                               &Loc);
12594   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12595     IsLV = Expr::MLV_InvalidMessageExpression;
12596   if (IsLV == Expr::MLV_Valid)
12597     return false;
12598 
12599   unsigned DiagID = 0;
12600   bool NeedType = false;
12601   switch (IsLV) { // C99 6.5.16p2
12602   case Expr::MLV_ConstQualified:
12603     // Use a specialized diagnostic when we're assigning to an object
12604     // from an enclosing function or block.
12605     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12606       if (NCCK == NCCK_Block)
12607         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12608       else
12609         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12610       break;
12611     }
12612 
12613     // In ARC, use some specialized diagnostics for occasions where we
12614     // infer 'const'.  These are always pseudo-strong variables.
12615     if (S.getLangOpts().ObjCAutoRefCount) {
12616       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12617       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12618         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12619 
12620         // Use the normal diagnostic if it's pseudo-__strong but the
12621         // user actually wrote 'const'.
12622         if (var->isARCPseudoStrong() &&
12623             (!var->getTypeSourceInfo() ||
12624              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12625           // There are three pseudo-strong cases:
12626           //  - self
12627           ObjCMethodDecl *method = S.getCurMethodDecl();
12628           if (method && var == method->getSelfDecl()) {
12629             DiagID = method->isClassMethod()
12630               ? diag::err_typecheck_arc_assign_self_class_method
12631               : diag::err_typecheck_arc_assign_self;
12632 
12633           //  - Objective-C externally_retained attribute.
12634           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12635                      isa<ParmVarDecl>(var)) {
12636             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12637 
12638           //  - fast enumeration variables
12639           } else {
12640             DiagID = diag::err_typecheck_arr_assign_enumeration;
12641           }
12642 
12643           SourceRange Assign;
12644           if (Loc != OrigLoc)
12645             Assign = SourceRange(OrigLoc, OrigLoc);
12646           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12647           // We need to preserve the AST regardless, so migration tool
12648           // can do its job.
12649           return false;
12650         }
12651       }
12652     }
12653 
12654     // If none of the special cases above are triggered, then this is a
12655     // simple const assignment.
12656     if (DiagID == 0) {
12657       DiagnoseConstAssignment(S, E, Loc);
12658       return true;
12659     }
12660 
12661     break;
12662   case Expr::MLV_ConstAddrSpace:
12663     DiagnoseConstAssignment(S, E, Loc);
12664     return true;
12665   case Expr::MLV_ConstQualifiedField:
12666     DiagnoseRecursiveConstFields(S, E, Loc);
12667     return true;
12668   case Expr::MLV_ArrayType:
12669   case Expr::MLV_ArrayTemporary:
12670     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12671     NeedType = true;
12672     break;
12673   case Expr::MLV_NotObjectType:
12674     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12675     NeedType = true;
12676     break;
12677   case Expr::MLV_LValueCast:
12678     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12679     break;
12680   case Expr::MLV_Valid:
12681     llvm_unreachable("did not take early return for MLV_Valid");
12682   case Expr::MLV_InvalidExpression:
12683   case Expr::MLV_MemberFunction:
12684   case Expr::MLV_ClassTemporary:
12685     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12686     break;
12687   case Expr::MLV_IncompleteType:
12688   case Expr::MLV_IncompleteVoidType:
12689     return S.RequireCompleteType(Loc, E->getType(),
12690              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12691   case Expr::MLV_DuplicateVectorComponents:
12692     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12693     break;
12694   case Expr::MLV_NoSetterProperty:
12695     llvm_unreachable("readonly properties should be processed differently");
12696   case Expr::MLV_InvalidMessageExpression:
12697     DiagID = diag::err_readonly_message_assignment;
12698     break;
12699   case Expr::MLV_SubObjCPropertySetting:
12700     DiagID = diag::err_no_subobject_property_setting;
12701     break;
12702   }
12703 
12704   SourceRange Assign;
12705   if (Loc != OrigLoc)
12706     Assign = SourceRange(OrigLoc, OrigLoc);
12707   if (NeedType)
12708     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12709   else
12710     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12711   return true;
12712 }
12713 
12714 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12715                                          SourceLocation Loc,
12716                                          Sema &Sema) {
12717   if (Sema.inTemplateInstantiation())
12718     return;
12719   if (Sema.isUnevaluatedContext())
12720     return;
12721   if (Loc.isInvalid() || Loc.isMacroID())
12722     return;
12723   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12724     return;
12725 
12726   // C / C++ fields
12727   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12728   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12729   if (ML && MR) {
12730     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12731       return;
12732     const ValueDecl *LHSDecl =
12733         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12734     const ValueDecl *RHSDecl =
12735         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12736     if (LHSDecl != RHSDecl)
12737       return;
12738     if (LHSDecl->getType().isVolatileQualified())
12739       return;
12740     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12741       if (RefTy->getPointeeType().isVolatileQualified())
12742         return;
12743 
12744     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12745   }
12746 
12747   // Objective-C instance variables
12748   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12749   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12750   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12751     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12752     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12753     if (RL && RR && RL->getDecl() == RR->getDecl())
12754       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12755   }
12756 }
12757 
12758 // C99 6.5.16.1
12759 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12760                                        SourceLocation Loc,
12761                                        QualType CompoundType) {
12762   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12763 
12764   // Verify that LHS is a modifiable lvalue, and emit error if not.
12765   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12766     return QualType();
12767 
12768   QualType LHSType = LHSExpr->getType();
12769   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12770                                              CompoundType;
12771   // OpenCL v1.2 s6.1.1.1 p2:
12772   // The half data type can only be used to declare a pointer to a buffer that
12773   // contains half values
12774   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12775     LHSType->isHalfType()) {
12776     Diag(Loc, diag::err_opencl_half_load_store) << 1
12777         << LHSType.getUnqualifiedType();
12778     return QualType();
12779   }
12780 
12781   AssignConvertType ConvTy;
12782   if (CompoundType.isNull()) {
12783     Expr *RHSCheck = RHS.get();
12784 
12785     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12786 
12787     QualType LHSTy(LHSType);
12788     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12789     if (RHS.isInvalid())
12790       return QualType();
12791     // Special case of NSObject attributes on c-style pointer types.
12792     if (ConvTy == IncompatiblePointer &&
12793         ((Context.isObjCNSObjectType(LHSType) &&
12794           RHSType->isObjCObjectPointerType()) ||
12795          (Context.isObjCNSObjectType(RHSType) &&
12796           LHSType->isObjCObjectPointerType())))
12797       ConvTy = Compatible;
12798 
12799     if (ConvTy == Compatible &&
12800         LHSType->isObjCObjectType())
12801         Diag(Loc, diag::err_objc_object_assignment)
12802           << LHSType;
12803 
12804     // If the RHS is a unary plus or minus, check to see if they = and + are
12805     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12806     // instead of "x += 4".
12807     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12808       RHSCheck = ICE->getSubExpr();
12809     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12810       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12811           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12812           // Only if the two operators are exactly adjacent.
12813           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12814           // And there is a space or other character before the subexpr of the
12815           // unary +/-.  We don't want to warn on "x=-1".
12816           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12817           UO->getSubExpr()->getBeginLoc().isFileID()) {
12818         Diag(Loc, diag::warn_not_compound_assign)
12819           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12820           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12821       }
12822     }
12823 
12824     if (ConvTy == Compatible) {
12825       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12826         // Warn about retain cycles where a block captures the LHS, but
12827         // not if the LHS is a simple variable into which the block is
12828         // being stored...unless that variable can be captured by reference!
12829         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12830         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12831         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12832           checkRetainCycles(LHSExpr, RHS.get());
12833       }
12834 
12835       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12836           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12837         // It is safe to assign a weak reference into a strong variable.
12838         // Although this code can still have problems:
12839         //   id x = self.weakProp;
12840         //   id y = self.weakProp;
12841         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12842         // paths through the function. This should be revisited if
12843         // -Wrepeated-use-of-weak is made flow-sensitive.
12844         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12845         // variable, which will be valid for the current autorelease scope.
12846         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12847                              RHS.get()->getBeginLoc()))
12848           getCurFunction()->markSafeWeakUse(RHS.get());
12849 
12850       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12851         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12852       }
12853     }
12854   } else {
12855     // Compound assignment "x += y"
12856     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12857   }
12858 
12859   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12860                                RHS.get(), AA_Assigning))
12861     return QualType();
12862 
12863   CheckForNullPointerDereference(*this, LHSExpr);
12864 
12865   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12866     if (CompoundType.isNull()) {
12867       // C++2a [expr.ass]p5:
12868       //   A simple-assignment whose left operand is of a volatile-qualified
12869       //   type is deprecated unless the assignment is either a discarded-value
12870       //   expression or an unevaluated operand
12871       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12872     } else {
12873       // C++2a [expr.ass]p6:
12874       //   [Compound-assignment] expressions are deprecated if E1 has
12875       //   volatile-qualified type
12876       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12877     }
12878   }
12879 
12880   // C99 6.5.16p3: The type of an assignment expression is the type of the
12881   // left operand unless the left operand has qualified type, in which case
12882   // it is the unqualified version of the type of the left operand.
12883   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12884   // is converted to the type of the assignment expression (above).
12885   // C++ 5.17p1: the type of the assignment expression is that of its left
12886   // operand.
12887   return (getLangOpts().CPlusPlus
12888           ? LHSType : LHSType.getUnqualifiedType());
12889 }
12890 
12891 // Only ignore explicit casts to void.
12892 static bool IgnoreCommaOperand(const Expr *E) {
12893   E = E->IgnoreParens();
12894 
12895   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12896     if (CE->getCastKind() == CK_ToVoid) {
12897       return true;
12898     }
12899 
12900     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12901     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12902         CE->getSubExpr()->getType()->isDependentType()) {
12903       return true;
12904     }
12905   }
12906 
12907   return false;
12908 }
12909 
12910 // Look for instances where it is likely the comma operator is confused with
12911 // another operator.  There is an explicit list of acceptable expressions for
12912 // the left hand side of the comma operator, otherwise emit a warning.
12913 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12914   // No warnings in macros
12915   if (Loc.isMacroID())
12916     return;
12917 
12918   // Don't warn in template instantiations.
12919   if (inTemplateInstantiation())
12920     return;
12921 
12922   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12923   // instead, skip more than needed, then call back into here with the
12924   // CommaVisitor in SemaStmt.cpp.
12925   // The listed locations are the initialization and increment portions
12926   // of a for loop.  The additional checks are on the condition of
12927   // if statements, do/while loops, and for loops.
12928   // Differences in scope flags for C89 mode requires the extra logic.
12929   const unsigned ForIncrementFlags =
12930       getLangOpts().C99 || getLangOpts().CPlusPlus
12931           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12932           : Scope::ContinueScope | Scope::BreakScope;
12933   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12934   const unsigned ScopeFlags = getCurScope()->getFlags();
12935   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12936       (ScopeFlags & ForInitFlags) == ForInitFlags)
12937     return;
12938 
12939   // If there are multiple comma operators used together, get the RHS of the
12940   // of the comma operator as the LHS.
12941   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12942     if (BO->getOpcode() != BO_Comma)
12943       break;
12944     LHS = BO->getRHS();
12945   }
12946 
12947   // Only allow some expressions on LHS to not warn.
12948   if (IgnoreCommaOperand(LHS))
12949     return;
12950 
12951   Diag(Loc, diag::warn_comma_operator);
12952   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12953       << LHS->getSourceRange()
12954       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12955                                     LangOpts.CPlusPlus ? "static_cast<void>("
12956                                                        : "(void)(")
12957       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12958                                     ")");
12959 }
12960 
12961 // C99 6.5.17
12962 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12963                                    SourceLocation Loc) {
12964   LHS = S.CheckPlaceholderExpr(LHS.get());
12965   RHS = S.CheckPlaceholderExpr(RHS.get());
12966   if (LHS.isInvalid() || RHS.isInvalid())
12967     return QualType();
12968 
12969   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12970   // operands, but not unary promotions.
12971   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12972 
12973   // So we treat the LHS as a ignored value, and in C++ we allow the
12974   // containing site to determine what should be done with the RHS.
12975   LHS = S.IgnoredValueConversions(LHS.get());
12976   if (LHS.isInvalid())
12977     return QualType();
12978 
12979   S.DiagnoseUnusedExprResult(LHS.get());
12980 
12981   if (!S.getLangOpts().CPlusPlus) {
12982     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12983     if (RHS.isInvalid())
12984       return QualType();
12985     if (!RHS.get()->getType()->isVoidType())
12986       S.RequireCompleteType(Loc, RHS.get()->getType(),
12987                             diag::err_incomplete_type);
12988   }
12989 
12990   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12991     S.DiagnoseCommaOperator(LHS.get(), Loc);
12992 
12993   return RHS.get()->getType();
12994 }
12995 
12996 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12997 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12998 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12999                                                ExprValueKind &VK,
13000                                                ExprObjectKind &OK,
13001                                                SourceLocation OpLoc,
13002                                                bool IsInc, bool IsPrefix) {
13003   if (Op->isTypeDependent())
13004     return S.Context.DependentTy;
13005 
13006   QualType ResType = Op->getType();
13007   // Atomic types can be used for increment / decrement where the non-atomic
13008   // versions can, so ignore the _Atomic() specifier for the purpose of
13009   // checking.
13010   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13011     ResType = ResAtomicType->getValueType();
13012 
13013   assert(!ResType.isNull() && "no type for increment/decrement expression");
13014 
13015   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13016     // Decrement of bool is not allowed.
13017     if (!IsInc) {
13018       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13019       return QualType();
13020     }
13021     // Increment of bool sets it to true, but is deprecated.
13022     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13023                                               : diag::warn_increment_bool)
13024       << Op->getSourceRange();
13025   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13026     // Error on enum increments and decrements in C++ mode
13027     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13028     return QualType();
13029   } else if (ResType->isRealType()) {
13030     // OK!
13031   } else if (ResType->isPointerType()) {
13032     // C99 6.5.2.4p2, 6.5.6p2
13033     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13034       return QualType();
13035   } else if (ResType->isObjCObjectPointerType()) {
13036     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13037     // Otherwise, we just need a complete type.
13038     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13039         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13040       return QualType();
13041   } else if (ResType->isAnyComplexType()) {
13042     // C99 does not support ++/-- on complex types, we allow as an extension.
13043     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13044       << ResType << Op->getSourceRange();
13045   } else if (ResType->isPlaceholderType()) {
13046     ExprResult PR = S.CheckPlaceholderExpr(Op);
13047     if (PR.isInvalid()) return QualType();
13048     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13049                                           IsInc, IsPrefix);
13050   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13051     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13052   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13053              (ResType->castAs<VectorType>()->getVectorKind() !=
13054               VectorType::AltiVecBool)) {
13055     // The z vector extensions allow ++ and -- for non-bool vectors.
13056   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13057             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13058     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13059   } else {
13060     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13061       << ResType << int(IsInc) << Op->getSourceRange();
13062     return QualType();
13063   }
13064   // At this point, we know we have a real, complex or pointer type.
13065   // Now make sure the operand is a modifiable lvalue.
13066   if (CheckForModifiableLvalue(Op, OpLoc, S))
13067     return QualType();
13068   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13069     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13070     //   An operand with volatile-qualified type is deprecated
13071     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13072         << IsInc << ResType;
13073   }
13074   // In C++, a prefix increment is the same type as the operand. Otherwise
13075   // (in C or with postfix), the increment is the unqualified type of the
13076   // operand.
13077   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13078     VK = VK_LValue;
13079     OK = Op->getObjectKind();
13080     return ResType;
13081   } else {
13082     VK = VK_RValue;
13083     return ResType.getUnqualifiedType();
13084   }
13085 }
13086 
13087 
13088 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13089 /// This routine allows us to typecheck complex/recursive expressions
13090 /// where the declaration is needed for type checking. We only need to
13091 /// handle cases when the expression references a function designator
13092 /// or is an lvalue. Here are some examples:
13093 ///  - &(x) => x
13094 ///  - &*****f => f for f a function designator.
13095 ///  - &s.xx => s
13096 ///  - &s.zz[1].yy -> s, if zz is an array
13097 ///  - *(x + 1) -> x, if x is an array
13098 ///  - &"123"[2] -> 0
13099 ///  - & __real__ x -> x
13100 ///
13101 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13102 /// members.
13103 static ValueDecl *getPrimaryDecl(Expr *E) {
13104   switch (E->getStmtClass()) {
13105   case Stmt::DeclRefExprClass:
13106     return cast<DeclRefExpr>(E)->getDecl();
13107   case Stmt::MemberExprClass:
13108     // If this is an arrow operator, the address is an offset from
13109     // the base's value, so the object the base refers to is
13110     // irrelevant.
13111     if (cast<MemberExpr>(E)->isArrow())
13112       return nullptr;
13113     // Otherwise, the expression refers to a part of the base
13114     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13115   case Stmt::ArraySubscriptExprClass: {
13116     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13117     // promotion of register arrays earlier.
13118     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13119     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13120       if (ICE->getSubExpr()->getType()->isArrayType())
13121         return getPrimaryDecl(ICE->getSubExpr());
13122     }
13123     return nullptr;
13124   }
13125   case Stmt::UnaryOperatorClass: {
13126     UnaryOperator *UO = cast<UnaryOperator>(E);
13127 
13128     switch(UO->getOpcode()) {
13129     case UO_Real:
13130     case UO_Imag:
13131     case UO_Extension:
13132       return getPrimaryDecl(UO->getSubExpr());
13133     default:
13134       return nullptr;
13135     }
13136   }
13137   case Stmt::ParenExprClass:
13138     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13139   case Stmt::ImplicitCastExprClass:
13140     // If the result of an implicit cast is an l-value, we care about
13141     // the sub-expression; otherwise, the result here doesn't matter.
13142     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13143   case Stmt::CXXUuidofExprClass:
13144     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13145   default:
13146     return nullptr;
13147   }
13148 }
13149 
13150 namespace {
13151 enum {
13152   AO_Bit_Field = 0,
13153   AO_Vector_Element = 1,
13154   AO_Property_Expansion = 2,
13155   AO_Register_Variable = 3,
13156   AO_Matrix_Element = 4,
13157   AO_No_Error = 5
13158 };
13159 }
13160 /// Diagnose invalid operand for address of operations.
13161 ///
13162 /// \param Type The type of operand which cannot have its address taken.
13163 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13164                                          Expr *E, unsigned Type) {
13165   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13166 }
13167 
13168 /// CheckAddressOfOperand - The operand of & must be either a function
13169 /// designator or an lvalue designating an object. If it is an lvalue, the
13170 /// object cannot be declared with storage class register or be a bit field.
13171 /// Note: The usual conversions are *not* applied to the operand of the &
13172 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13173 /// In C++, the operand might be an overloaded function name, in which case
13174 /// we allow the '&' but retain the overloaded-function type.
13175 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13176   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13177     if (PTy->getKind() == BuiltinType::Overload) {
13178       Expr *E = OrigOp.get()->IgnoreParens();
13179       if (!isa<OverloadExpr>(E)) {
13180         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13181         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13182           << OrigOp.get()->getSourceRange();
13183         return QualType();
13184       }
13185 
13186       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13187       if (isa<UnresolvedMemberExpr>(Ovl))
13188         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13189           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13190             << OrigOp.get()->getSourceRange();
13191           return QualType();
13192         }
13193 
13194       return Context.OverloadTy;
13195     }
13196 
13197     if (PTy->getKind() == BuiltinType::UnknownAny)
13198       return Context.UnknownAnyTy;
13199 
13200     if (PTy->getKind() == BuiltinType::BoundMember) {
13201       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13202         << OrigOp.get()->getSourceRange();
13203       return QualType();
13204     }
13205 
13206     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13207     if (OrigOp.isInvalid()) return QualType();
13208   }
13209 
13210   if (OrigOp.get()->isTypeDependent())
13211     return Context.DependentTy;
13212 
13213   assert(!OrigOp.get()->getType()->isPlaceholderType());
13214 
13215   // Make sure to ignore parentheses in subsequent checks
13216   Expr *op = OrigOp.get()->IgnoreParens();
13217 
13218   // In OpenCL captures for blocks called as lambda functions
13219   // are located in the private address space. Blocks used in
13220   // enqueue_kernel can be located in a different address space
13221   // depending on a vendor implementation. Thus preventing
13222   // taking an address of the capture to avoid invalid AS casts.
13223   if (LangOpts.OpenCL) {
13224     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13225     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13226       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13227       return QualType();
13228     }
13229   }
13230 
13231   if (getLangOpts().C99) {
13232     // Implement C99-only parts of addressof rules.
13233     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13234       if (uOp->getOpcode() == UO_Deref)
13235         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13236         // (assuming the deref expression is valid).
13237         return uOp->getSubExpr()->getType();
13238     }
13239     // Technically, there should be a check for array subscript
13240     // expressions here, but the result of one is always an lvalue anyway.
13241   }
13242   ValueDecl *dcl = getPrimaryDecl(op);
13243 
13244   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13245     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13246                                            op->getBeginLoc()))
13247       return QualType();
13248 
13249   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13250   unsigned AddressOfError = AO_No_Error;
13251 
13252   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13253     bool sfinae = (bool)isSFINAEContext();
13254     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13255                                   : diag::ext_typecheck_addrof_temporary)
13256       << op->getType() << op->getSourceRange();
13257     if (sfinae)
13258       return QualType();
13259     // Materialize the temporary as an lvalue so that we can take its address.
13260     OrigOp = op =
13261         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13262   } else if (isa<ObjCSelectorExpr>(op)) {
13263     return Context.getPointerType(op->getType());
13264   } else if (lval == Expr::LV_MemberFunction) {
13265     // If it's an instance method, make a member pointer.
13266     // The expression must have exactly the form &A::foo.
13267 
13268     // If the underlying expression isn't a decl ref, give up.
13269     if (!isa<DeclRefExpr>(op)) {
13270       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13271         << OrigOp.get()->getSourceRange();
13272       return QualType();
13273     }
13274     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13275     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13276 
13277     // The id-expression was parenthesized.
13278     if (OrigOp.get() != DRE) {
13279       Diag(OpLoc, diag::err_parens_pointer_member_function)
13280         << OrigOp.get()->getSourceRange();
13281 
13282     // The method was named without a qualifier.
13283     } else if (!DRE->getQualifier()) {
13284       if (MD->getParent()->getName().empty())
13285         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13286           << op->getSourceRange();
13287       else {
13288         SmallString<32> Str;
13289         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13290         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13291           << op->getSourceRange()
13292           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13293       }
13294     }
13295 
13296     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13297     if (isa<CXXDestructorDecl>(MD))
13298       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13299 
13300     QualType MPTy = Context.getMemberPointerType(
13301         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13302     // Under the MS ABI, lock down the inheritance model now.
13303     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13304       (void)isCompleteType(OpLoc, MPTy);
13305     return MPTy;
13306   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13307     // C99 6.5.3.2p1
13308     // The operand must be either an l-value or a function designator
13309     if (!op->getType()->isFunctionType()) {
13310       // Use a special diagnostic for loads from property references.
13311       if (isa<PseudoObjectExpr>(op)) {
13312         AddressOfError = AO_Property_Expansion;
13313       } else {
13314         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13315           << op->getType() << op->getSourceRange();
13316         return QualType();
13317       }
13318     }
13319   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13320     // The operand cannot be a bit-field
13321     AddressOfError = AO_Bit_Field;
13322   } else if (op->getObjectKind() == OK_VectorComponent) {
13323     // The operand cannot be an element of a vector
13324     AddressOfError = AO_Vector_Element;
13325   } else if (op->getObjectKind() == OK_MatrixComponent) {
13326     // The operand cannot be an element of a matrix.
13327     AddressOfError = AO_Matrix_Element;
13328   } else if (dcl) { // C99 6.5.3.2p1
13329     // We have an lvalue with a decl. Make sure the decl is not declared
13330     // with the register storage-class specifier.
13331     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13332       // in C++ it is not error to take address of a register
13333       // variable (c++03 7.1.1P3)
13334       if (vd->getStorageClass() == SC_Register &&
13335           !getLangOpts().CPlusPlus) {
13336         AddressOfError = AO_Register_Variable;
13337       }
13338     } else if (isa<MSPropertyDecl>(dcl)) {
13339       AddressOfError = AO_Property_Expansion;
13340     } else if (isa<FunctionTemplateDecl>(dcl)) {
13341       return Context.OverloadTy;
13342     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13343       // Okay: we can take the address of a field.
13344       // Could be a pointer to member, though, if there is an explicit
13345       // scope qualifier for the class.
13346       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13347         DeclContext *Ctx = dcl->getDeclContext();
13348         if (Ctx && Ctx->isRecord()) {
13349           if (dcl->getType()->isReferenceType()) {
13350             Diag(OpLoc,
13351                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13352               << dcl->getDeclName() << dcl->getType();
13353             return QualType();
13354           }
13355 
13356           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13357             Ctx = Ctx->getParent();
13358 
13359           QualType MPTy = Context.getMemberPointerType(
13360               op->getType(),
13361               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13362           // Under the MS ABI, lock down the inheritance model now.
13363           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13364             (void)isCompleteType(OpLoc, MPTy);
13365           return MPTy;
13366         }
13367       }
13368     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13369                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13370       llvm_unreachable("Unknown/unexpected decl type");
13371   }
13372 
13373   if (AddressOfError != AO_No_Error) {
13374     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13375     return QualType();
13376   }
13377 
13378   if (lval == Expr::LV_IncompleteVoidType) {
13379     // Taking the address of a void variable is technically illegal, but we
13380     // allow it in cases which are otherwise valid.
13381     // Example: "extern void x; void* y = &x;".
13382     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13383   }
13384 
13385   // If the operand has type "type", the result has type "pointer to type".
13386   if (op->getType()->isObjCObjectType())
13387     return Context.getObjCObjectPointerType(op->getType());
13388 
13389   CheckAddressOfPackedMember(op);
13390 
13391   return Context.getPointerType(op->getType());
13392 }
13393 
13394 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13395   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13396   if (!DRE)
13397     return;
13398   const Decl *D = DRE->getDecl();
13399   if (!D)
13400     return;
13401   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13402   if (!Param)
13403     return;
13404   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13405     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13406       return;
13407   if (FunctionScopeInfo *FD = S.getCurFunction())
13408     if (!FD->ModifiedNonNullParams.count(Param))
13409       FD->ModifiedNonNullParams.insert(Param);
13410 }
13411 
13412 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13413 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13414                                         SourceLocation OpLoc) {
13415   if (Op->isTypeDependent())
13416     return S.Context.DependentTy;
13417 
13418   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13419   if (ConvResult.isInvalid())
13420     return QualType();
13421   Op = ConvResult.get();
13422   QualType OpTy = Op->getType();
13423   QualType Result;
13424 
13425   if (isa<CXXReinterpretCastExpr>(Op)) {
13426     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13427     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13428                                      Op->getSourceRange());
13429   }
13430 
13431   if (const PointerType *PT = OpTy->getAs<PointerType>())
13432   {
13433     Result = PT->getPointeeType();
13434   }
13435   else if (const ObjCObjectPointerType *OPT =
13436              OpTy->getAs<ObjCObjectPointerType>())
13437     Result = OPT->getPointeeType();
13438   else {
13439     ExprResult PR = S.CheckPlaceholderExpr(Op);
13440     if (PR.isInvalid()) return QualType();
13441     if (PR.get() != Op)
13442       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13443   }
13444 
13445   if (Result.isNull()) {
13446     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13447       << OpTy << Op->getSourceRange();
13448     return QualType();
13449   }
13450 
13451   // Note that per both C89 and C99, indirection is always legal, even if Result
13452   // is an incomplete type or void.  It would be possible to warn about
13453   // dereferencing a void pointer, but it's completely well-defined, and such a
13454   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13455   // for pointers to 'void' but is fine for any other pointer type:
13456   //
13457   // C++ [expr.unary.op]p1:
13458   //   [...] the expression to which [the unary * operator] is applied shall
13459   //   be a pointer to an object type, or a pointer to a function type
13460   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13461     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13462       << OpTy << Op->getSourceRange();
13463 
13464   // Dereferences are usually l-values...
13465   VK = VK_LValue;
13466 
13467   // ...except that certain expressions are never l-values in C.
13468   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13469     VK = VK_RValue;
13470 
13471   return Result;
13472 }
13473 
13474 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13475   BinaryOperatorKind Opc;
13476   switch (Kind) {
13477   default: llvm_unreachable("Unknown binop!");
13478   case tok::periodstar:           Opc = BO_PtrMemD; break;
13479   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13480   case tok::star:                 Opc = BO_Mul; break;
13481   case tok::slash:                Opc = BO_Div; break;
13482   case tok::percent:              Opc = BO_Rem; break;
13483   case tok::plus:                 Opc = BO_Add; break;
13484   case tok::minus:                Opc = BO_Sub; break;
13485   case tok::lessless:             Opc = BO_Shl; break;
13486   case tok::greatergreater:       Opc = BO_Shr; break;
13487   case tok::lessequal:            Opc = BO_LE; break;
13488   case tok::less:                 Opc = BO_LT; break;
13489   case tok::greaterequal:         Opc = BO_GE; break;
13490   case tok::greater:              Opc = BO_GT; break;
13491   case tok::exclaimequal:         Opc = BO_NE; break;
13492   case tok::equalequal:           Opc = BO_EQ; break;
13493   case tok::spaceship:            Opc = BO_Cmp; break;
13494   case tok::amp:                  Opc = BO_And; break;
13495   case tok::caret:                Opc = BO_Xor; break;
13496   case tok::pipe:                 Opc = BO_Or; break;
13497   case tok::ampamp:               Opc = BO_LAnd; break;
13498   case tok::pipepipe:             Opc = BO_LOr; break;
13499   case tok::equal:                Opc = BO_Assign; break;
13500   case tok::starequal:            Opc = BO_MulAssign; break;
13501   case tok::slashequal:           Opc = BO_DivAssign; break;
13502   case tok::percentequal:         Opc = BO_RemAssign; break;
13503   case tok::plusequal:            Opc = BO_AddAssign; break;
13504   case tok::minusequal:           Opc = BO_SubAssign; break;
13505   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13506   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13507   case tok::ampequal:             Opc = BO_AndAssign; break;
13508   case tok::caretequal:           Opc = BO_XorAssign; break;
13509   case tok::pipeequal:            Opc = BO_OrAssign; break;
13510   case tok::comma:                Opc = BO_Comma; break;
13511   }
13512   return Opc;
13513 }
13514 
13515 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13516   tok::TokenKind Kind) {
13517   UnaryOperatorKind Opc;
13518   switch (Kind) {
13519   default: llvm_unreachable("Unknown unary op!");
13520   case tok::plusplus:     Opc = UO_PreInc; break;
13521   case tok::minusminus:   Opc = UO_PreDec; break;
13522   case tok::amp:          Opc = UO_AddrOf; break;
13523   case tok::star:         Opc = UO_Deref; break;
13524   case tok::plus:         Opc = UO_Plus; break;
13525   case tok::minus:        Opc = UO_Minus; break;
13526   case tok::tilde:        Opc = UO_Not; break;
13527   case tok::exclaim:      Opc = UO_LNot; break;
13528   case tok::kw___real:    Opc = UO_Real; break;
13529   case tok::kw___imag:    Opc = UO_Imag; break;
13530   case tok::kw___extension__: Opc = UO_Extension; break;
13531   }
13532   return Opc;
13533 }
13534 
13535 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13536 /// This warning suppressed in the event of macro expansions.
13537 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13538                                    SourceLocation OpLoc, bool IsBuiltin) {
13539   if (S.inTemplateInstantiation())
13540     return;
13541   if (S.isUnevaluatedContext())
13542     return;
13543   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13544     return;
13545   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13546   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13547   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13548   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13549   if (!LHSDeclRef || !RHSDeclRef ||
13550       LHSDeclRef->getLocation().isMacroID() ||
13551       RHSDeclRef->getLocation().isMacroID())
13552     return;
13553   const ValueDecl *LHSDecl =
13554     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13555   const ValueDecl *RHSDecl =
13556     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13557   if (LHSDecl != RHSDecl)
13558     return;
13559   if (LHSDecl->getType().isVolatileQualified())
13560     return;
13561   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13562     if (RefTy->getPointeeType().isVolatileQualified())
13563       return;
13564 
13565   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13566                           : diag::warn_self_assignment_overloaded)
13567       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13568       << RHSExpr->getSourceRange();
13569 }
13570 
13571 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13572 /// is usually indicative of introspection within the Objective-C pointer.
13573 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13574                                           SourceLocation OpLoc) {
13575   if (!S.getLangOpts().ObjC)
13576     return;
13577 
13578   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13579   const Expr *LHS = L.get();
13580   const Expr *RHS = R.get();
13581 
13582   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13583     ObjCPointerExpr = LHS;
13584     OtherExpr = RHS;
13585   }
13586   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13587     ObjCPointerExpr = RHS;
13588     OtherExpr = LHS;
13589   }
13590 
13591   // This warning is deliberately made very specific to reduce false
13592   // positives with logic that uses '&' for hashing.  This logic mainly
13593   // looks for code trying to introspect into tagged pointers, which
13594   // code should generally never do.
13595   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13596     unsigned Diag = diag::warn_objc_pointer_masking;
13597     // Determine if we are introspecting the result of performSelectorXXX.
13598     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13599     // Special case messages to -performSelector and friends, which
13600     // can return non-pointer values boxed in a pointer value.
13601     // Some clients may wish to silence warnings in this subcase.
13602     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13603       Selector S = ME->getSelector();
13604       StringRef SelArg0 = S.getNameForSlot(0);
13605       if (SelArg0.startswith("performSelector"))
13606         Diag = diag::warn_objc_pointer_masking_performSelector;
13607     }
13608 
13609     S.Diag(OpLoc, Diag)
13610       << ObjCPointerExpr->getSourceRange();
13611   }
13612 }
13613 
13614 static NamedDecl *getDeclFromExpr(Expr *E) {
13615   if (!E)
13616     return nullptr;
13617   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13618     return DRE->getDecl();
13619   if (auto *ME = dyn_cast<MemberExpr>(E))
13620     return ME->getMemberDecl();
13621   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13622     return IRE->getDecl();
13623   return nullptr;
13624 }
13625 
13626 // This helper function promotes a binary operator's operands (which are of a
13627 // half vector type) to a vector of floats and then truncates the result to
13628 // a vector of either half or short.
13629 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13630                                       BinaryOperatorKind Opc, QualType ResultTy,
13631                                       ExprValueKind VK, ExprObjectKind OK,
13632                                       bool IsCompAssign, SourceLocation OpLoc,
13633                                       FPOptions FPFeatures) {
13634   auto &Context = S.getASTContext();
13635   assert((isVector(ResultTy, Context.HalfTy) ||
13636           isVector(ResultTy, Context.ShortTy)) &&
13637          "Result must be a vector of half or short");
13638   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13639          isVector(RHS.get()->getType(), Context.HalfTy) &&
13640          "both operands expected to be a half vector");
13641 
13642   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13643   QualType BinOpResTy = RHS.get()->getType();
13644 
13645   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13646   // change BinOpResTy to a vector of ints.
13647   if (isVector(ResultTy, Context.ShortTy))
13648     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13649 
13650   if (IsCompAssign)
13651     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13652                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13653                                           BinOpResTy, BinOpResTy);
13654 
13655   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13656   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13657                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13658   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13659 }
13660 
13661 static std::pair<ExprResult, ExprResult>
13662 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13663                            Expr *RHSExpr) {
13664   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13665   if (!S.getLangOpts().CPlusPlus) {
13666     // C cannot handle TypoExpr nodes on either side of a binop because it
13667     // doesn't handle dependent types properly, so make sure any TypoExprs have
13668     // been dealt with before checking the operands.
13669     LHS = S.CorrectDelayedTyposInExpr(LHS);
13670     RHS = S.CorrectDelayedTyposInExpr(
13671         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13672         [Opc, LHS](Expr *E) {
13673           if (Opc != BO_Assign)
13674             return ExprResult(E);
13675           // Avoid correcting the RHS to the same Expr as the LHS.
13676           Decl *D = getDeclFromExpr(E);
13677           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13678         });
13679   }
13680   return std::make_pair(LHS, RHS);
13681 }
13682 
13683 /// Returns true if conversion between vectors of halfs and vectors of floats
13684 /// is needed.
13685 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13686                                      Expr *E0, Expr *E1 = nullptr) {
13687   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13688       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13689     return false;
13690 
13691   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13692     QualType Ty = E->IgnoreImplicit()->getType();
13693 
13694     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13695     // to vectors of floats. Although the element type of the vectors is __fp16,
13696     // the vectors shouldn't be treated as storage-only types. See the
13697     // discussion here: https://reviews.llvm.org/rG825235c140e7
13698     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13699       if (VT->getVectorKind() == VectorType::NeonVector)
13700         return false;
13701       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13702     }
13703     return false;
13704   };
13705 
13706   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13707 }
13708 
13709 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13710 /// operator @p Opc at location @c TokLoc. This routine only supports
13711 /// built-in operations; ActOnBinOp handles overloaded operators.
13712 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13713                                     BinaryOperatorKind Opc,
13714                                     Expr *LHSExpr, Expr *RHSExpr) {
13715   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13716     // The syntax only allows initializer lists on the RHS of assignment,
13717     // so we don't need to worry about accepting invalid code for
13718     // non-assignment operators.
13719     // C++11 5.17p9:
13720     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13721     //   of x = {} is x = T().
13722     InitializationKind Kind = InitializationKind::CreateDirectList(
13723         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13724     InitializedEntity Entity =
13725         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13726     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13727     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13728     if (Init.isInvalid())
13729       return Init;
13730     RHSExpr = Init.get();
13731   }
13732 
13733   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13734   QualType ResultTy;     // Result type of the binary operator.
13735   // The following two variables are used for compound assignment operators
13736   QualType CompLHSTy;    // Type of LHS after promotions for computation
13737   QualType CompResultTy; // Type of computation result
13738   ExprValueKind VK = VK_RValue;
13739   ExprObjectKind OK = OK_Ordinary;
13740   bool ConvertHalfVec = false;
13741 
13742   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13743   if (!LHS.isUsable() || !RHS.isUsable())
13744     return ExprError();
13745 
13746   if (getLangOpts().OpenCL) {
13747     QualType LHSTy = LHSExpr->getType();
13748     QualType RHSTy = RHSExpr->getType();
13749     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13750     // the ATOMIC_VAR_INIT macro.
13751     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13752       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13753       if (BO_Assign == Opc)
13754         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13755       else
13756         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13757       return ExprError();
13758     }
13759 
13760     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13761     // only with a builtin functions and therefore should be disallowed here.
13762     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13763         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13764         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13765         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13766       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13767       return ExprError();
13768     }
13769   }
13770 
13771   switch (Opc) {
13772   case BO_Assign:
13773     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13774     if (getLangOpts().CPlusPlus &&
13775         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13776       VK = LHS.get()->getValueKind();
13777       OK = LHS.get()->getObjectKind();
13778     }
13779     if (!ResultTy.isNull()) {
13780       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13781       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13782 
13783       // Avoid copying a block to the heap if the block is assigned to a local
13784       // auto variable that is declared in the same scope as the block. This
13785       // optimization is unsafe if the local variable is declared in an outer
13786       // scope. For example:
13787       //
13788       // BlockTy b;
13789       // {
13790       //   b = ^{...};
13791       // }
13792       // // It is unsafe to invoke the block here if it wasn't copied to the
13793       // // heap.
13794       // b();
13795 
13796       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13797         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13798           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13799             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13800               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13801 
13802       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13803         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13804                               NTCUC_Assignment, NTCUK_Copy);
13805     }
13806     RecordModifiableNonNullParam(*this, LHS.get());
13807     break;
13808   case BO_PtrMemD:
13809   case BO_PtrMemI:
13810     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13811                                             Opc == BO_PtrMemI);
13812     break;
13813   case BO_Mul:
13814   case BO_Div:
13815     ConvertHalfVec = true;
13816     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13817                                            Opc == BO_Div);
13818     break;
13819   case BO_Rem:
13820     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13821     break;
13822   case BO_Add:
13823     ConvertHalfVec = true;
13824     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13825     break;
13826   case BO_Sub:
13827     ConvertHalfVec = true;
13828     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13829     break;
13830   case BO_Shl:
13831   case BO_Shr:
13832     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13833     break;
13834   case BO_LE:
13835   case BO_LT:
13836   case BO_GE:
13837   case BO_GT:
13838     ConvertHalfVec = true;
13839     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13840     break;
13841   case BO_EQ:
13842   case BO_NE:
13843     ConvertHalfVec = true;
13844     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13845     break;
13846   case BO_Cmp:
13847     ConvertHalfVec = true;
13848     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13849     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13850     break;
13851   case BO_And:
13852     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13853     LLVM_FALLTHROUGH;
13854   case BO_Xor:
13855   case BO_Or:
13856     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13857     break;
13858   case BO_LAnd:
13859   case BO_LOr:
13860     ConvertHalfVec = true;
13861     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13862     break;
13863   case BO_MulAssign:
13864   case BO_DivAssign:
13865     ConvertHalfVec = true;
13866     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13867                                                Opc == BO_DivAssign);
13868     CompLHSTy = CompResultTy;
13869     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13870       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13871     break;
13872   case BO_RemAssign:
13873     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13874     CompLHSTy = CompResultTy;
13875     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13876       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13877     break;
13878   case BO_AddAssign:
13879     ConvertHalfVec = true;
13880     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13881     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13882       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13883     break;
13884   case BO_SubAssign:
13885     ConvertHalfVec = true;
13886     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13887     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13888       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13889     break;
13890   case BO_ShlAssign:
13891   case BO_ShrAssign:
13892     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13893     CompLHSTy = CompResultTy;
13894     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13895       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13896     break;
13897   case BO_AndAssign:
13898   case BO_OrAssign: // fallthrough
13899     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13900     LLVM_FALLTHROUGH;
13901   case BO_XorAssign:
13902     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13903     CompLHSTy = CompResultTy;
13904     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13905       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13906     break;
13907   case BO_Comma:
13908     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13909     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13910       VK = RHS.get()->getValueKind();
13911       OK = RHS.get()->getObjectKind();
13912     }
13913     break;
13914   }
13915   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13916     return ExprError();
13917 
13918   // Some of the binary operations require promoting operands of half vector to
13919   // float vectors and truncating the result back to half vector. For now, we do
13920   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13921   // arm64).
13922   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13923          isVector(LHS.get()->getType(), Context.HalfTy) &&
13924          "both sides are half vectors or neither sides are");
13925   ConvertHalfVec =
13926       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13927 
13928   // Check for array bounds violations for both sides of the BinaryOperator
13929   CheckArrayAccess(LHS.get());
13930   CheckArrayAccess(RHS.get());
13931 
13932   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13933     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13934                                                  &Context.Idents.get("object_setClass"),
13935                                                  SourceLocation(), LookupOrdinaryName);
13936     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13937       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13938       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13939           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13940                                         "object_setClass(")
13941           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13942                                           ",")
13943           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13944     }
13945     else
13946       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13947   }
13948   else if (const ObjCIvarRefExpr *OIRE =
13949            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13950     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13951 
13952   // Opc is not a compound assignment if CompResultTy is null.
13953   if (CompResultTy.isNull()) {
13954     if (ConvertHalfVec)
13955       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13956                                  OpLoc, CurFPFeatures);
13957     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13958                                   VK, OK, OpLoc, CurFPFeatures);
13959   }
13960 
13961   // Handle compound assignments.
13962   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13963       OK_ObjCProperty) {
13964     VK = VK_LValue;
13965     OK = LHS.get()->getObjectKind();
13966   }
13967 
13968   // The LHS is not converted to the result type for fixed-point compound
13969   // assignment as the common type is computed on demand. Reset the CompLHSTy
13970   // to the LHS type we would have gotten after unary conversions.
13971   if (CompResultTy->isFixedPointType())
13972     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13973 
13974   if (ConvertHalfVec)
13975     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13976                                OpLoc, CurFPFeatures);
13977 
13978   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13979                                         ResultTy, VK, OK, OpLoc, CurFPFeatures,
13980                                         CompLHSTy, CompResultTy);
13981 }
13982 
13983 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13984 /// operators are mixed in a way that suggests that the programmer forgot that
13985 /// comparison operators have higher precedence. The most typical example of
13986 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13987 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13988                                       SourceLocation OpLoc, Expr *LHSExpr,
13989                                       Expr *RHSExpr) {
13990   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13991   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13992 
13993   // Check that one of the sides is a comparison operator and the other isn't.
13994   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13995   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13996   if (isLeftComp == isRightComp)
13997     return;
13998 
13999   // Bitwise operations are sometimes used as eager logical ops.
14000   // Don't diagnose this.
14001   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14002   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14003   if (isLeftBitwise || isRightBitwise)
14004     return;
14005 
14006   SourceRange DiagRange = isLeftComp
14007                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14008                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14009   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14010   SourceRange ParensRange =
14011       isLeftComp
14012           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14013           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14014 
14015   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14016     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14017   SuggestParentheses(Self, OpLoc,
14018     Self.PDiag(diag::note_precedence_silence) << OpStr,
14019     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14020   SuggestParentheses(Self, OpLoc,
14021     Self.PDiag(diag::note_precedence_bitwise_first)
14022       << BinaryOperator::getOpcodeStr(Opc),
14023     ParensRange);
14024 }
14025 
14026 /// It accepts a '&&' expr that is inside a '||' one.
14027 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14028 /// in parentheses.
14029 static void
14030 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14031                                        BinaryOperator *Bop) {
14032   assert(Bop->getOpcode() == BO_LAnd);
14033   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14034       << Bop->getSourceRange() << OpLoc;
14035   SuggestParentheses(Self, Bop->getOperatorLoc(),
14036     Self.PDiag(diag::note_precedence_silence)
14037       << Bop->getOpcodeStr(),
14038     Bop->getSourceRange());
14039 }
14040 
14041 /// Returns true if the given expression can be evaluated as a constant
14042 /// 'true'.
14043 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14044   bool Res;
14045   return !E->isValueDependent() &&
14046          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14047 }
14048 
14049 /// Returns true if the given expression can be evaluated as a constant
14050 /// 'false'.
14051 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14052   bool Res;
14053   return !E->isValueDependent() &&
14054          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14055 }
14056 
14057 /// Look for '&&' in the left hand of a '||' expr.
14058 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14059                                              Expr *LHSExpr, Expr *RHSExpr) {
14060   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14061     if (Bop->getOpcode() == BO_LAnd) {
14062       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14063       if (EvaluatesAsFalse(S, RHSExpr))
14064         return;
14065       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14066       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14067         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14068     } else if (Bop->getOpcode() == BO_LOr) {
14069       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14070         // If it's "a || b && 1 || c" we didn't warn earlier for
14071         // "a || b && 1", but warn now.
14072         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14073           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14074       }
14075     }
14076   }
14077 }
14078 
14079 /// Look for '&&' in the right hand of a '||' expr.
14080 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14081                                              Expr *LHSExpr, Expr *RHSExpr) {
14082   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14083     if (Bop->getOpcode() == BO_LAnd) {
14084       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14085       if (EvaluatesAsFalse(S, LHSExpr))
14086         return;
14087       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14088       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14089         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14090     }
14091   }
14092 }
14093 
14094 /// Look for bitwise op in the left or right hand of a bitwise op with
14095 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14096 /// the '&' expression in parentheses.
14097 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14098                                          SourceLocation OpLoc, Expr *SubExpr) {
14099   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14100     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14101       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14102         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14103         << Bop->getSourceRange() << OpLoc;
14104       SuggestParentheses(S, Bop->getOperatorLoc(),
14105         S.PDiag(diag::note_precedence_silence)
14106           << Bop->getOpcodeStr(),
14107         Bop->getSourceRange());
14108     }
14109   }
14110 }
14111 
14112 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14113                                     Expr *SubExpr, StringRef Shift) {
14114   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14115     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14116       StringRef Op = Bop->getOpcodeStr();
14117       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14118           << Bop->getSourceRange() << OpLoc << Shift << Op;
14119       SuggestParentheses(S, Bop->getOperatorLoc(),
14120           S.PDiag(diag::note_precedence_silence) << Op,
14121           Bop->getSourceRange());
14122     }
14123   }
14124 }
14125 
14126 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14127                                  Expr *LHSExpr, Expr *RHSExpr) {
14128   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14129   if (!OCE)
14130     return;
14131 
14132   FunctionDecl *FD = OCE->getDirectCallee();
14133   if (!FD || !FD->isOverloadedOperator())
14134     return;
14135 
14136   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14137   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14138     return;
14139 
14140   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14141       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14142       << (Kind == OO_LessLess);
14143   SuggestParentheses(S, OCE->getOperatorLoc(),
14144                      S.PDiag(diag::note_precedence_silence)
14145                          << (Kind == OO_LessLess ? "<<" : ">>"),
14146                      OCE->getSourceRange());
14147   SuggestParentheses(
14148       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14149       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14150 }
14151 
14152 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14153 /// precedence.
14154 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14155                                     SourceLocation OpLoc, Expr *LHSExpr,
14156                                     Expr *RHSExpr){
14157   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14158   if (BinaryOperator::isBitwiseOp(Opc))
14159     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14160 
14161   // Diagnose "arg1 & arg2 | arg3"
14162   if ((Opc == BO_Or || Opc == BO_Xor) &&
14163       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14164     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14165     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14166   }
14167 
14168   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14169   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14170   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14171     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14172     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14173   }
14174 
14175   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14176       || Opc == BO_Shr) {
14177     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14178     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14179     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14180   }
14181 
14182   // Warn on overloaded shift operators and comparisons, such as:
14183   // cout << 5 == 4;
14184   if (BinaryOperator::isComparisonOp(Opc))
14185     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14186 }
14187 
14188 // Binary Operators.  'Tok' is the token for the operator.
14189 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14190                             tok::TokenKind Kind,
14191                             Expr *LHSExpr, Expr *RHSExpr) {
14192   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14193   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14194   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14195 
14196   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14197   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14198 
14199   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14200 }
14201 
14202 /// Build an overloaded binary operator expression in the given scope.
14203 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14204                                        BinaryOperatorKind Opc,
14205                                        Expr *LHS, Expr *RHS) {
14206   switch (Opc) {
14207   case BO_Assign:
14208   case BO_DivAssign:
14209   case BO_RemAssign:
14210   case BO_SubAssign:
14211   case BO_AndAssign:
14212   case BO_OrAssign:
14213   case BO_XorAssign:
14214     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14215     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14216     break;
14217   default:
14218     break;
14219   }
14220 
14221   // Find all of the overloaded operators visible from this
14222   // point. We perform both an operator-name lookup from the local
14223   // scope and an argument-dependent lookup based on the types of
14224   // the arguments.
14225   UnresolvedSet<16> Functions;
14226   OverloadedOperatorKind OverOp
14227     = BinaryOperator::getOverloadedOperator(Opc);
14228   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14229     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14230                                    RHS->getType(), Functions);
14231 
14232   // In C++20 onwards, we may have a second operator to look up.
14233   if (S.getLangOpts().CPlusPlus20) {
14234     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14235       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14236                                      RHS->getType(), Functions);
14237   }
14238 
14239   // Build the (potentially-overloaded, potentially-dependent)
14240   // binary operation.
14241   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14242 }
14243 
14244 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14245                             BinaryOperatorKind Opc,
14246                             Expr *LHSExpr, Expr *RHSExpr) {
14247   ExprResult LHS, RHS;
14248   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14249   if (!LHS.isUsable() || !RHS.isUsable())
14250     return ExprError();
14251   LHSExpr = LHS.get();
14252   RHSExpr = RHS.get();
14253 
14254   // We want to end up calling one of checkPseudoObjectAssignment
14255   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14256   // both expressions are overloadable or either is type-dependent),
14257   // or CreateBuiltinBinOp (in any other case).  We also want to get
14258   // any placeholder types out of the way.
14259 
14260   // Handle pseudo-objects in the LHS.
14261   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14262     // Assignments with a pseudo-object l-value need special analysis.
14263     if (pty->getKind() == BuiltinType::PseudoObject &&
14264         BinaryOperator::isAssignmentOp(Opc))
14265       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14266 
14267     // Don't resolve overloads if the other type is overloadable.
14268     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14269       // We can't actually test that if we still have a placeholder,
14270       // though.  Fortunately, none of the exceptions we see in that
14271       // code below are valid when the LHS is an overload set.  Note
14272       // that an overload set can be dependently-typed, but it never
14273       // instantiates to having an overloadable type.
14274       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14275       if (resolvedRHS.isInvalid()) return ExprError();
14276       RHSExpr = resolvedRHS.get();
14277 
14278       if (RHSExpr->isTypeDependent() ||
14279           RHSExpr->getType()->isOverloadableType())
14280         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14281     }
14282 
14283     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14284     // template, diagnose the missing 'template' keyword instead of diagnosing
14285     // an invalid use of a bound member function.
14286     //
14287     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14288     // to C++1z [over.over]/1.4, but we already checked for that case above.
14289     if (Opc == BO_LT && inTemplateInstantiation() &&
14290         (pty->getKind() == BuiltinType::BoundMember ||
14291          pty->getKind() == BuiltinType::Overload)) {
14292       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14293       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14294           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14295             return isa<FunctionTemplateDecl>(ND);
14296           })) {
14297         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14298                                 : OE->getNameLoc(),
14299              diag::err_template_kw_missing)
14300           << OE->getName().getAsString() << "";
14301         return ExprError();
14302       }
14303     }
14304 
14305     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14306     if (LHS.isInvalid()) return ExprError();
14307     LHSExpr = LHS.get();
14308   }
14309 
14310   // Handle pseudo-objects in the RHS.
14311   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14312     // An overload in the RHS can potentially be resolved by the type
14313     // being assigned to.
14314     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14315       if (getLangOpts().CPlusPlus &&
14316           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14317            LHSExpr->getType()->isOverloadableType()))
14318         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14319 
14320       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14321     }
14322 
14323     // Don't resolve overloads if the other type is overloadable.
14324     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14325         LHSExpr->getType()->isOverloadableType())
14326       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14327 
14328     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14329     if (!resolvedRHS.isUsable()) return ExprError();
14330     RHSExpr = resolvedRHS.get();
14331   }
14332 
14333   if (getLangOpts().CPlusPlus) {
14334     // If either expression is type-dependent, always build an
14335     // overloaded op.
14336     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14337       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14338 
14339     // Otherwise, build an overloaded op if either expression has an
14340     // overloadable type.
14341     if (LHSExpr->getType()->isOverloadableType() ||
14342         RHSExpr->getType()->isOverloadableType())
14343       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14344   }
14345 
14346   // Build a built-in binary operation.
14347   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14348 }
14349 
14350 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14351   if (T.isNull() || T->isDependentType())
14352     return false;
14353 
14354   if (!T->isPromotableIntegerType())
14355     return true;
14356 
14357   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14358 }
14359 
14360 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14361                                       UnaryOperatorKind Opc,
14362                                       Expr *InputExpr) {
14363   ExprResult Input = InputExpr;
14364   ExprValueKind VK = VK_RValue;
14365   ExprObjectKind OK = OK_Ordinary;
14366   QualType resultType;
14367   bool CanOverflow = false;
14368 
14369   bool ConvertHalfVec = false;
14370   if (getLangOpts().OpenCL) {
14371     QualType Ty = InputExpr->getType();
14372     // The only legal unary operation for atomics is '&'.
14373     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14374     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14375     // only with a builtin functions and therefore should be disallowed here.
14376         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14377         || Ty->isBlockPointerType())) {
14378       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14379                        << InputExpr->getType()
14380                        << Input.get()->getSourceRange());
14381     }
14382   }
14383 
14384   switch (Opc) {
14385   case UO_PreInc:
14386   case UO_PreDec:
14387   case UO_PostInc:
14388   case UO_PostDec:
14389     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14390                                                 OpLoc,
14391                                                 Opc == UO_PreInc ||
14392                                                 Opc == UO_PostInc,
14393                                                 Opc == UO_PreInc ||
14394                                                 Opc == UO_PreDec);
14395     CanOverflow = isOverflowingIntegerType(Context, resultType);
14396     break;
14397   case UO_AddrOf:
14398     resultType = CheckAddressOfOperand(Input, OpLoc);
14399     CheckAddressOfNoDeref(InputExpr);
14400     RecordModifiableNonNullParam(*this, InputExpr);
14401     break;
14402   case UO_Deref: {
14403     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14404     if (Input.isInvalid()) return ExprError();
14405     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14406     break;
14407   }
14408   case UO_Plus:
14409   case UO_Minus:
14410     CanOverflow = Opc == UO_Minus &&
14411                   isOverflowingIntegerType(Context, Input.get()->getType());
14412     Input = UsualUnaryConversions(Input.get());
14413     if (Input.isInvalid()) return ExprError();
14414     // Unary plus and minus require promoting an operand of half vector to a
14415     // float vector and truncating the result back to a half vector. For now, we
14416     // do this only when HalfArgsAndReturns is set (that is, when the target is
14417     // arm or arm64).
14418     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14419 
14420     // If the operand is a half vector, promote it to a float vector.
14421     if (ConvertHalfVec)
14422       Input = convertVector(Input.get(), Context.FloatTy, *this);
14423     resultType = Input.get()->getType();
14424     if (resultType->isDependentType())
14425       break;
14426     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14427       break;
14428     else if (resultType->isVectorType() &&
14429              // The z vector extensions don't allow + or - with bool vectors.
14430              (!Context.getLangOpts().ZVector ||
14431               resultType->castAs<VectorType>()->getVectorKind() !=
14432               VectorType::AltiVecBool))
14433       break;
14434     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14435              Opc == UO_Plus &&
14436              resultType->isPointerType())
14437       break;
14438 
14439     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14440       << resultType << Input.get()->getSourceRange());
14441 
14442   case UO_Not: // bitwise complement
14443     Input = UsualUnaryConversions(Input.get());
14444     if (Input.isInvalid())
14445       return ExprError();
14446     resultType = Input.get()->getType();
14447     if (resultType->isDependentType())
14448       break;
14449     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14450     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14451       // C99 does not support '~' for complex conjugation.
14452       Diag(OpLoc, diag::ext_integer_complement_complex)
14453           << resultType << Input.get()->getSourceRange();
14454     else if (resultType->hasIntegerRepresentation())
14455       break;
14456     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14457       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14458       // on vector float types.
14459       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14460       if (!T->isIntegerType())
14461         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14462                           << resultType << Input.get()->getSourceRange());
14463     } else {
14464       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14465                        << resultType << Input.get()->getSourceRange());
14466     }
14467     break;
14468 
14469   case UO_LNot: // logical negation
14470     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14471     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14472     if (Input.isInvalid()) return ExprError();
14473     resultType = Input.get()->getType();
14474 
14475     // Though we still have to promote half FP to float...
14476     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14477       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14478       resultType = Context.FloatTy;
14479     }
14480 
14481     if (resultType->isDependentType())
14482       break;
14483     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14484       // C99 6.5.3.3p1: ok, fallthrough;
14485       if (Context.getLangOpts().CPlusPlus) {
14486         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14487         // operand contextually converted to bool.
14488         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14489                                   ScalarTypeToBooleanCastKind(resultType));
14490       } else if (Context.getLangOpts().OpenCL &&
14491                  Context.getLangOpts().OpenCLVersion < 120) {
14492         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14493         // operate on scalar float types.
14494         if (!resultType->isIntegerType() && !resultType->isPointerType())
14495           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14496                            << resultType << Input.get()->getSourceRange());
14497       }
14498     } else if (resultType->isExtVectorType()) {
14499       if (Context.getLangOpts().OpenCL &&
14500           Context.getLangOpts().OpenCLVersion < 120 &&
14501           !Context.getLangOpts().OpenCLCPlusPlus) {
14502         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14503         // operate on vector float types.
14504         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14505         if (!T->isIntegerType())
14506           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14507                            << resultType << Input.get()->getSourceRange());
14508       }
14509       // Vector logical not returns the signed variant of the operand type.
14510       resultType = GetSignedVectorType(resultType);
14511       break;
14512     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14513       const VectorType *VTy = resultType->castAs<VectorType>();
14514       if (VTy->getVectorKind() != VectorType::GenericVector)
14515         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14516                          << resultType << Input.get()->getSourceRange());
14517 
14518       // Vector logical not returns the signed variant of the operand type.
14519       resultType = GetSignedVectorType(resultType);
14520       break;
14521     } else {
14522       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14523         << resultType << Input.get()->getSourceRange());
14524     }
14525 
14526     // LNot always has type int. C99 6.5.3.3p5.
14527     // In C++, it's bool. C++ 5.3.1p8
14528     resultType = Context.getLogicalOperationType();
14529     break;
14530   case UO_Real:
14531   case UO_Imag:
14532     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14533     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14534     // complex l-values to ordinary l-values and all other values to r-values.
14535     if (Input.isInvalid()) return ExprError();
14536     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14537       if (Input.get()->getValueKind() != VK_RValue &&
14538           Input.get()->getObjectKind() == OK_Ordinary)
14539         VK = Input.get()->getValueKind();
14540     } else if (!getLangOpts().CPlusPlus) {
14541       // In C, a volatile scalar is read by __imag. In C++, it is not.
14542       Input = DefaultLvalueConversion(Input.get());
14543     }
14544     break;
14545   case UO_Extension:
14546     resultType = Input.get()->getType();
14547     VK = Input.get()->getValueKind();
14548     OK = Input.get()->getObjectKind();
14549     break;
14550   case UO_Coawait:
14551     // It's unnecessary to represent the pass-through operator co_await in the
14552     // AST; just return the input expression instead.
14553     assert(!Input.get()->getType()->isDependentType() &&
14554                    "the co_await expression must be non-dependant before "
14555                    "building operator co_await");
14556     return Input;
14557   }
14558   if (resultType.isNull() || Input.isInvalid())
14559     return ExprError();
14560 
14561   // Check for array bounds violations in the operand of the UnaryOperator,
14562   // except for the '*' and '&' operators that have to be handled specially
14563   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14564   // that are explicitly defined as valid by the standard).
14565   if (Opc != UO_AddrOf && Opc != UO_Deref)
14566     CheckArrayAccess(Input.get());
14567 
14568   auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK,
14569                                    OK, OpLoc, CanOverflow, CurFPFeatures);
14570 
14571   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14572       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14573     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14574 
14575   // Convert the result back to a half vector.
14576   if (ConvertHalfVec)
14577     return convertVector(UO, Context.HalfTy, *this);
14578   return UO;
14579 }
14580 
14581 /// Determine whether the given expression is a qualified member
14582 /// access expression, of a form that could be turned into a pointer to member
14583 /// with the address-of operator.
14584 bool Sema::isQualifiedMemberAccess(Expr *E) {
14585   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14586     if (!DRE->getQualifier())
14587       return false;
14588 
14589     ValueDecl *VD = DRE->getDecl();
14590     if (!VD->isCXXClassMember())
14591       return false;
14592 
14593     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14594       return true;
14595     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14596       return Method->isInstance();
14597 
14598     return false;
14599   }
14600 
14601   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14602     if (!ULE->getQualifier())
14603       return false;
14604 
14605     for (NamedDecl *D : ULE->decls()) {
14606       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14607         if (Method->isInstance())
14608           return true;
14609       } else {
14610         // Overload set does not contain methods.
14611         break;
14612       }
14613     }
14614 
14615     return false;
14616   }
14617 
14618   return false;
14619 }
14620 
14621 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14622                               UnaryOperatorKind Opc, Expr *Input) {
14623   // First things first: handle placeholders so that the
14624   // overloaded-operator check considers the right type.
14625   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14626     // Increment and decrement of pseudo-object references.
14627     if (pty->getKind() == BuiltinType::PseudoObject &&
14628         UnaryOperator::isIncrementDecrementOp(Opc))
14629       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14630 
14631     // extension is always a builtin operator.
14632     if (Opc == UO_Extension)
14633       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14634 
14635     // & gets special logic for several kinds of placeholder.
14636     // The builtin code knows what to do.
14637     if (Opc == UO_AddrOf &&
14638         (pty->getKind() == BuiltinType::Overload ||
14639          pty->getKind() == BuiltinType::UnknownAny ||
14640          pty->getKind() == BuiltinType::BoundMember))
14641       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14642 
14643     // Anything else needs to be handled now.
14644     ExprResult Result = CheckPlaceholderExpr(Input);
14645     if (Result.isInvalid()) return ExprError();
14646     Input = Result.get();
14647   }
14648 
14649   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14650       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14651       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14652     // Find all of the overloaded operators visible from this
14653     // point. We perform both an operator-name lookup from the local
14654     // scope and an argument-dependent lookup based on the types of
14655     // the arguments.
14656     UnresolvedSet<16> Functions;
14657     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14658     if (S && OverOp != OO_None)
14659       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14660                                    Functions);
14661 
14662     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14663   }
14664 
14665   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14666 }
14667 
14668 // Unary Operators.  'Tok' is the token for the operator.
14669 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14670                               tok::TokenKind Op, Expr *Input) {
14671   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14672 }
14673 
14674 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14675 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14676                                 LabelDecl *TheDecl) {
14677   TheDecl->markUsed(Context);
14678   // Create the AST node.  The address of a label always has type 'void*'.
14679   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14680                                      Context.getPointerType(Context.VoidTy));
14681 }
14682 
14683 void Sema::ActOnStartStmtExpr() {
14684   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14685 }
14686 
14687 void Sema::ActOnStmtExprError() {
14688   // Note that function is also called by TreeTransform when leaving a
14689   // StmtExpr scope without rebuilding anything.
14690 
14691   DiscardCleanupsInEvaluationContext();
14692   PopExpressionEvaluationContext();
14693 }
14694 
14695 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14696                                SourceLocation RPLoc) {
14697   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14698 }
14699 
14700 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14701                                SourceLocation RPLoc, unsigned TemplateDepth) {
14702   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14703   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14704 
14705   if (hasAnyUnrecoverableErrorsInThisFunction())
14706     DiscardCleanupsInEvaluationContext();
14707   assert(!Cleanup.exprNeedsCleanups() &&
14708          "cleanups within StmtExpr not correctly bound!");
14709   PopExpressionEvaluationContext();
14710 
14711   // FIXME: there are a variety of strange constraints to enforce here, for
14712   // example, it is not possible to goto into a stmt expression apparently.
14713   // More semantic analysis is needed.
14714 
14715   // If there are sub-stmts in the compound stmt, take the type of the last one
14716   // as the type of the stmtexpr.
14717   QualType Ty = Context.VoidTy;
14718   bool StmtExprMayBindToTemp = false;
14719   if (!Compound->body_empty()) {
14720     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14721     if (const auto *LastStmt =
14722             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14723       if (const Expr *Value = LastStmt->getExprStmt()) {
14724         StmtExprMayBindToTemp = true;
14725         Ty = Value->getType();
14726       }
14727     }
14728   }
14729 
14730   // FIXME: Check that expression type is complete/non-abstract; statement
14731   // expressions are not lvalues.
14732   Expr *ResStmtExpr =
14733       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14734   if (StmtExprMayBindToTemp)
14735     return MaybeBindToTemporary(ResStmtExpr);
14736   return ResStmtExpr;
14737 }
14738 
14739 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14740   if (ER.isInvalid())
14741     return ExprError();
14742 
14743   // Do function/array conversion on the last expression, but not
14744   // lvalue-to-rvalue.  However, initialize an unqualified type.
14745   ER = DefaultFunctionArrayConversion(ER.get());
14746   if (ER.isInvalid())
14747     return ExprError();
14748   Expr *E = ER.get();
14749 
14750   if (E->isTypeDependent())
14751     return E;
14752 
14753   // In ARC, if the final expression ends in a consume, splice
14754   // the consume out and bind it later.  In the alternate case
14755   // (when dealing with a retainable type), the result
14756   // initialization will create a produce.  In both cases the
14757   // result will be +1, and we'll need to balance that out with
14758   // a bind.
14759   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14760   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14761     return Cast->getSubExpr();
14762 
14763   // FIXME: Provide a better location for the initialization.
14764   return PerformCopyInitialization(
14765       InitializedEntity::InitializeStmtExprResult(
14766           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14767       SourceLocation(), E);
14768 }
14769 
14770 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14771                                       TypeSourceInfo *TInfo,
14772                                       ArrayRef<OffsetOfComponent> Components,
14773                                       SourceLocation RParenLoc) {
14774   QualType ArgTy = TInfo->getType();
14775   bool Dependent = ArgTy->isDependentType();
14776   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14777 
14778   // We must have at least one component that refers to the type, and the first
14779   // one is known to be a field designator.  Verify that the ArgTy represents
14780   // a struct/union/class.
14781   if (!Dependent && !ArgTy->isRecordType())
14782     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14783                        << ArgTy << TypeRange);
14784 
14785   // Type must be complete per C99 7.17p3 because a declaring a variable
14786   // with an incomplete type would be ill-formed.
14787   if (!Dependent
14788       && RequireCompleteType(BuiltinLoc, ArgTy,
14789                              diag::err_offsetof_incomplete_type, TypeRange))
14790     return ExprError();
14791 
14792   bool DidWarnAboutNonPOD = false;
14793   QualType CurrentType = ArgTy;
14794   SmallVector<OffsetOfNode, 4> Comps;
14795   SmallVector<Expr*, 4> Exprs;
14796   for (const OffsetOfComponent &OC : Components) {
14797     if (OC.isBrackets) {
14798       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14799       if (!CurrentType->isDependentType()) {
14800         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14801         if(!AT)
14802           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14803                            << CurrentType);
14804         CurrentType = AT->getElementType();
14805       } else
14806         CurrentType = Context.DependentTy;
14807 
14808       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14809       if (IdxRval.isInvalid())
14810         return ExprError();
14811       Expr *Idx = IdxRval.get();
14812 
14813       // The expression must be an integral expression.
14814       // FIXME: An integral constant expression?
14815       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14816           !Idx->getType()->isIntegerType())
14817         return ExprError(
14818             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14819             << Idx->getSourceRange());
14820 
14821       // Record this array index.
14822       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14823       Exprs.push_back(Idx);
14824       continue;
14825     }
14826 
14827     // Offset of a field.
14828     if (CurrentType->isDependentType()) {
14829       // We have the offset of a field, but we can't look into the dependent
14830       // type. Just record the identifier of the field.
14831       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14832       CurrentType = Context.DependentTy;
14833       continue;
14834     }
14835 
14836     // We need to have a complete type to look into.
14837     if (RequireCompleteType(OC.LocStart, CurrentType,
14838                             diag::err_offsetof_incomplete_type))
14839       return ExprError();
14840 
14841     // Look for the designated field.
14842     const RecordType *RC = CurrentType->getAs<RecordType>();
14843     if (!RC)
14844       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14845                        << CurrentType);
14846     RecordDecl *RD = RC->getDecl();
14847 
14848     // C++ [lib.support.types]p5:
14849     //   The macro offsetof accepts a restricted set of type arguments in this
14850     //   International Standard. type shall be a POD structure or a POD union
14851     //   (clause 9).
14852     // C++11 [support.types]p4:
14853     //   If type is not a standard-layout class (Clause 9), the results are
14854     //   undefined.
14855     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14856       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14857       unsigned DiagID =
14858         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14859                             : diag::ext_offsetof_non_pod_type;
14860 
14861       if (!IsSafe && !DidWarnAboutNonPOD &&
14862           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14863                               PDiag(DiagID)
14864                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14865                               << CurrentType))
14866         DidWarnAboutNonPOD = true;
14867     }
14868 
14869     // Look for the field.
14870     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14871     LookupQualifiedName(R, RD);
14872     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14873     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14874     if (!MemberDecl) {
14875       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14876         MemberDecl = IndirectMemberDecl->getAnonField();
14877     }
14878 
14879     if (!MemberDecl)
14880       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14881                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14882                                                               OC.LocEnd));
14883 
14884     // C99 7.17p3:
14885     //   (If the specified member is a bit-field, the behavior is undefined.)
14886     //
14887     // We diagnose this as an error.
14888     if (MemberDecl->isBitField()) {
14889       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14890         << MemberDecl->getDeclName()
14891         << SourceRange(BuiltinLoc, RParenLoc);
14892       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14893       return ExprError();
14894     }
14895 
14896     RecordDecl *Parent = MemberDecl->getParent();
14897     if (IndirectMemberDecl)
14898       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14899 
14900     // If the member was found in a base class, introduce OffsetOfNodes for
14901     // the base class indirections.
14902     CXXBasePaths Paths;
14903     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14904                       Paths)) {
14905       if (Paths.getDetectedVirtual()) {
14906         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14907           << MemberDecl->getDeclName()
14908           << SourceRange(BuiltinLoc, RParenLoc);
14909         return ExprError();
14910       }
14911 
14912       CXXBasePath &Path = Paths.front();
14913       for (const CXXBasePathElement &B : Path)
14914         Comps.push_back(OffsetOfNode(B.Base));
14915     }
14916 
14917     if (IndirectMemberDecl) {
14918       for (auto *FI : IndirectMemberDecl->chain()) {
14919         assert(isa<FieldDecl>(FI));
14920         Comps.push_back(OffsetOfNode(OC.LocStart,
14921                                      cast<FieldDecl>(FI), OC.LocEnd));
14922       }
14923     } else
14924       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14925 
14926     CurrentType = MemberDecl->getType().getNonReferenceType();
14927   }
14928 
14929   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14930                               Comps, Exprs, RParenLoc);
14931 }
14932 
14933 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14934                                       SourceLocation BuiltinLoc,
14935                                       SourceLocation TypeLoc,
14936                                       ParsedType ParsedArgTy,
14937                                       ArrayRef<OffsetOfComponent> Components,
14938                                       SourceLocation RParenLoc) {
14939 
14940   TypeSourceInfo *ArgTInfo;
14941   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14942   if (ArgTy.isNull())
14943     return ExprError();
14944 
14945   if (!ArgTInfo)
14946     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14947 
14948   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14949 }
14950 
14951 
14952 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14953                                  Expr *CondExpr,
14954                                  Expr *LHSExpr, Expr *RHSExpr,
14955                                  SourceLocation RPLoc) {
14956   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14957 
14958   ExprValueKind VK = VK_RValue;
14959   ExprObjectKind OK = OK_Ordinary;
14960   QualType resType;
14961   bool CondIsTrue = false;
14962   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14963     resType = Context.DependentTy;
14964   } else {
14965     // The conditional expression is required to be a constant expression.
14966     llvm::APSInt condEval(32);
14967     ExprResult CondICE
14968       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14969           diag::err_typecheck_choose_expr_requires_constant, false);
14970     if (CondICE.isInvalid())
14971       return ExprError();
14972     CondExpr = CondICE.get();
14973     CondIsTrue = condEval.getZExtValue();
14974 
14975     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14976     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14977 
14978     resType = ActiveExpr->getType();
14979     VK = ActiveExpr->getValueKind();
14980     OK = ActiveExpr->getObjectKind();
14981   }
14982 
14983   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14984                                   resType, VK, OK, RPLoc, CondIsTrue);
14985 }
14986 
14987 //===----------------------------------------------------------------------===//
14988 // Clang Extensions.
14989 //===----------------------------------------------------------------------===//
14990 
14991 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14992 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14993   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14994 
14995   if (LangOpts.CPlusPlus) {
14996     MangleNumberingContext *MCtx;
14997     Decl *ManglingContextDecl;
14998     std::tie(MCtx, ManglingContextDecl) =
14999         getCurrentMangleNumberContext(Block->getDeclContext());
15000     if (MCtx) {
15001       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15002       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15003     }
15004   }
15005 
15006   PushBlockScope(CurScope, Block);
15007   CurContext->addDecl(Block);
15008   if (CurScope)
15009     PushDeclContext(CurScope, Block);
15010   else
15011     CurContext = Block;
15012 
15013   getCurBlock()->HasImplicitReturnType = true;
15014 
15015   // Enter a new evaluation context to insulate the block from any
15016   // cleanups from the enclosing full-expression.
15017   PushExpressionEvaluationContext(
15018       ExpressionEvaluationContext::PotentiallyEvaluated);
15019 }
15020 
15021 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15022                                Scope *CurScope) {
15023   assert(ParamInfo.getIdentifier() == nullptr &&
15024          "block-id should have no identifier!");
15025   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15026   BlockScopeInfo *CurBlock = getCurBlock();
15027 
15028   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15029   QualType T = Sig->getType();
15030 
15031   // FIXME: We should allow unexpanded parameter packs here, but that would,
15032   // in turn, make the block expression contain unexpanded parameter packs.
15033   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15034     // Drop the parameters.
15035     FunctionProtoType::ExtProtoInfo EPI;
15036     EPI.HasTrailingReturn = false;
15037     EPI.TypeQuals.addConst();
15038     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15039     Sig = Context.getTrivialTypeSourceInfo(T);
15040   }
15041 
15042   // GetTypeForDeclarator always produces a function type for a block
15043   // literal signature.  Furthermore, it is always a FunctionProtoType
15044   // unless the function was written with a typedef.
15045   assert(T->isFunctionType() &&
15046          "GetTypeForDeclarator made a non-function block signature");
15047 
15048   // Look for an explicit signature in that function type.
15049   FunctionProtoTypeLoc ExplicitSignature;
15050 
15051   if ((ExplicitSignature = Sig->getTypeLoc()
15052                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15053 
15054     // Check whether that explicit signature was synthesized by
15055     // GetTypeForDeclarator.  If so, don't save that as part of the
15056     // written signature.
15057     if (ExplicitSignature.getLocalRangeBegin() ==
15058         ExplicitSignature.getLocalRangeEnd()) {
15059       // This would be much cheaper if we stored TypeLocs instead of
15060       // TypeSourceInfos.
15061       TypeLoc Result = ExplicitSignature.getReturnLoc();
15062       unsigned Size = Result.getFullDataSize();
15063       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15064       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15065 
15066       ExplicitSignature = FunctionProtoTypeLoc();
15067     }
15068   }
15069 
15070   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15071   CurBlock->FunctionType = T;
15072 
15073   const FunctionType *Fn = T->getAs<FunctionType>();
15074   QualType RetTy = Fn->getReturnType();
15075   bool isVariadic =
15076     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15077 
15078   CurBlock->TheDecl->setIsVariadic(isVariadic);
15079 
15080   // Context.DependentTy is used as a placeholder for a missing block
15081   // return type.  TODO:  what should we do with declarators like:
15082   //   ^ * { ... }
15083   // If the answer is "apply template argument deduction"....
15084   if (RetTy != Context.DependentTy) {
15085     CurBlock->ReturnType = RetTy;
15086     CurBlock->TheDecl->setBlockMissingReturnType(false);
15087     CurBlock->HasImplicitReturnType = false;
15088   }
15089 
15090   // Push block parameters from the declarator if we had them.
15091   SmallVector<ParmVarDecl*, 8> Params;
15092   if (ExplicitSignature) {
15093     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15094       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15095       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15096           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15097         // Diagnose this as an extension in C17 and earlier.
15098         if (!getLangOpts().C2x)
15099           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15100       }
15101       Params.push_back(Param);
15102     }
15103 
15104   // Fake up parameter variables if we have a typedef, like
15105   //   ^ fntype { ... }
15106   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15107     for (const auto &I : Fn->param_types()) {
15108       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15109           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15110       Params.push_back(Param);
15111     }
15112   }
15113 
15114   // Set the parameters on the block decl.
15115   if (!Params.empty()) {
15116     CurBlock->TheDecl->setParams(Params);
15117     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15118                              /*CheckParameterNames=*/false);
15119   }
15120 
15121   // Finally we can process decl attributes.
15122   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15123 
15124   // Put the parameter variables in scope.
15125   for (auto AI : CurBlock->TheDecl->parameters()) {
15126     AI->setOwningFunction(CurBlock->TheDecl);
15127 
15128     // If this has an identifier, add it to the scope stack.
15129     if (AI->getIdentifier()) {
15130       CheckShadow(CurBlock->TheScope, AI);
15131 
15132       PushOnScopeChains(AI, CurBlock->TheScope);
15133     }
15134   }
15135 }
15136 
15137 /// ActOnBlockError - If there is an error parsing a block, this callback
15138 /// is invoked to pop the information about the block from the action impl.
15139 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15140   // Leave the expression-evaluation context.
15141   DiscardCleanupsInEvaluationContext();
15142   PopExpressionEvaluationContext();
15143 
15144   // Pop off CurBlock, handle nested blocks.
15145   PopDeclContext();
15146   PopFunctionScopeInfo();
15147 }
15148 
15149 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15150 /// literal was successfully completed.  ^(int x){...}
15151 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15152                                     Stmt *Body, Scope *CurScope) {
15153   // If blocks are disabled, emit an error.
15154   if (!LangOpts.Blocks)
15155     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15156 
15157   // Leave the expression-evaluation context.
15158   if (hasAnyUnrecoverableErrorsInThisFunction())
15159     DiscardCleanupsInEvaluationContext();
15160   assert(!Cleanup.exprNeedsCleanups() &&
15161          "cleanups within block not correctly bound!");
15162   PopExpressionEvaluationContext();
15163 
15164   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15165   BlockDecl *BD = BSI->TheDecl;
15166 
15167   if (BSI->HasImplicitReturnType)
15168     deduceClosureReturnType(*BSI);
15169 
15170   QualType RetTy = Context.VoidTy;
15171   if (!BSI->ReturnType.isNull())
15172     RetTy = BSI->ReturnType;
15173 
15174   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15175   QualType BlockTy;
15176 
15177   // If the user wrote a function type in some form, try to use that.
15178   if (!BSI->FunctionType.isNull()) {
15179     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15180 
15181     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15182     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15183 
15184     // Turn protoless block types into nullary block types.
15185     if (isa<FunctionNoProtoType>(FTy)) {
15186       FunctionProtoType::ExtProtoInfo EPI;
15187       EPI.ExtInfo = Ext;
15188       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15189 
15190     // Otherwise, if we don't need to change anything about the function type,
15191     // preserve its sugar structure.
15192     } else if (FTy->getReturnType() == RetTy &&
15193                (!NoReturn || FTy->getNoReturnAttr())) {
15194       BlockTy = BSI->FunctionType;
15195 
15196     // Otherwise, make the minimal modifications to the function type.
15197     } else {
15198       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15199       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15200       EPI.TypeQuals = Qualifiers();
15201       EPI.ExtInfo = Ext;
15202       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15203     }
15204 
15205   // If we don't have a function type, just build one from nothing.
15206   } else {
15207     FunctionProtoType::ExtProtoInfo EPI;
15208     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15209     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15210   }
15211 
15212   DiagnoseUnusedParameters(BD->parameters());
15213   BlockTy = Context.getBlockPointerType(BlockTy);
15214 
15215   // If needed, diagnose invalid gotos and switches in the block.
15216   if (getCurFunction()->NeedsScopeChecking() &&
15217       !PP.isCodeCompletionEnabled())
15218     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15219 
15220   BD->setBody(cast<CompoundStmt>(Body));
15221 
15222   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15223     DiagnoseUnguardedAvailabilityViolations(BD);
15224 
15225   // Try to apply the named return value optimization. We have to check again
15226   // if we can do this, though, because blocks keep return statements around
15227   // to deduce an implicit return type.
15228   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15229       !BD->isDependentContext())
15230     computeNRVO(Body, BSI);
15231 
15232   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15233       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15234     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15235                           NTCUK_Destruct|NTCUK_Copy);
15236 
15237   PopDeclContext();
15238 
15239   // Pop the block scope now but keep it alive to the end of this function.
15240   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15241   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15242 
15243   // Set the captured variables on the block.
15244   SmallVector<BlockDecl::Capture, 4> Captures;
15245   for (Capture &Cap : BSI->Captures) {
15246     if (Cap.isInvalid() || Cap.isThisCapture())
15247       continue;
15248 
15249     VarDecl *Var = Cap.getVariable();
15250     Expr *CopyExpr = nullptr;
15251     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15252       if (const RecordType *Record =
15253               Cap.getCaptureType()->getAs<RecordType>()) {
15254         // The capture logic needs the destructor, so make sure we mark it.
15255         // Usually this is unnecessary because most local variables have
15256         // their destructors marked at declaration time, but parameters are
15257         // an exception because it's technically only the call site that
15258         // actually requires the destructor.
15259         if (isa<ParmVarDecl>(Var))
15260           FinalizeVarWithDestructor(Var, Record);
15261 
15262         // Enter a separate potentially-evaluated context while building block
15263         // initializers to isolate their cleanups from those of the block
15264         // itself.
15265         // FIXME: Is this appropriate even when the block itself occurs in an
15266         // unevaluated operand?
15267         EnterExpressionEvaluationContext EvalContext(
15268             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15269 
15270         SourceLocation Loc = Cap.getLocation();
15271 
15272         ExprResult Result = BuildDeclarationNameExpr(
15273             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15274 
15275         // According to the blocks spec, the capture of a variable from
15276         // the stack requires a const copy constructor.  This is not true
15277         // of the copy/move done to move a __block variable to the heap.
15278         if (!Result.isInvalid() &&
15279             !Result.get()->getType().isConstQualified()) {
15280           Result = ImpCastExprToType(Result.get(),
15281                                      Result.get()->getType().withConst(),
15282                                      CK_NoOp, VK_LValue);
15283         }
15284 
15285         if (!Result.isInvalid()) {
15286           Result = PerformCopyInitialization(
15287               InitializedEntity::InitializeBlock(Var->getLocation(),
15288                                                  Cap.getCaptureType(), false),
15289               Loc, Result.get());
15290         }
15291 
15292         // Build a full-expression copy expression if initialization
15293         // succeeded and used a non-trivial constructor.  Recover from
15294         // errors by pretending that the copy isn't necessary.
15295         if (!Result.isInvalid() &&
15296             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15297                 ->isTrivial()) {
15298           Result = MaybeCreateExprWithCleanups(Result);
15299           CopyExpr = Result.get();
15300         }
15301       }
15302     }
15303 
15304     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15305                               CopyExpr);
15306     Captures.push_back(NewCap);
15307   }
15308   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15309 
15310   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15311 
15312   // If the block isn't obviously global, i.e. it captures anything at
15313   // all, then we need to do a few things in the surrounding context:
15314   if (Result->getBlockDecl()->hasCaptures()) {
15315     // First, this expression has a new cleanup object.
15316     ExprCleanupObjects.push_back(Result->getBlockDecl());
15317     Cleanup.setExprNeedsCleanups(true);
15318 
15319     // It also gets a branch-protected scope if any of the captured
15320     // variables needs destruction.
15321     for (const auto &CI : Result->getBlockDecl()->captures()) {
15322       const VarDecl *var = CI.getVariable();
15323       if (var->getType().isDestructedType() != QualType::DK_none) {
15324         setFunctionHasBranchProtectedScope();
15325         break;
15326       }
15327     }
15328   }
15329 
15330   if (getCurFunction())
15331     getCurFunction()->addBlock(BD);
15332 
15333   return Result;
15334 }
15335 
15336 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15337                             SourceLocation RPLoc) {
15338   TypeSourceInfo *TInfo;
15339   GetTypeFromParser(Ty, &TInfo);
15340   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15341 }
15342 
15343 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15344                                 Expr *E, TypeSourceInfo *TInfo,
15345                                 SourceLocation RPLoc) {
15346   Expr *OrigExpr = E;
15347   bool IsMS = false;
15348 
15349   // CUDA device code does not support varargs.
15350   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15351     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15352       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15353       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15354         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15355     }
15356   }
15357 
15358   // NVPTX does not support va_arg expression.
15359   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15360       Context.getTargetInfo().getTriple().isNVPTX())
15361     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15362 
15363   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15364   // as Microsoft ABI on an actual Microsoft platform, where
15365   // __builtin_ms_va_list and __builtin_va_list are the same.)
15366   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15367       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15368     QualType MSVaListType = Context.getBuiltinMSVaListType();
15369     if (Context.hasSameType(MSVaListType, E->getType())) {
15370       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15371         return ExprError();
15372       IsMS = true;
15373     }
15374   }
15375 
15376   // Get the va_list type
15377   QualType VaListType = Context.getBuiltinVaListType();
15378   if (!IsMS) {
15379     if (VaListType->isArrayType()) {
15380       // Deal with implicit array decay; for example, on x86-64,
15381       // va_list is an array, but it's supposed to decay to
15382       // a pointer for va_arg.
15383       VaListType = Context.getArrayDecayedType(VaListType);
15384       // Make sure the input expression also decays appropriately.
15385       ExprResult Result = UsualUnaryConversions(E);
15386       if (Result.isInvalid())
15387         return ExprError();
15388       E = Result.get();
15389     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15390       // If va_list is a record type and we are compiling in C++ mode,
15391       // check the argument using reference binding.
15392       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15393           Context, Context.getLValueReferenceType(VaListType), false);
15394       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15395       if (Init.isInvalid())
15396         return ExprError();
15397       E = Init.getAs<Expr>();
15398     } else {
15399       // Otherwise, the va_list argument must be an l-value because
15400       // it is modified by va_arg.
15401       if (!E->isTypeDependent() &&
15402           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15403         return ExprError();
15404     }
15405   }
15406 
15407   if (!IsMS && !E->isTypeDependent() &&
15408       !Context.hasSameType(VaListType, E->getType()))
15409     return ExprError(
15410         Diag(E->getBeginLoc(),
15411              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15412         << OrigExpr->getType() << E->getSourceRange());
15413 
15414   if (!TInfo->getType()->isDependentType()) {
15415     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15416                             diag::err_second_parameter_to_va_arg_incomplete,
15417                             TInfo->getTypeLoc()))
15418       return ExprError();
15419 
15420     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15421                                TInfo->getType(),
15422                                diag::err_second_parameter_to_va_arg_abstract,
15423                                TInfo->getTypeLoc()))
15424       return ExprError();
15425 
15426     if (!TInfo->getType().isPODType(Context)) {
15427       Diag(TInfo->getTypeLoc().getBeginLoc(),
15428            TInfo->getType()->isObjCLifetimeType()
15429              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15430              : diag::warn_second_parameter_to_va_arg_not_pod)
15431         << TInfo->getType()
15432         << TInfo->getTypeLoc().getSourceRange();
15433     }
15434 
15435     // Check for va_arg where arguments of the given type will be promoted
15436     // (i.e. this va_arg is guaranteed to have undefined behavior).
15437     QualType PromoteType;
15438     if (TInfo->getType()->isPromotableIntegerType()) {
15439       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15440       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15441         PromoteType = QualType();
15442     }
15443     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15444       PromoteType = Context.DoubleTy;
15445     if (!PromoteType.isNull())
15446       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15447                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15448                           << TInfo->getType()
15449                           << PromoteType
15450                           << TInfo->getTypeLoc().getSourceRange());
15451   }
15452 
15453   QualType T = TInfo->getType().getNonLValueExprType(Context);
15454   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15455 }
15456 
15457 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15458   // The type of __null will be int or long, depending on the size of
15459   // pointers on the target.
15460   QualType Ty;
15461   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15462   if (pw == Context.getTargetInfo().getIntWidth())
15463     Ty = Context.IntTy;
15464   else if (pw == Context.getTargetInfo().getLongWidth())
15465     Ty = Context.LongTy;
15466   else if (pw == Context.getTargetInfo().getLongLongWidth())
15467     Ty = Context.LongLongTy;
15468   else {
15469     llvm_unreachable("I don't know size of pointer!");
15470   }
15471 
15472   return new (Context) GNUNullExpr(Ty, TokenLoc);
15473 }
15474 
15475 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15476                                     SourceLocation BuiltinLoc,
15477                                     SourceLocation RPLoc) {
15478   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15479 }
15480 
15481 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15482                                     SourceLocation BuiltinLoc,
15483                                     SourceLocation RPLoc,
15484                                     DeclContext *ParentContext) {
15485   return new (Context)
15486       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15487 }
15488 
15489 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15490                                         bool Diagnose) {
15491   if (!getLangOpts().ObjC)
15492     return false;
15493 
15494   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15495   if (!PT)
15496     return false;
15497   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15498 
15499   // Ignore any parens, implicit casts (should only be
15500   // array-to-pointer decays), and not-so-opaque values.  The last is
15501   // important for making this trigger for property assignments.
15502   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15503   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15504     if (OV->getSourceExpr())
15505       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15506 
15507   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15508     if (!PT->isObjCIdType() &&
15509         !(ID && ID->getIdentifier()->isStr("NSString")))
15510       return false;
15511     if (!SL->isAscii())
15512       return false;
15513 
15514     if (Diagnose) {
15515       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15516           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15517       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15518     }
15519     return true;
15520   }
15521 
15522   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15523       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15524       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15525       !SrcExpr->isNullPointerConstant(
15526           getASTContext(), Expr::NPC_NeverValueDependent)) {
15527     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15528       return false;
15529     if (Diagnose) {
15530       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15531           << /*number*/1
15532           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15533       Expr *NumLit =
15534           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15535       if (NumLit)
15536         Exp = NumLit;
15537     }
15538     return true;
15539   }
15540 
15541   return false;
15542 }
15543 
15544 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15545                                               const Expr *SrcExpr) {
15546   if (!DstType->isFunctionPointerType() ||
15547       !SrcExpr->getType()->isFunctionType())
15548     return false;
15549 
15550   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15551   if (!DRE)
15552     return false;
15553 
15554   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15555   if (!FD)
15556     return false;
15557 
15558   return !S.checkAddressOfFunctionIsAvailable(FD,
15559                                               /*Complain=*/true,
15560                                               SrcExpr->getBeginLoc());
15561 }
15562 
15563 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15564                                     SourceLocation Loc,
15565                                     QualType DstType, QualType SrcType,
15566                                     Expr *SrcExpr, AssignmentAction Action,
15567                                     bool *Complained) {
15568   if (Complained)
15569     *Complained = false;
15570 
15571   // Decode the result (notice that AST's are still created for extensions).
15572   bool CheckInferredResultType = false;
15573   bool isInvalid = false;
15574   unsigned DiagKind = 0;
15575   FixItHint Hint;
15576   ConversionFixItGenerator ConvHints;
15577   bool MayHaveConvFixit = false;
15578   bool MayHaveFunctionDiff = false;
15579   const ObjCInterfaceDecl *IFace = nullptr;
15580   const ObjCProtocolDecl *PDecl = nullptr;
15581 
15582   switch (ConvTy) {
15583   case Compatible:
15584       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15585       return false;
15586 
15587   case PointerToInt:
15588     if (getLangOpts().CPlusPlus) {
15589       DiagKind = diag::err_typecheck_convert_pointer_int;
15590       isInvalid = true;
15591     } else {
15592       DiagKind = diag::ext_typecheck_convert_pointer_int;
15593     }
15594     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15595     MayHaveConvFixit = true;
15596     break;
15597   case IntToPointer:
15598     if (getLangOpts().CPlusPlus) {
15599       DiagKind = diag::err_typecheck_convert_int_pointer;
15600       isInvalid = true;
15601     } else {
15602       DiagKind = diag::ext_typecheck_convert_int_pointer;
15603     }
15604     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15605     MayHaveConvFixit = true;
15606     break;
15607   case IncompatibleFunctionPointer:
15608     if (getLangOpts().CPlusPlus) {
15609       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15610       isInvalid = true;
15611     } else {
15612       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15613     }
15614     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15615     MayHaveConvFixit = true;
15616     break;
15617   case IncompatiblePointer:
15618     if (Action == AA_Passing_CFAudited) {
15619       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15620     } else if (getLangOpts().CPlusPlus) {
15621       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15622       isInvalid = true;
15623     } else {
15624       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15625     }
15626     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15627       SrcType->isObjCObjectPointerType();
15628     if (Hint.isNull() && !CheckInferredResultType) {
15629       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15630     }
15631     else if (CheckInferredResultType) {
15632       SrcType = SrcType.getUnqualifiedType();
15633       DstType = DstType.getUnqualifiedType();
15634     }
15635     MayHaveConvFixit = true;
15636     break;
15637   case IncompatiblePointerSign:
15638     if (getLangOpts().CPlusPlus) {
15639       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15640       isInvalid = true;
15641     } else {
15642       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15643     }
15644     break;
15645   case FunctionVoidPointer:
15646     if (getLangOpts().CPlusPlus) {
15647       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15648       isInvalid = true;
15649     } else {
15650       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15651     }
15652     break;
15653   case IncompatiblePointerDiscardsQualifiers: {
15654     // Perform array-to-pointer decay if necessary.
15655     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15656 
15657     isInvalid = true;
15658 
15659     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15660     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15661     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15662       DiagKind = diag::err_typecheck_incompatible_address_space;
15663       break;
15664 
15665     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15666       DiagKind = diag::err_typecheck_incompatible_ownership;
15667       break;
15668     }
15669 
15670     llvm_unreachable("unknown error case for discarding qualifiers!");
15671     // fallthrough
15672   }
15673   case CompatiblePointerDiscardsQualifiers:
15674     // If the qualifiers lost were because we were applying the
15675     // (deprecated) C++ conversion from a string literal to a char*
15676     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15677     // Ideally, this check would be performed in
15678     // checkPointerTypesForAssignment. However, that would require a
15679     // bit of refactoring (so that the second argument is an
15680     // expression, rather than a type), which should be done as part
15681     // of a larger effort to fix checkPointerTypesForAssignment for
15682     // C++ semantics.
15683     if (getLangOpts().CPlusPlus &&
15684         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15685       return false;
15686     if (getLangOpts().CPlusPlus) {
15687       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15688       isInvalid = true;
15689     } else {
15690       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15691     }
15692 
15693     break;
15694   case IncompatibleNestedPointerQualifiers:
15695     if (getLangOpts().CPlusPlus) {
15696       isInvalid = true;
15697       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15698     } else {
15699       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15700     }
15701     break;
15702   case IncompatibleNestedPointerAddressSpaceMismatch:
15703     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15704     isInvalid = true;
15705     break;
15706   case IntToBlockPointer:
15707     DiagKind = diag::err_int_to_block_pointer;
15708     isInvalid = true;
15709     break;
15710   case IncompatibleBlockPointer:
15711     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15712     isInvalid = true;
15713     break;
15714   case IncompatibleObjCQualifiedId: {
15715     if (SrcType->isObjCQualifiedIdType()) {
15716       const ObjCObjectPointerType *srcOPT =
15717                 SrcType->castAs<ObjCObjectPointerType>();
15718       for (auto *srcProto : srcOPT->quals()) {
15719         PDecl = srcProto;
15720         break;
15721       }
15722       if (const ObjCInterfaceType *IFaceT =
15723             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15724         IFace = IFaceT->getDecl();
15725     }
15726     else if (DstType->isObjCQualifiedIdType()) {
15727       const ObjCObjectPointerType *dstOPT =
15728         DstType->castAs<ObjCObjectPointerType>();
15729       for (auto *dstProto : dstOPT->quals()) {
15730         PDecl = dstProto;
15731         break;
15732       }
15733       if (const ObjCInterfaceType *IFaceT =
15734             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15735         IFace = IFaceT->getDecl();
15736     }
15737     if (getLangOpts().CPlusPlus) {
15738       DiagKind = diag::err_incompatible_qualified_id;
15739       isInvalid = true;
15740     } else {
15741       DiagKind = diag::warn_incompatible_qualified_id;
15742     }
15743     break;
15744   }
15745   case IncompatibleVectors:
15746     if (getLangOpts().CPlusPlus) {
15747       DiagKind = diag::err_incompatible_vectors;
15748       isInvalid = true;
15749     } else {
15750       DiagKind = diag::warn_incompatible_vectors;
15751     }
15752     break;
15753   case IncompatibleObjCWeakRef:
15754     DiagKind = diag::err_arc_weak_unavailable_assign;
15755     isInvalid = true;
15756     break;
15757   case Incompatible:
15758     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15759       if (Complained)
15760         *Complained = true;
15761       return true;
15762     }
15763 
15764     DiagKind = diag::err_typecheck_convert_incompatible;
15765     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15766     MayHaveConvFixit = true;
15767     isInvalid = true;
15768     MayHaveFunctionDiff = true;
15769     break;
15770   }
15771 
15772   QualType FirstType, SecondType;
15773   switch (Action) {
15774   case AA_Assigning:
15775   case AA_Initializing:
15776     // The destination type comes first.
15777     FirstType = DstType;
15778     SecondType = SrcType;
15779     break;
15780 
15781   case AA_Returning:
15782   case AA_Passing:
15783   case AA_Passing_CFAudited:
15784   case AA_Converting:
15785   case AA_Sending:
15786   case AA_Casting:
15787     // The source type comes first.
15788     FirstType = SrcType;
15789     SecondType = DstType;
15790     break;
15791   }
15792 
15793   PartialDiagnostic FDiag = PDiag(DiagKind);
15794   if (Action == AA_Passing_CFAudited)
15795     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15796   else
15797     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15798 
15799   // If we can fix the conversion, suggest the FixIts.
15800   assert(ConvHints.isNull() || Hint.isNull());
15801   if (!ConvHints.isNull()) {
15802     for (FixItHint &H : ConvHints.Hints)
15803       FDiag << H;
15804   } else {
15805     FDiag << Hint;
15806   }
15807   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15808 
15809   if (MayHaveFunctionDiff)
15810     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15811 
15812   Diag(Loc, FDiag);
15813   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15814        DiagKind == diag::err_incompatible_qualified_id) &&
15815       PDecl && IFace && !IFace->hasDefinition())
15816     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15817         << IFace << PDecl;
15818 
15819   if (SecondType == Context.OverloadTy)
15820     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15821                               FirstType, /*TakingAddress=*/true);
15822 
15823   if (CheckInferredResultType)
15824     EmitRelatedResultTypeNote(SrcExpr);
15825 
15826   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15827     EmitRelatedResultTypeNoteForReturn(DstType);
15828 
15829   if (Complained)
15830     *Complained = true;
15831   return isInvalid;
15832 }
15833 
15834 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15835                                                  llvm::APSInt *Result) {
15836   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15837   public:
15838     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15839       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15840     }
15841   } Diagnoser;
15842 
15843   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15844 }
15845 
15846 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15847                                                  llvm::APSInt *Result,
15848                                                  unsigned DiagID,
15849                                                  bool AllowFold) {
15850   class IDDiagnoser : public VerifyICEDiagnoser {
15851     unsigned DiagID;
15852 
15853   public:
15854     IDDiagnoser(unsigned DiagID)
15855       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15856 
15857     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15858       S.Diag(Loc, DiagID) << SR;
15859     }
15860   } Diagnoser(DiagID);
15861 
15862   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15863 }
15864 
15865 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15866                                             SourceRange SR) {
15867   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15868 }
15869 
15870 ExprResult
15871 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15872                                       VerifyICEDiagnoser &Diagnoser,
15873                                       bool AllowFold) {
15874   SourceLocation DiagLoc = E->getBeginLoc();
15875 
15876   if (getLangOpts().CPlusPlus11) {
15877     // C++11 [expr.const]p5:
15878     //   If an expression of literal class type is used in a context where an
15879     //   integral constant expression is required, then that class type shall
15880     //   have a single non-explicit conversion function to an integral or
15881     //   unscoped enumeration type
15882     ExprResult Converted;
15883     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15884     public:
15885       CXX11ConvertDiagnoser(bool Silent)
15886           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15887                                 Silent, true) {}
15888 
15889       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15890                                            QualType T) override {
15891         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15892       }
15893 
15894       SemaDiagnosticBuilder diagnoseIncomplete(
15895           Sema &S, SourceLocation Loc, QualType T) override {
15896         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15897       }
15898 
15899       SemaDiagnosticBuilder diagnoseExplicitConv(
15900           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15901         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15902       }
15903 
15904       SemaDiagnosticBuilder noteExplicitConv(
15905           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15906         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15907                  << ConvTy->isEnumeralType() << ConvTy;
15908       }
15909 
15910       SemaDiagnosticBuilder diagnoseAmbiguous(
15911           Sema &S, SourceLocation Loc, QualType T) override {
15912         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15913       }
15914 
15915       SemaDiagnosticBuilder noteAmbiguous(
15916           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15917         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15918                  << ConvTy->isEnumeralType() << ConvTy;
15919       }
15920 
15921       SemaDiagnosticBuilder diagnoseConversion(
15922           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15923         llvm_unreachable("conversion functions are permitted");
15924       }
15925     } ConvertDiagnoser(Diagnoser.Suppress);
15926 
15927     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15928                                                     ConvertDiagnoser);
15929     if (Converted.isInvalid())
15930       return Converted;
15931     E = Converted.get();
15932     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15933       return ExprError();
15934   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15935     // An ICE must be of integral or unscoped enumeration type.
15936     if (!Diagnoser.Suppress)
15937       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15938     return ExprError();
15939   }
15940 
15941   ExprResult RValueExpr = DefaultLvalueConversion(E);
15942   if (RValueExpr.isInvalid())
15943     return ExprError();
15944 
15945   E = RValueExpr.get();
15946 
15947   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15948   // in the non-ICE case.
15949   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15950     if (Result)
15951       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15952     if (!isa<ConstantExpr>(E))
15953       E = ConstantExpr::Create(Context, E);
15954     return E;
15955   }
15956 
15957   Expr::EvalResult EvalResult;
15958   SmallVector<PartialDiagnosticAt, 8> Notes;
15959   EvalResult.Diag = &Notes;
15960 
15961   // Try to evaluate the expression, and produce diagnostics explaining why it's
15962   // not a constant expression as a side-effect.
15963   bool Folded =
15964       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15965       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15966 
15967   if (!isa<ConstantExpr>(E))
15968     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15969 
15970   // In C++11, we can rely on diagnostics being produced for any expression
15971   // which is not a constant expression. If no diagnostics were produced, then
15972   // this is a constant expression.
15973   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15974     if (Result)
15975       *Result = EvalResult.Val.getInt();
15976     return E;
15977   }
15978 
15979   // If our only note is the usual "invalid subexpression" note, just point
15980   // the caret at its location rather than producing an essentially
15981   // redundant note.
15982   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15983         diag::note_invalid_subexpr_in_const_expr) {
15984     DiagLoc = Notes[0].first;
15985     Notes.clear();
15986   }
15987 
15988   if (!Folded || !AllowFold) {
15989     if (!Diagnoser.Suppress) {
15990       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15991       for (const PartialDiagnosticAt &Note : Notes)
15992         Diag(Note.first, Note.second);
15993     }
15994 
15995     return ExprError();
15996   }
15997 
15998   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15999   for (const PartialDiagnosticAt &Note : Notes)
16000     Diag(Note.first, Note.second);
16001 
16002   if (Result)
16003     *Result = EvalResult.Val.getInt();
16004   return E;
16005 }
16006 
16007 namespace {
16008   // Handle the case where we conclude a expression which we speculatively
16009   // considered to be unevaluated is actually evaluated.
16010   class TransformToPE : public TreeTransform<TransformToPE> {
16011     typedef TreeTransform<TransformToPE> BaseTransform;
16012 
16013   public:
16014     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16015 
16016     // Make sure we redo semantic analysis
16017     bool AlwaysRebuild() { return true; }
16018     bool ReplacingOriginal() { return true; }
16019 
16020     // We need to special-case DeclRefExprs referring to FieldDecls which
16021     // are not part of a member pointer formation; normal TreeTransforming
16022     // doesn't catch this case because of the way we represent them in the AST.
16023     // FIXME: This is a bit ugly; is it really the best way to handle this
16024     // case?
16025     //
16026     // Error on DeclRefExprs referring to FieldDecls.
16027     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16028       if (isa<FieldDecl>(E->getDecl()) &&
16029           !SemaRef.isUnevaluatedContext())
16030         return SemaRef.Diag(E->getLocation(),
16031                             diag::err_invalid_non_static_member_use)
16032             << E->getDecl() << E->getSourceRange();
16033 
16034       return BaseTransform::TransformDeclRefExpr(E);
16035     }
16036 
16037     // Exception: filter out member pointer formation
16038     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16039       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16040         return E;
16041 
16042       return BaseTransform::TransformUnaryOperator(E);
16043     }
16044 
16045     // The body of a lambda-expression is in a separate expression evaluation
16046     // context so never needs to be transformed.
16047     // FIXME: Ideally we wouldn't transform the closure type either, and would
16048     // just recreate the capture expressions and lambda expression.
16049     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16050       return SkipLambdaBody(E, Body);
16051     }
16052   };
16053 }
16054 
16055 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16056   assert(isUnevaluatedContext() &&
16057          "Should only transform unevaluated expressions");
16058   ExprEvalContexts.back().Context =
16059       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16060   if (isUnevaluatedContext())
16061     return E;
16062   return TransformToPE(*this).TransformExpr(E);
16063 }
16064 
16065 void
16066 Sema::PushExpressionEvaluationContext(
16067     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16068     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16069   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16070                                 LambdaContextDecl, ExprContext);
16071   Cleanup.reset();
16072   if (!MaybeODRUseExprs.empty())
16073     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16074 }
16075 
16076 void
16077 Sema::PushExpressionEvaluationContext(
16078     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16079     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16080   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16081   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16082 }
16083 
16084 namespace {
16085 
16086 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16087   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16088   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16089     if (E->getOpcode() == UO_Deref)
16090       return CheckPossibleDeref(S, E->getSubExpr());
16091   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16092     return CheckPossibleDeref(S, E->getBase());
16093   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16094     return CheckPossibleDeref(S, E->getBase());
16095   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16096     QualType Inner;
16097     QualType Ty = E->getType();
16098     if (const auto *Ptr = Ty->getAs<PointerType>())
16099       Inner = Ptr->getPointeeType();
16100     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16101       Inner = Arr->getElementType();
16102     else
16103       return nullptr;
16104 
16105     if (Inner->hasAttr(attr::NoDeref))
16106       return E;
16107   }
16108   return nullptr;
16109 }
16110 
16111 } // namespace
16112 
16113 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16114   for (const Expr *E : Rec.PossibleDerefs) {
16115     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16116     if (DeclRef) {
16117       const ValueDecl *Decl = DeclRef->getDecl();
16118       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16119           << Decl->getName() << E->getSourceRange();
16120       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16121     } else {
16122       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16123           << E->getSourceRange();
16124     }
16125   }
16126   Rec.PossibleDerefs.clear();
16127 }
16128 
16129 /// Check whether E, which is either a discarded-value expression or an
16130 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16131 /// and if so, remove it from the list of volatile-qualified assignments that
16132 /// we are going to warn are deprecated.
16133 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16134   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16135     return;
16136 
16137   // Note: ignoring parens here is not justified by the standard rules, but
16138   // ignoring parentheses seems like a more reasonable approach, and this only
16139   // drives a deprecation warning so doesn't affect conformance.
16140   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16141     if (BO->getOpcode() == BO_Assign) {
16142       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16143       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16144                  LHSs.end());
16145     }
16146   }
16147 }
16148 
16149 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16150   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16151       RebuildingImmediateInvocation)
16152     return E;
16153 
16154   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16155   /// It's OK if this fails; we'll also remove this in
16156   /// HandleImmediateInvocations, but catching it here allows us to avoid
16157   /// walking the AST looking for it in simple cases.
16158   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16159     if (auto *DeclRef =
16160             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16161       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16162 
16163   E = MaybeCreateExprWithCleanups(E);
16164 
16165   ConstantExpr *Res = ConstantExpr::Create(
16166       getASTContext(), E.get(),
16167       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16168                                    getASTContext()),
16169       /*IsImmediateInvocation*/ true);
16170   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16171   return Res;
16172 }
16173 
16174 static void EvaluateAndDiagnoseImmediateInvocation(
16175     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16176   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16177   Expr::EvalResult Eval;
16178   Eval.Diag = &Notes;
16179   ConstantExpr *CE = Candidate.getPointer();
16180   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16181                                            SemaRef.getASTContext(), true);
16182   if (!Result || !Notes.empty()) {
16183     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16184     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16185       InnerExpr = FunctionalCast->getSubExpr();
16186     FunctionDecl *FD = nullptr;
16187     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16188       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16189     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16190       FD = Call->getConstructor();
16191     else
16192       llvm_unreachable("unhandled decl kind");
16193     assert(FD->isConsteval());
16194     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16195     for (auto &Note : Notes)
16196       SemaRef.Diag(Note.first, Note.second);
16197     return;
16198   }
16199   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16200 }
16201 
16202 static void RemoveNestedImmediateInvocation(
16203     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16204     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16205   struct ComplexRemove : TreeTransform<ComplexRemove> {
16206     using Base = TreeTransform<ComplexRemove>;
16207     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16208     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16209     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16210         CurrentII;
16211     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16212                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16213                   SmallVector<Sema::ImmediateInvocationCandidate,
16214                               4>::reverse_iterator Current)
16215         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16216     void RemoveImmediateInvocation(ConstantExpr* E) {
16217       auto It = std::find_if(CurrentII, IISet.rend(),
16218                              [E](Sema::ImmediateInvocationCandidate Elem) {
16219                                return Elem.getPointer() == E;
16220                              });
16221       assert(It != IISet.rend() &&
16222              "ConstantExpr marked IsImmediateInvocation should "
16223              "be present");
16224       It->setInt(1); // Mark as deleted
16225     }
16226     ExprResult TransformConstantExpr(ConstantExpr *E) {
16227       if (!E->isImmediateInvocation())
16228         return Base::TransformConstantExpr(E);
16229       RemoveImmediateInvocation(E);
16230       return Base::TransformExpr(E->getSubExpr());
16231     }
16232     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16233     /// we need to remove its DeclRefExpr from the DRSet.
16234     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16235       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16236       return Base::TransformCXXOperatorCallExpr(E);
16237     }
16238     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16239     /// here.
16240     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16241       if (!Init)
16242         return Init;
16243       /// ConstantExpr are the first layer of implicit node to be removed so if
16244       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16245       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16246         if (CE->isImmediateInvocation())
16247           RemoveImmediateInvocation(CE);
16248       return Base::TransformInitializer(Init, NotCopyInit);
16249     }
16250     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16251       DRSet.erase(E);
16252       return E;
16253     }
16254     bool AlwaysRebuild() { return false; }
16255     bool ReplacingOriginal() { return true; }
16256     bool AllowSkippingCXXConstructExpr() {
16257       bool Res = AllowSkippingFirstCXXConstructExpr;
16258       AllowSkippingFirstCXXConstructExpr = true;
16259       return Res;
16260     }
16261     bool AllowSkippingFirstCXXConstructExpr = true;
16262   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16263                 Rec.ImmediateInvocationCandidates, It);
16264 
16265   /// CXXConstructExpr with a single argument are getting skipped by
16266   /// TreeTransform in some situtation because they could be implicit. This
16267   /// can only occur for the top-level CXXConstructExpr because it is used
16268   /// nowhere in the expression being transformed therefore will not be rebuilt.
16269   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16270   /// skipping the first CXXConstructExpr.
16271   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16272     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16273 
16274   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16275   assert(Res.isUsable());
16276   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16277   It->getPointer()->setSubExpr(Res.get());
16278 }
16279 
16280 static void
16281 HandleImmediateInvocations(Sema &SemaRef,
16282                            Sema::ExpressionEvaluationContextRecord &Rec) {
16283   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16284        Rec.ReferenceToConsteval.size() == 0) ||
16285       SemaRef.RebuildingImmediateInvocation)
16286     return;
16287 
16288   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16289   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16290   /// need to remove ReferenceToConsteval in the immediate invocation.
16291   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16292 
16293     /// Prevent sema calls during the tree transform from adding pointers that
16294     /// are already in the sets.
16295     llvm::SaveAndRestore<bool> DisableIITracking(
16296         SemaRef.RebuildingImmediateInvocation, true);
16297 
16298     /// Prevent diagnostic during tree transfrom as they are duplicates
16299     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16300 
16301     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16302          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16303       if (!It->getInt())
16304         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16305   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16306              Rec.ReferenceToConsteval.size()) {
16307     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16308       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16309       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16310       bool VisitDeclRefExpr(DeclRefExpr *E) {
16311         DRSet.erase(E);
16312         return DRSet.size();
16313       }
16314     } Visitor(Rec.ReferenceToConsteval);
16315     Visitor.TraverseStmt(
16316         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16317   }
16318   for (auto CE : Rec.ImmediateInvocationCandidates)
16319     if (!CE.getInt())
16320       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16321   for (auto DR : Rec.ReferenceToConsteval) {
16322     auto *FD = cast<FunctionDecl>(DR->getDecl());
16323     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16324         << FD;
16325     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16326   }
16327 }
16328 
16329 void Sema::PopExpressionEvaluationContext() {
16330   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16331   unsigned NumTypos = Rec.NumTypos;
16332 
16333   if (!Rec.Lambdas.empty()) {
16334     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16335     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16336         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16337       unsigned D;
16338       if (Rec.isUnevaluated()) {
16339         // C++11 [expr.prim.lambda]p2:
16340         //   A lambda-expression shall not appear in an unevaluated operand
16341         //   (Clause 5).
16342         D = diag::err_lambda_unevaluated_operand;
16343       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16344         // C++1y [expr.const]p2:
16345         //   A conditional-expression e is a core constant expression unless the
16346         //   evaluation of e, following the rules of the abstract machine, would
16347         //   evaluate [...] a lambda-expression.
16348         D = diag::err_lambda_in_constant_expression;
16349       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16350         // C++17 [expr.prim.lamda]p2:
16351         // A lambda-expression shall not appear [...] in a template-argument.
16352         D = diag::err_lambda_in_invalid_context;
16353       } else
16354         llvm_unreachable("Couldn't infer lambda error message.");
16355 
16356       for (const auto *L : Rec.Lambdas)
16357         Diag(L->getBeginLoc(), D);
16358     }
16359   }
16360 
16361   WarnOnPendingNoDerefs(Rec);
16362   HandleImmediateInvocations(*this, Rec);
16363 
16364   // Warn on any volatile-qualified simple-assignments that are not discarded-
16365   // value expressions nor unevaluated operands (those cases get removed from
16366   // this list by CheckUnusedVolatileAssignment).
16367   for (auto *BO : Rec.VolatileAssignmentLHSs)
16368     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16369         << BO->getType();
16370 
16371   // When are coming out of an unevaluated context, clear out any
16372   // temporaries that we may have created as part of the evaluation of
16373   // the expression in that context: they aren't relevant because they
16374   // will never be constructed.
16375   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16376     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16377                              ExprCleanupObjects.end());
16378     Cleanup = Rec.ParentCleanup;
16379     CleanupVarDeclMarking();
16380     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16381   // Otherwise, merge the contexts together.
16382   } else {
16383     Cleanup.mergeFrom(Rec.ParentCleanup);
16384     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16385                             Rec.SavedMaybeODRUseExprs.end());
16386   }
16387 
16388   // Pop the current expression evaluation context off the stack.
16389   ExprEvalContexts.pop_back();
16390 
16391   // The global expression evaluation context record is never popped.
16392   ExprEvalContexts.back().NumTypos += NumTypos;
16393 }
16394 
16395 void Sema::DiscardCleanupsInEvaluationContext() {
16396   ExprCleanupObjects.erase(
16397          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16398          ExprCleanupObjects.end());
16399   Cleanup.reset();
16400   MaybeODRUseExprs.clear();
16401 }
16402 
16403 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16404   ExprResult Result = CheckPlaceholderExpr(E);
16405   if (Result.isInvalid())
16406     return ExprError();
16407   E = Result.get();
16408   if (!E->getType()->isVariablyModifiedType())
16409     return E;
16410   return TransformToPotentiallyEvaluated(E);
16411 }
16412 
16413 /// Are we in a context that is potentially constant evaluated per C++20
16414 /// [expr.const]p12?
16415 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16416   /// C++2a [expr.const]p12:
16417   //   An expression or conversion is potentially constant evaluated if it is
16418   switch (SemaRef.ExprEvalContexts.back().Context) {
16419     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16420       // -- a manifestly constant-evaluated expression,
16421     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16422     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16423     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16424       // -- a potentially-evaluated expression,
16425     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16426       // -- an immediate subexpression of a braced-init-list,
16427 
16428       // -- [FIXME] an expression of the form & cast-expression that occurs
16429       //    within a templated entity
16430       // -- a subexpression of one of the above that is not a subexpression of
16431       // a nested unevaluated operand.
16432       return true;
16433 
16434     case Sema::ExpressionEvaluationContext::Unevaluated:
16435     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16436       // Expressions in this context are never evaluated.
16437       return false;
16438   }
16439   llvm_unreachable("Invalid context");
16440 }
16441 
16442 /// Return true if this function has a calling convention that requires mangling
16443 /// in the size of the parameter pack.
16444 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16445   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16446   // we don't need parameter type sizes.
16447   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16448   if (!TT.isOSWindows() || !TT.isX86())
16449     return false;
16450 
16451   // If this is C++ and this isn't an extern "C" function, parameters do not
16452   // need to be complete. In this case, C++ mangling will apply, which doesn't
16453   // use the size of the parameters.
16454   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16455     return false;
16456 
16457   // Stdcall, fastcall, and vectorcall need this special treatment.
16458   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16459   switch (CC) {
16460   case CC_X86StdCall:
16461   case CC_X86FastCall:
16462   case CC_X86VectorCall:
16463     return true;
16464   default:
16465     break;
16466   }
16467   return false;
16468 }
16469 
16470 /// Require that all of the parameter types of function be complete. Normally,
16471 /// parameter types are only required to be complete when a function is called
16472 /// or defined, but to mangle functions with certain calling conventions, the
16473 /// mangler needs to know the size of the parameter list. In this situation,
16474 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16475 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16476 /// result in a linker error. Clang doesn't implement this behavior, and instead
16477 /// attempts to error at compile time.
16478 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16479                                                   SourceLocation Loc) {
16480   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16481     FunctionDecl *FD;
16482     ParmVarDecl *Param;
16483 
16484   public:
16485     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16486         : FD(FD), Param(Param) {}
16487 
16488     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16489       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16490       StringRef CCName;
16491       switch (CC) {
16492       case CC_X86StdCall:
16493         CCName = "stdcall";
16494         break;
16495       case CC_X86FastCall:
16496         CCName = "fastcall";
16497         break;
16498       case CC_X86VectorCall:
16499         CCName = "vectorcall";
16500         break;
16501       default:
16502         llvm_unreachable("CC does not need mangling");
16503       }
16504 
16505       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16506           << Param->getDeclName() << FD->getDeclName() << CCName;
16507     }
16508   };
16509 
16510   for (ParmVarDecl *Param : FD->parameters()) {
16511     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16512     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16513   }
16514 }
16515 
16516 namespace {
16517 enum class OdrUseContext {
16518   /// Declarations in this context are not odr-used.
16519   None,
16520   /// Declarations in this context are formally odr-used, but this is a
16521   /// dependent context.
16522   Dependent,
16523   /// Declarations in this context are odr-used but not actually used (yet).
16524   FormallyOdrUsed,
16525   /// Declarations in this context are used.
16526   Used
16527 };
16528 }
16529 
16530 /// Are we within a context in which references to resolved functions or to
16531 /// variables result in odr-use?
16532 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16533   OdrUseContext Result;
16534 
16535   switch (SemaRef.ExprEvalContexts.back().Context) {
16536     case Sema::ExpressionEvaluationContext::Unevaluated:
16537     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16538     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16539       return OdrUseContext::None;
16540 
16541     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16542     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16543       Result = OdrUseContext::Used;
16544       break;
16545 
16546     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16547       Result = OdrUseContext::FormallyOdrUsed;
16548       break;
16549 
16550     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16551       // A default argument formally results in odr-use, but doesn't actually
16552       // result in a use in any real sense until it itself is used.
16553       Result = OdrUseContext::FormallyOdrUsed;
16554       break;
16555   }
16556 
16557   if (SemaRef.CurContext->isDependentContext())
16558     return OdrUseContext::Dependent;
16559 
16560   return Result;
16561 }
16562 
16563 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16564   return Func->isConstexpr() &&
16565          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16566 }
16567 
16568 /// Mark a function referenced, and check whether it is odr-used
16569 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16570 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16571                                   bool MightBeOdrUse) {
16572   assert(Func && "No function?");
16573 
16574   Func->setReferenced();
16575 
16576   // Recursive functions aren't really used until they're used from some other
16577   // context.
16578   bool IsRecursiveCall = CurContext == Func;
16579 
16580   // C++11 [basic.def.odr]p3:
16581   //   A function whose name appears as a potentially-evaluated expression is
16582   //   odr-used if it is the unique lookup result or the selected member of a
16583   //   set of overloaded functions [...].
16584   //
16585   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16586   // can just check that here.
16587   OdrUseContext OdrUse =
16588       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16589   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16590     OdrUse = OdrUseContext::FormallyOdrUsed;
16591 
16592   // Trivial default constructors and destructors are never actually used.
16593   // FIXME: What about other special members?
16594   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16595       OdrUse == OdrUseContext::Used) {
16596     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16597       if (Constructor->isDefaultConstructor())
16598         OdrUse = OdrUseContext::FormallyOdrUsed;
16599     if (isa<CXXDestructorDecl>(Func))
16600       OdrUse = OdrUseContext::FormallyOdrUsed;
16601   }
16602 
16603   // C++20 [expr.const]p12:
16604   //   A function [...] is needed for constant evaluation if it is [...] a
16605   //   constexpr function that is named by an expression that is potentially
16606   //   constant evaluated
16607   bool NeededForConstantEvaluation =
16608       isPotentiallyConstantEvaluatedContext(*this) &&
16609       isImplicitlyDefinableConstexprFunction(Func);
16610 
16611   // Determine whether we require a function definition to exist, per
16612   // C++11 [temp.inst]p3:
16613   //   Unless a function template specialization has been explicitly
16614   //   instantiated or explicitly specialized, the function template
16615   //   specialization is implicitly instantiated when the specialization is
16616   //   referenced in a context that requires a function definition to exist.
16617   // C++20 [temp.inst]p7:
16618   //   The existence of a definition of a [...] function is considered to
16619   //   affect the semantics of the program if the [...] function is needed for
16620   //   constant evaluation by an expression
16621   // C++20 [basic.def.odr]p10:
16622   //   Every program shall contain exactly one definition of every non-inline
16623   //   function or variable that is odr-used in that program outside of a
16624   //   discarded statement
16625   // C++20 [special]p1:
16626   //   The implementation will implicitly define [defaulted special members]
16627   //   if they are odr-used or needed for constant evaluation.
16628   //
16629   // Note that we skip the implicit instantiation of templates that are only
16630   // used in unused default arguments or by recursive calls to themselves.
16631   // This is formally non-conforming, but seems reasonable in practice.
16632   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16633                                              NeededForConstantEvaluation);
16634 
16635   // C++14 [temp.expl.spec]p6:
16636   //   If a template [...] is explicitly specialized then that specialization
16637   //   shall be declared before the first use of that specialization that would
16638   //   cause an implicit instantiation to take place, in every translation unit
16639   //   in which such a use occurs
16640   if (NeedDefinition &&
16641       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16642        Func->getMemberSpecializationInfo()))
16643     checkSpecializationVisibility(Loc, Func);
16644 
16645   if (getLangOpts().CUDA)
16646     CheckCUDACall(Loc, Func);
16647 
16648   if (getLangOpts().SYCLIsDevice)
16649     checkSYCLDeviceFunction(Loc, Func);
16650 
16651   // If we need a definition, try to create one.
16652   if (NeedDefinition && !Func->getBody()) {
16653     runWithSufficientStackSpace(Loc, [&] {
16654       if (CXXConstructorDecl *Constructor =
16655               dyn_cast<CXXConstructorDecl>(Func)) {
16656         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16657         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16658           if (Constructor->isDefaultConstructor()) {
16659             if (Constructor->isTrivial() &&
16660                 !Constructor->hasAttr<DLLExportAttr>())
16661               return;
16662             DefineImplicitDefaultConstructor(Loc, Constructor);
16663           } else if (Constructor->isCopyConstructor()) {
16664             DefineImplicitCopyConstructor(Loc, Constructor);
16665           } else if (Constructor->isMoveConstructor()) {
16666             DefineImplicitMoveConstructor(Loc, Constructor);
16667           }
16668         } else if (Constructor->getInheritedConstructor()) {
16669           DefineInheritingConstructor(Loc, Constructor);
16670         }
16671       } else if (CXXDestructorDecl *Destructor =
16672                      dyn_cast<CXXDestructorDecl>(Func)) {
16673         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16674         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16675           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16676             return;
16677           DefineImplicitDestructor(Loc, Destructor);
16678         }
16679         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16680           MarkVTableUsed(Loc, Destructor->getParent());
16681       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16682         if (MethodDecl->isOverloadedOperator() &&
16683             MethodDecl->getOverloadedOperator() == OO_Equal) {
16684           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16685           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16686             if (MethodDecl->isCopyAssignmentOperator())
16687               DefineImplicitCopyAssignment(Loc, MethodDecl);
16688             else if (MethodDecl->isMoveAssignmentOperator())
16689               DefineImplicitMoveAssignment(Loc, MethodDecl);
16690           }
16691         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16692                    MethodDecl->getParent()->isLambda()) {
16693           CXXConversionDecl *Conversion =
16694               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16695           if (Conversion->isLambdaToBlockPointerConversion())
16696             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16697           else
16698             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16699         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16700           MarkVTableUsed(Loc, MethodDecl->getParent());
16701       }
16702 
16703       if (Func->isDefaulted() && !Func->isDeleted()) {
16704         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16705         if (DCK != DefaultedComparisonKind::None)
16706           DefineDefaultedComparison(Loc, Func, DCK);
16707       }
16708 
16709       // Implicit instantiation of function templates and member functions of
16710       // class templates.
16711       if (Func->isImplicitlyInstantiable()) {
16712         TemplateSpecializationKind TSK =
16713             Func->getTemplateSpecializationKindForInstantiation();
16714         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16715         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16716         if (FirstInstantiation) {
16717           PointOfInstantiation = Loc;
16718           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16719         } else if (TSK != TSK_ImplicitInstantiation) {
16720           // Use the point of use as the point of instantiation, instead of the
16721           // point of explicit instantiation (which we track as the actual point
16722           // of instantiation). This gives better backtraces in diagnostics.
16723           PointOfInstantiation = Loc;
16724         }
16725 
16726         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16727             Func->isConstexpr()) {
16728           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16729               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16730               CodeSynthesisContexts.size())
16731             PendingLocalImplicitInstantiations.push_back(
16732                 std::make_pair(Func, PointOfInstantiation));
16733           else if (Func->isConstexpr())
16734             // Do not defer instantiations of constexpr functions, to avoid the
16735             // expression evaluator needing to call back into Sema if it sees a
16736             // call to such a function.
16737             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16738           else {
16739             Func->setInstantiationIsPending(true);
16740             PendingInstantiations.push_back(
16741                 std::make_pair(Func, PointOfInstantiation));
16742             // Notify the consumer that a function was implicitly instantiated.
16743             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16744           }
16745         }
16746       } else {
16747         // Walk redefinitions, as some of them may be instantiable.
16748         for (auto i : Func->redecls()) {
16749           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16750             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16751         }
16752       }
16753     });
16754   }
16755 
16756   // C++14 [except.spec]p17:
16757   //   An exception-specification is considered to be needed when:
16758   //   - the function is odr-used or, if it appears in an unevaluated operand,
16759   //     would be odr-used if the expression were potentially-evaluated;
16760   //
16761   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16762   // function is a pure virtual function we're calling, and in that case the
16763   // function was selected by overload resolution and we need to resolve its
16764   // exception specification for a different reason.
16765   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16766   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16767     ResolveExceptionSpec(Loc, FPT);
16768 
16769   // If this is the first "real" use, act on that.
16770   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16771     // Keep track of used but undefined functions.
16772     if (!Func->isDefined()) {
16773       if (mightHaveNonExternalLinkage(Func))
16774         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16775       else if (Func->getMostRecentDecl()->isInlined() &&
16776                !LangOpts.GNUInline &&
16777                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16778         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16779       else if (isExternalWithNoLinkageType(Func))
16780         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16781     }
16782 
16783     // Some x86 Windows calling conventions mangle the size of the parameter
16784     // pack into the name. Computing the size of the parameters requires the
16785     // parameter types to be complete. Check that now.
16786     if (funcHasParameterSizeMangling(*this, Func))
16787       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16788 
16789     // In the MS C++ ABI, the compiler emits destructor variants where they are
16790     // used. If the destructor is used here but defined elsewhere, mark the
16791     // virtual base destructors referenced. If those virtual base destructors
16792     // are inline, this will ensure they are defined when emitting the complete
16793     // destructor variant. This checking may be redundant if the destructor is
16794     // provided later in this TU.
16795     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16796       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16797         CXXRecordDecl *Parent = Dtor->getParent();
16798         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16799           CheckCompleteDestructorVariant(Loc, Dtor);
16800       }
16801     }
16802 
16803     Func->markUsed(Context);
16804   }
16805 }
16806 
16807 /// Directly mark a variable odr-used. Given a choice, prefer to use
16808 /// MarkVariableReferenced since it does additional checks and then
16809 /// calls MarkVarDeclODRUsed.
16810 /// If the variable must be captured:
16811 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16812 ///  - else capture it in the DeclContext that maps to the
16813 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16814 static void
16815 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16816                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16817   // Keep track of used but undefined variables.
16818   // FIXME: We shouldn't suppress this warning for static data members.
16819   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16820       (!Var->isExternallyVisible() || Var->isInline() ||
16821        SemaRef.isExternalWithNoLinkageType(Var)) &&
16822       !(Var->isStaticDataMember() && Var->hasInit())) {
16823     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16824     if (old.isInvalid())
16825       old = Loc;
16826   }
16827   QualType CaptureType, DeclRefType;
16828   if (SemaRef.LangOpts.OpenMP)
16829     SemaRef.tryCaptureOpenMPLambdas(Var);
16830   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16831     /*EllipsisLoc*/ SourceLocation(),
16832     /*BuildAndDiagnose*/ true,
16833     CaptureType, DeclRefType,
16834     FunctionScopeIndexToStopAt);
16835 
16836   Var->markUsed(SemaRef.Context);
16837 }
16838 
16839 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16840                                              SourceLocation Loc,
16841                                              unsigned CapturingScopeIndex) {
16842   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16843 }
16844 
16845 static void
16846 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16847                                    ValueDecl *var, DeclContext *DC) {
16848   DeclContext *VarDC = var->getDeclContext();
16849 
16850   //  If the parameter still belongs to the translation unit, then
16851   //  we're actually just using one parameter in the declaration of
16852   //  the next.
16853   if (isa<ParmVarDecl>(var) &&
16854       isa<TranslationUnitDecl>(VarDC))
16855     return;
16856 
16857   // For C code, don't diagnose about capture if we're not actually in code
16858   // right now; it's impossible to write a non-constant expression outside of
16859   // function context, so we'll get other (more useful) diagnostics later.
16860   //
16861   // For C++, things get a bit more nasty... it would be nice to suppress this
16862   // diagnostic for certain cases like using a local variable in an array bound
16863   // for a member of a local class, but the correct predicate is not obvious.
16864   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16865     return;
16866 
16867   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16868   unsigned ContextKind = 3; // unknown
16869   if (isa<CXXMethodDecl>(VarDC) &&
16870       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16871     ContextKind = 2;
16872   } else if (isa<FunctionDecl>(VarDC)) {
16873     ContextKind = 0;
16874   } else if (isa<BlockDecl>(VarDC)) {
16875     ContextKind = 1;
16876   }
16877 
16878   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16879     << var << ValueKind << ContextKind << VarDC;
16880   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16881       << var;
16882 
16883   // FIXME: Add additional diagnostic info about class etc. which prevents
16884   // capture.
16885 }
16886 
16887 
16888 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16889                                       bool &SubCapturesAreNested,
16890                                       QualType &CaptureType,
16891                                       QualType &DeclRefType) {
16892    // Check whether we've already captured it.
16893   if (CSI->CaptureMap.count(Var)) {
16894     // If we found a capture, any subcaptures are nested.
16895     SubCapturesAreNested = true;
16896 
16897     // Retrieve the capture type for this variable.
16898     CaptureType = CSI->getCapture(Var).getCaptureType();
16899 
16900     // Compute the type of an expression that refers to this variable.
16901     DeclRefType = CaptureType.getNonReferenceType();
16902 
16903     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16904     // are mutable in the sense that user can change their value - they are
16905     // private instances of the captured declarations.
16906     const Capture &Cap = CSI->getCapture(Var);
16907     if (Cap.isCopyCapture() &&
16908         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16909         !(isa<CapturedRegionScopeInfo>(CSI) &&
16910           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16911       DeclRefType.addConst();
16912     return true;
16913   }
16914   return false;
16915 }
16916 
16917 // Only block literals, captured statements, and lambda expressions can
16918 // capture; other scopes don't work.
16919 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16920                                  SourceLocation Loc,
16921                                  const bool Diagnose, Sema &S) {
16922   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16923     return getLambdaAwareParentOfDeclContext(DC);
16924   else if (Var->hasLocalStorage()) {
16925     if (Diagnose)
16926        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16927   }
16928   return nullptr;
16929 }
16930 
16931 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16932 // certain types of variables (unnamed, variably modified types etc.)
16933 // so check for eligibility.
16934 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16935                                  SourceLocation Loc,
16936                                  const bool Diagnose, Sema &S) {
16937 
16938   bool IsBlock = isa<BlockScopeInfo>(CSI);
16939   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16940 
16941   // Lambdas are not allowed to capture unnamed variables
16942   // (e.g. anonymous unions).
16943   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16944   // assuming that's the intent.
16945   if (IsLambda && !Var->getDeclName()) {
16946     if (Diagnose) {
16947       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16948       S.Diag(Var->getLocation(), diag::note_declared_at);
16949     }
16950     return false;
16951   }
16952 
16953   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16954   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16955     if (Diagnose) {
16956       S.Diag(Loc, diag::err_ref_vm_type);
16957       S.Diag(Var->getLocation(), diag::note_previous_decl)
16958         << Var->getDeclName();
16959     }
16960     return false;
16961   }
16962   // Prohibit structs with flexible array members too.
16963   // We cannot capture what is in the tail end of the struct.
16964   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16965     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16966       if (Diagnose) {
16967         if (IsBlock)
16968           S.Diag(Loc, diag::err_ref_flexarray_type);
16969         else
16970           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16971             << Var->getDeclName();
16972         S.Diag(Var->getLocation(), diag::note_previous_decl)
16973           << Var->getDeclName();
16974       }
16975       return false;
16976     }
16977   }
16978   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16979   // Lambdas and captured statements are not allowed to capture __block
16980   // variables; they don't support the expected semantics.
16981   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16982     if (Diagnose) {
16983       S.Diag(Loc, diag::err_capture_block_variable)
16984         << Var->getDeclName() << !IsLambda;
16985       S.Diag(Var->getLocation(), diag::note_previous_decl)
16986         << Var->getDeclName();
16987     }
16988     return false;
16989   }
16990   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16991   if (S.getLangOpts().OpenCL && IsBlock &&
16992       Var->getType()->isBlockPointerType()) {
16993     if (Diagnose)
16994       S.Diag(Loc, diag::err_opencl_block_ref_block);
16995     return false;
16996   }
16997 
16998   return true;
16999 }
17000 
17001 // Returns true if the capture by block was successful.
17002 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17003                                  SourceLocation Loc,
17004                                  const bool BuildAndDiagnose,
17005                                  QualType &CaptureType,
17006                                  QualType &DeclRefType,
17007                                  const bool Nested,
17008                                  Sema &S, bool Invalid) {
17009   bool ByRef = false;
17010 
17011   // Blocks are not allowed to capture arrays, excepting OpenCL.
17012   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17013   // (decayed to pointers).
17014   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17015     if (BuildAndDiagnose) {
17016       S.Diag(Loc, diag::err_ref_array_type);
17017       S.Diag(Var->getLocation(), diag::note_previous_decl)
17018       << Var->getDeclName();
17019       Invalid = true;
17020     } else {
17021       return false;
17022     }
17023   }
17024 
17025   // Forbid the block-capture of autoreleasing variables.
17026   if (!Invalid &&
17027       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17028     if (BuildAndDiagnose) {
17029       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17030         << /*block*/ 0;
17031       S.Diag(Var->getLocation(), diag::note_previous_decl)
17032         << Var->getDeclName();
17033       Invalid = true;
17034     } else {
17035       return false;
17036     }
17037   }
17038 
17039   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17040   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17041     QualType PointeeTy = PT->getPointeeType();
17042 
17043     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17044         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17045         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17046       if (BuildAndDiagnose) {
17047         SourceLocation VarLoc = Var->getLocation();
17048         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17049         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17050       }
17051     }
17052   }
17053 
17054   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17055   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17056       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17057     // Block capture by reference does not change the capture or
17058     // declaration reference types.
17059     ByRef = true;
17060   } else {
17061     // Block capture by copy introduces 'const'.
17062     CaptureType = CaptureType.getNonReferenceType().withConst();
17063     DeclRefType = CaptureType;
17064   }
17065 
17066   // Actually capture the variable.
17067   if (BuildAndDiagnose)
17068     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17069                     CaptureType, Invalid);
17070 
17071   return !Invalid;
17072 }
17073 
17074 
17075 /// Capture the given variable in the captured region.
17076 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17077                                     VarDecl *Var,
17078                                     SourceLocation Loc,
17079                                     const bool BuildAndDiagnose,
17080                                     QualType &CaptureType,
17081                                     QualType &DeclRefType,
17082                                     const bool RefersToCapturedVariable,
17083                                     Sema &S, bool Invalid) {
17084   // By default, capture variables by reference.
17085   bool ByRef = true;
17086   // Using an LValue reference type is consistent with Lambdas (see below).
17087   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17088     if (S.isOpenMPCapturedDecl(Var)) {
17089       bool HasConst = DeclRefType.isConstQualified();
17090       DeclRefType = DeclRefType.getUnqualifiedType();
17091       // Don't lose diagnostics about assignments to const.
17092       if (HasConst)
17093         DeclRefType.addConst();
17094     }
17095     // Do not capture firstprivates in tasks.
17096     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17097         OMPC_unknown)
17098       return true;
17099     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17100                                     RSI->OpenMPCaptureLevel);
17101   }
17102 
17103   if (ByRef)
17104     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17105   else
17106     CaptureType = DeclRefType;
17107 
17108   // Actually capture the variable.
17109   if (BuildAndDiagnose)
17110     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17111                     Loc, SourceLocation(), CaptureType, Invalid);
17112 
17113   return !Invalid;
17114 }
17115 
17116 /// Capture the given variable in the lambda.
17117 static bool captureInLambda(LambdaScopeInfo *LSI,
17118                             VarDecl *Var,
17119                             SourceLocation Loc,
17120                             const bool BuildAndDiagnose,
17121                             QualType &CaptureType,
17122                             QualType &DeclRefType,
17123                             const bool RefersToCapturedVariable,
17124                             const Sema::TryCaptureKind Kind,
17125                             SourceLocation EllipsisLoc,
17126                             const bool IsTopScope,
17127                             Sema &S, bool Invalid) {
17128   // Determine whether we are capturing by reference or by value.
17129   bool ByRef = false;
17130   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17131     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17132   } else {
17133     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17134   }
17135 
17136   // Compute the type of the field that will capture this variable.
17137   if (ByRef) {
17138     // C++11 [expr.prim.lambda]p15:
17139     //   An entity is captured by reference if it is implicitly or
17140     //   explicitly captured but not captured by copy. It is
17141     //   unspecified whether additional unnamed non-static data
17142     //   members are declared in the closure type for entities
17143     //   captured by reference.
17144     //
17145     // FIXME: It is not clear whether we want to build an lvalue reference
17146     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17147     // to do the former, while EDG does the latter. Core issue 1249 will
17148     // clarify, but for now we follow GCC because it's a more permissive and
17149     // easily defensible position.
17150     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17151   } else {
17152     // C++11 [expr.prim.lambda]p14:
17153     //   For each entity captured by copy, an unnamed non-static
17154     //   data member is declared in the closure type. The
17155     //   declaration order of these members is unspecified. The type
17156     //   of such a data member is the type of the corresponding
17157     //   captured entity if the entity is not a reference to an
17158     //   object, or the referenced type otherwise. [Note: If the
17159     //   captured entity is a reference to a function, the
17160     //   corresponding data member is also a reference to a
17161     //   function. - end note ]
17162     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17163       if (!RefType->getPointeeType()->isFunctionType())
17164         CaptureType = RefType->getPointeeType();
17165     }
17166 
17167     // Forbid the lambda copy-capture of autoreleasing variables.
17168     if (!Invalid &&
17169         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17170       if (BuildAndDiagnose) {
17171         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17172         S.Diag(Var->getLocation(), diag::note_previous_decl)
17173           << Var->getDeclName();
17174         Invalid = true;
17175       } else {
17176         return false;
17177       }
17178     }
17179 
17180     // Make sure that by-copy captures are of a complete and non-abstract type.
17181     if (!Invalid && BuildAndDiagnose) {
17182       if (!CaptureType->isDependentType() &&
17183           S.RequireCompleteSizedType(
17184               Loc, CaptureType,
17185               diag::err_capture_of_incomplete_or_sizeless_type,
17186               Var->getDeclName()))
17187         Invalid = true;
17188       else if (S.RequireNonAbstractType(Loc, CaptureType,
17189                                         diag::err_capture_of_abstract_type))
17190         Invalid = true;
17191     }
17192   }
17193 
17194   // Compute the type of a reference to this captured variable.
17195   if (ByRef)
17196     DeclRefType = CaptureType.getNonReferenceType();
17197   else {
17198     // C++ [expr.prim.lambda]p5:
17199     //   The closure type for a lambda-expression has a public inline
17200     //   function call operator [...]. This function call operator is
17201     //   declared const (9.3.1) if and only if the lambda-expression's
17202     //   parameter-declaration-clause is not followed by mutable.
17203     DeclRefType = CaptureType.getNonReferenceType();
17204     if (!LSI->Mutable && !CaptureType->isReferenceType())
17205       DeclRefType.addConst();
17206   }
17207 
17208   // Add the capture.
17209   if (BuildAndDiagnose)
17210     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17211                     Loc, EllipsisLoc, CaptureType, Invalid);
17212 
17213   return !Invalid;
17214 }
17215 
17216 bool Sema::tryCaptureVariable(
17217     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17218     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17219     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17220   // An init-capture is notionally from the context surrounding its
17221   // declaration, but its parent DC is the lambda class.
17222   DeclContext *VarDC = Var->getDeclContext();
17223   if (Var->isInitCapture())
17224     VarDC = VarDC->getParent();
17225 
17226   DeclContext *DC = CurContext;
17227   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17228       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17229   // We need to sync up the Declaration Context with the
17230   // FunctionScopeIndexToStopAt
17231   if (FunctionScopeIndexToStopAt) {
17232     unsigned FSIndex = FunctionScopes.size() - 1;
17233     while (FSIndex != MaxFunctionScopesIndex) {
17234       DC = getLambdaAwareParentOfDeclContext(DC);
17235       --FSIndex;
17236     }
17237   }
17238 
17239 
17240   // If the variable is declared in the current context, there is no need to
17241   // capture it.
17242   if (VarDC == DC) return true;
17243 
17244   // Capture global variables if it is required to use private copy of this
17245   // variable.
17246   bool IsGlobal = !Var->hasLocalStorage();
17247   if (IsGlobal &&
17248       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17249                                                 MaxFunctionScopesIndex)))
17250     return true;
17251   Var = Var->getCanonicalDecl();
17252 
17253   // Walk up the stack to determine whether we can capture the variable,
17254   // performing the "simple" checks that don't depend on type. We stop when
17255   // we've either hit the declared scope of the variable or find an existing
17256   // capture of that variable.  We start from the innermost capturing-entity
17257   // (the DC) and ensure that all intervening capturing-entities
17258   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17259   // declcontext can either capture the variable or have already captured
17260   // the variable.
17261   CaptureType = Var->getType();
17262   DeclRefType = CaptureType.getNonReferenceType();
17263   bool Nested = false;
17264   bool Explicit = (Kind != TryCapture_Implicit);
17265   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17266   do {
17267     // Only block literals, captured statements, and lambda expressions can
17268     // capture; other scopes don't work.
17269     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17270                                                               ExprLoc,
17271                                                               BuildAndDiagnose,
17272                                                               *this);
17273     // We need to check for the parent *first* because, if we *have*
17274     // private-captured a global variable, we need to recursively capture it in
17275     // intermediate blocks, lambdas, etc.
17276     if (!ParentDC) {
17277       if (IsGlobal) {
17278         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17279         break;
17280       }
17281       return true;
17282     }
17283 
17284     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17285     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17286 
17287 
17288     // Check whether we've already captured it.
17289     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17290                                              DeclRefType)) {
17291       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17292       break;
17293     }
17294     // If we are instantiating a generic lambda call operator body,
17295     // we do not want to capture new variables.  What was captured
17296     // during either a lambdas transformation or initial parsing
17297     // should be used.
17298     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17299       if (BuildAndDiagnose) {
17300         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17301         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17302           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17303           Diag(Var->getLocation(), diag::note_previous_decl)
17304              << Var->getDeclName();
17305           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17306         } else
17307           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17308       }
17309       return true;
17310     }
17311 
17312     // Try to capture variable-length arrays types.
17313     if (Var->getType()->isVariablyModifiedType()) {
17314       // We're going to walk down into the type and look for VLA
17315       // expressions.
17316       QualType QTy = Var->getType();
17317       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17318         QTy = PVD->getOriginalType();
17319       captureVariablyModifiedType(Context, QTy, CSI);
17320     }
17321 
17322     if (getLangOpts().OpenMP) {
17323       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17324         // OpenMP private variables should not be captured in outer scope, so
17325         // just break here. Similarly, global variables that are captured in a
17326         // target region should not be captured outside the scope of the region.
17327         if (RSI->CapRegionKind == CR_OpenMP) {
17328           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17329               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17330           // If the variable is private (i.e. not captured) and has variably
17331           // modified type, we still need to capture the type for correct
17332           // codegen in all regions, associated with the construct. Currently,
17333           // it is captured in the innermost captured region only.
17334           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17335               Var->getType()->isVariablyModifiedType()) {
17336             QualType QTy = Var->getType();
17337             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17338               QTy = PVD->getOriginalType();
17339             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17340                  I < E; ++I) {
17341               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17342                   FunctionScopes[FunctionScopesIndex - I]);
17343               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17344                      "Wrong number of captured regions associated with the "
17345                      "OpenMP construct.");
17346               captureVariablyModifiedType(Context, QTy, OuterRSI);
17347             }
17348           }
17349           bool IsTargetCap =
17350               IsOpenMPPrivateDecl != OMPC_private &&
17351               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17352                                          RSI->OpenMPCaptureLevel);
17353           // Do not capture global if it is not privatized in outer regions.
17354           bool IsGlobalCap =
17355               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17356                                                      RSI->OpenMPCaptureLevel);
17357 
17358           // When we detect target captures we are looking from inside the
17359           // target region, therefore we need to propagate the capture from the
17360           // enclosing region. Therefore, the capture is not initially nested.
17361           if (IsTargetCap)
17362             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17363 
17364           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17365               (IsGlobal && !IsGlobalCap)) {
17366             Nested = !IsTargetCap;
17367             DeclRefType = DeclRefType.getUnqualifiedType();
17368             CaptureType = Context.getLValueReferenceType(DeclRefType);
17369             break;
17370           }
17371         }
17372       }
17373     }
17374     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17375       // No capture-default, and this is not an explicit capture
17376       // so cannot capture this variable.
17377       if (BuildAndDiagnose) {
17378         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17379         Diag(Var->getLocation(), diag::note_previous_decl)
17380           << Var->getDeclName();
17381         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17382           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17383                diag::note_lambda_decl);
17384         // FIXME: If we error out because an outer lambda can not implicitly
17385         // capture a variable that an inner lambda explicitly captures, we
17386         // should have the inner lambda do the explicit capture - because
17387         // it makes for cleaner diagnostics later.  This would purely be done
17388         // so that the diagnostic does not misleadingly claim that a variable
17389         // can not be captured by a lambda implicitly even though it is captured
17390         // explicitly.  Suggestion:
17391         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17392         //    at the function head
17393         //  - cache the StartingDeclContext - this must be a lambda
17394         //  - captureInLambda in the innermost lambda the variable.
17395       }
17396       return true;
17397     }
17398 
17399     FunctionScopesIndex--;
17400     DC = ParentDC;
17401     Explicit = false;
17402   } while (!VarDC->Equals(DC));
17403 
17404   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17405   // computing the type of the capture at each step, checking type-specific
17406   // requirements, and adding captures if requested.
17407   // If the variable had already been captured previously, we start capturing
17408   // at the lambda nested within that one.
17409   bool Invalid = false;
17410   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17411        ++I) {
17412     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17413 
17414     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17415     // certain types of variables (unnamed, variably modified types etc.)
17416     // so check for eligibility.
17417     if (!Invalid)
17418       Invalid =
17419           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17420 
17421     // After encountering an error, if we're actually supposed to capture, keep
17422     // capturing in nested contexts to suppress any follow-on diagnostics.
17423     if (Invalid && !BuildAndDiagnose)
17424       return true;
17425 
17426     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17427       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17428                                DeclRefType, Nested, *this, Invalid);
17429       Nested = true;
17430     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17431       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17432                                          CaptureType, DeclRefType, Nested,
17433                                          *this, Invalid);
17434       Nested = true;
17435     } else {
17436       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17437       Invalid =
17438           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17439                            DeclRefType, Nested, Kind, EllipsisLoc,
17440                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17441       Nested = true;
17442     }
17443 
17444     if (Invalid && !BuildAndDiagnose)
17445       return true;
17446   }
17447   return Invalid;
17448 }
17449 
17450 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17451                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17452   QualType CaptureType;
17453   QualType DeclRefType;
17454   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17455                             /*BuildAndDiagnose=*/true, CaptureType,
17456                             DeclRefType, nullptr);
17457 }
17458 
17459 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17460   QualType CaptureType;
17461   QualType DeclRefType;
17462   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17463                              /*BuildAndDiagnose=*/false, CaptureType,
17464                              DeclRefType, nullptr);
17465 }
17466 
17467 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17468   QualType CaptureType;
17469   QualType DeclRefType;
17470 
17471   // Determine whether we can capture this variable.
17472   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17473                          /*BuildAndDiagnose=*/false, CaptureType,
17474                          DeclRefType, nullptr))
17475     return QualType();
17476 
17477   return DeclRefType;
17478 }
17479 
17480 namespace {
17481 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17482 // The produced TemplateArgumentListInfo* points to data stored within this
17483 // object, so should only be used in contexts where the pointer will not be
17484 // used after the CopiedTemplateArgs object is destroyed.
17485 class CopiedTemplateArgs {
17486   bool HasArgs;
17487   TemplateArgumentListInfo TemplateArgStorage;
17488 public:
17489   template<typename RefExpr>
17490   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17491     if (HasArgs)
17492       E->copyTemplateArgumentsInto(TemplateArgStorage);
17493   }
17494   operator TemplateArgumentListInfo*()
17495 #ifdef __has_cpp_attribute
17496 #if __has_cpp_attribute(clang::lifetimebound)
17497   [[clang::lifetimebound]]
17498 #endif
17499 #endif
17500   {
17501     return HasArgs ? &TemplateArgStorage : nullptr;
17502   }
17503 };
17504 }
17505 
17506 /// Walk the set of potential results of an expression and mark them all as
17507 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17508 ///
17509 /// \return A new expression if we found any potential results, ExprEmpty() if
17510 ///         not, and ExprError() if we diagnosed an error.
17511 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17512                                                       NonOdrUseReason NOUR) {
17513   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17514   // an object that satisfies the requirements for appearing in a
17515   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17516   // is immediately applied."  This function handles the lvalue-to-rvalue
17517   // conversion part.
17518   //
17519   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17520   // transform it into the relevant kind of non-odr-use node and rebuild the
17521   // tree of nodes leading to it.
17522   //
17523   // This is a mini-TreeTransform that only transforms a restricted subset of
17524   // nodes (and only certain operands of them).
17525 
17526   // Rebuild a subexpression.
17527   auto Rebuild = [&](Expr *Sub) {
17528     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17529   };
17530 
17531   // Check whether a potential result satisfies the requirements of NOUR.
17532   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17533     // Any entity other than a VarDecl is always odr-used whenever it's named
17534     // in a potentially-evaluated expression.
17535     auto *VD = dyn_cast<VarDecl>(D);
17536     if (!VD)
17537       return true;
17538 
17539     // C++2a [basic.def.odr]p4:
17540     //   A variable x whose name appears as a potentially-evalauted expression
17541     //   e is odr-used by e unless
17542     //   -- x is a reference that is usable in constant expressions, or
17543     //   -- x is a variable of non-reference type that is usable in constant
17544     //      expressions and has no mutable subobjects, and e is an element of
17545     //      the set of potential results of an expression of
17546     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17547     //      conversion is applied, or
17548     //   -- x is a variable of non-reference type, and e is an element of the
17549     //      set of potential results of a discarded-value expression to which
17550     //      the lvalue-to-rvalue conversion is not applied
17551     //
17552     // We check the first bullet and the "potentially-evaluated" condition in
17553     // BuildDeclRefExpr. We check the type requirements in the second bullet
17554     // in CheckLValueToRValueConversionOperand below.
17555     switch (NOUR) {
17556     case NOUR_None:
17557     case NOUR_Unevaluated:
17558       llvm_unreachable("unexpected non-odr-use-reason");
17559 
17560     case NOUR_Constant:
17561       // Constant references were handled when they were built.
17562       if (VD->getType()->isReferenceType())
17563         return true;
17564       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17565         if (RD->hasMutableFields())
17566           return true;
17567       if (!VD->isUsableInConstantExpressions(S.Context))
17568         return true;
17569       break;
17570 
17571     case NOUR_Discarded:
17572       if (VD->getType()->isReferenceType())
17573         return true;
17574       break;
17575     }
17576     return false;
17577   };
17578 
17579   // Mark that this expression does not constitute an odr-use.
17580   auto MarkNotOdrUsed = [&] {
17581     S.MaybeODRUseExprs.remove(E);
17582     if (LambdaScopeInfo *LSI = S.getCurLambda())
17583       LSI->markVariableExprAsNonODRUsed(E);
17584   };
17585 
17586   // C++2a [basic.def.odr]p2:
17587   //   The set of potential results of an expression e is defined as follows:
17588   switch (E->getStmtClass()) {
17589   //   -- If e is an id-expression, ...
17590   case Expr::DeclRefExprClass: {
17591     auto *DRE = cast<DeclRefExpr>(E);
17592     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17593       break;
17594 
17595     // Rebuild as a non-odr-use DeclRefExpr.
17596     MarkNotOdrUsed();
17597     return DeclRefExpr::Create(
17598         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17599         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17600         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17601         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17602   }
17603 
17604   case Expr::FunctionParmPackExprClass: {
17605     auto *FPPE = cast<FunctionParmPackExpr>(E);
17606     // If any of the declarations in the pack is odr-used, then the expression
17607     // as a whole constitutes an odr-use.
17608     for (VarDecl *D : *FPPE)
17609       if (IsPotentialResultOdrUsed(D))
17610         return ExprEmpty();
17611 
17612     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17613     // nothing cares about whether we marked this as an odr-use, but it might
17614     // be useful for non-compiler tools.
17615     MarkNotOdrUsed();
17616     break;
17617   }
17618 
17619   //   -- If e is a subscripting operation with an array operand...
17620   case Expr::ArraySubscriptExprClass: {
17621     auto *ASE = cast<ArraySubscriptExpr>(E);
17622     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17623     if (!OldBase->getType()->isArrayType())
17624       break;
17625     ExprResult Base = Rebuild(OldBase);
17626     if (!Base.isUsable())
17627       return Base;
17628     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17629     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17630     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17631     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17632                                      ASE->getRBracketLoc());
17633   }
17634 
17635   case Expr::MemberExprClass: {
17636     auto *ME = cast<MemberExpr>(E);
17637     // -- If e is a class member access expression [...] naming a non-static
17638     //    data member...
17639     if (isa<FieldDecl>(ME->getMemberDecl())) {
17640       ExprResult Base = Rebuild(ME->getBase());
17641       if (!Base.isUsable())
17642         return Base;
17643       return MemberExpr::Create(
17644           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17645           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17646           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17647           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17648           ME->getObjectKind(), ME->isNonOdrUse());
17649     }
17650 
17651     if (ME->getMemberDecl()->isCXXInstanceMember())
17652       break;
17653 
17654     // -- If e is a class member access expression naming a static data member,
17655     //    ...
17656     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17657       break;
17658 
17659     // Rebuild as a non-odr-use MemberExpr.
17660     MarkNotOdrUsed();
17661     return MemberExpr::Create(
17662         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17663         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17664         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17665         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17666     return ExprEmpty();
17667   }
17668 
17669   case Expr::BinaryOperatorClass: {
17670     auto *BO = cast<BinaryOperator>(E);
17671     Expr *LHS = BO->getLHS();
17672     Expr *RHS = BO->getRHS();
17673     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17674     if (BO->getOpcode() == BO_PtrMemD) {
17675       ExprResult Sub = Rebuild(LHS);
17676       if (!Sub.isUsable())
17677         return Sub;
17678       LHS = Sub.get();
17679     //   -- If e is a comma expression, ...
17680     } else if (BO->getOpcode() == BO_Comma) {
17681       ExprResult Sub = Rebuild(RHS);
17682       if (!Sub.isUsable())
17683         return Sub;
17684       RHS = Sub.get();
17685     } else {
17686       break;
17687     }
17688     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17689                         LHS, RHS);
17690   }
17691 
17692   //   -- If e has the form (e1)...
17693   case Expr::ParenExprClass: {
17694     auto *PE = cast<ParenExpr>(E);
17695     ExprResult Sub = Rebuild(PE->getSubExpr());
17696     if (!Sub.isUsable())
17697       return Sub;
17698     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17699   }
17700 
17701   //   -- If e is a glvalue conditional expression, ...
17702   // We don't apply this to a binary conditional operator. FIXME: Should we?
17703   case Expr::ConditionalOperatorClass: {
17704     auto *CO = cast<ConditionalOperator>(E);
17705     ExprResult LHS = Rebuild(CO->getLHS());
17706     if (LHS.isInvalid())
17707       return ExprError();
17708     ExprResult RHS = Rebuild(CO->getRHS());
17709     if (RHS.isInvalid())
17710       return ExprError();
17711     if (!LHS.isUsable() && !RHS.isUsable())
17712       return ExprEmpty();
17713     if (!LHS.isUsable())
17714       LHS = CO->getLHS();
17715     if (!RHS.isUsable())
17716       RHS = CO->getRHS();
17717     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17718                                 CO->getCond(), LHS.get(), RHS.get());
17719   }
17720 
17721   // [Clang extension]
17722   //   -- If e has the form __extension__ e1...
17723   case Expr::UnaryOperatorClass: {
17724     auto *UO = cast<UnaryOperator>(E);
17725     if (UO->getOpcode() != UO_Extension)
17726       break;
17727     ExprResult Sub = Rebuild(UO->getSubExpr());
17728     if (!Sub.isUsable())
17729       return Sub;
17730     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17731                           Sub.get());
17732   }
17733 
17734   // [Clang extension]
17735   //   -- If e has the form _Generic(...), the set of potential results is the
17736   //      union of the sets of potential results of the associated expressions.
17737   case Expr::GenericSelectionExprClass: {
17738     auto *GSE = cast<GenericSelectionExpr>(E);
17739 
17740     SmallVector<Expr *, 4> AssocExprs;
17741     bool AnyChanged = false;
17742     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17743       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17744       if (AssocExpr.isInvalid())
17745         return ExprError();
17746       if (AssocExpr.isUsable()) {
17747         AssocExprs.push_back(AssocExpr.get());
17748         AnyChanged = true;
17749       } else {
17750         AssocExprs.push_back(OrigAssocExpr);
17751       }
17752     }
17753 
17754     return AnyChanged ? S.CreateGenericSelectionExpr(
17755                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17756                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17757                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17758                       : ExprEmpty();
17759   }
17760 
17761   // [Clang extension]
17762   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17763   //      results is the union of the sets of potential results of the
17764   //      second and third subexpressions.
17765   case Expr::ChooseExprClass: {
17766     auto *CE = cast<ChooseExpr>(E);
17767 
17768     ExprResult LHS = Rebuild(CE->getLHS());
17769     if (LHS.isInvalid())
17770       return ExprError();
17771 
17772     ExprResult RHS = Rebuild(CE->getLHS());
17773     if (RHS.isInvalid())
17774       return ExprError();
17775 
17776     if (!LHS.get() && !RHS.get())
17777       return ExprEmpty();
17778     if (!LHS.isUsable())
17779       LHS = CE->getLHS();
17780     if (!RHS.isUsable())
17781       RHS = CE->getRHS();
17782 
17783     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17784                              RHS.get(), CE->getRParenLoc());
17785   }
17786 
17787   // Step through non-syntactic nodes.
17788   case Expr::ConstantExprClass: {
17789     auto *CE = cast<ConstantExpr>(E);
17790     ExprResult Sub = Rebuild(CE->getSubExpr());
17791     if (!Sub.isUsable())
17792       return Sub;
17793     return ConstantExpr::Create(S.Context, Sub.get());
17794   }
17795 
17796   // We could mostly rely on the recursive rebuilding to rebuild implicit
17797   // casts, but not at the top level, so rebuild them here.
17798   case Expr::ImplicitCastExprClass: {
17799     auto *ICE = cast<ImplicitCastExpr>(E);
17800     // Only step through the narrow set of cast kinds we expect to encounter.
17801     // Anything else suggests we've left the region in which potential results
17802     // can be found.
17803     switch (ICE->getCastKind()) {
17804     case CK_NoOp:
17805     case CK_DerivedToBase:
17806     case CK_UncheckedDerivedToBase: {
17807       ExprResult Sub = Rebuild(ICE->getSubExpr());
17808       if (!Sub.isUsable())
17809         return Sub;
17810       CXXCastPath Path(ICE->path());
17811       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17812                                  ICE->getValueKind(), &Path);
17813     }
17814 
17815     default:
17816       break;
17817     }
17818     break;
17819   }
17820 
17821   default:
17822     break;
17823   }
17824 
17825   // Can't traverse through this node. Nothing to do.
17826   return ExprEmpty();
17827 }
17828 
17829 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17830   // Check whether the operand is or contains an object of non-trivial C union
17831   // type.
17832   if (E->getType().isVolatileQualified() &&
17833       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17834        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17835     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17836                           Sema::NTCUC_LValueToRValueVolatile,
17837                           NTCUK_Destruct|NTCUK_Copy);
17838 
17839   // C++2a [basic.def.odr]p4:
17840   //   [...] an expression of non-volatile-qualified non-class type to which
17841   //   the lvalue-to-rvalue conversion is applied [...]
17842   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17843     return E;
17844 
17845   ExprResult Result =
17846       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17847   if (Result.isInvalid())
17848     return ExprError();
17849   return Result.get() ? Result : E;
17850 }
17851 
17852 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17853   Res = CorrectDelayedTyposInExpr(Res);
17854 
17855   if (!Res.isUsable())
17856     return Res;
17857 
17858   // If a constant-expression is a reference to a variable where we delay
17859   // deciding whether it is an odr-use, just assume we will apply the
17860   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17861   // (a non-type template argument), we have special handling anyway.
17862   return CheckLValueToRValueConversionOperand(Res.get());
17863 }
17864 
17865 void Sema::CleanupVarDeclMarking() {
17866   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17867   // call.
17868   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17869   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17870 
17871   for (Expr *E : LocalMaybeODRUseExprs) {
17872     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17873       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17874                          DRE->getLocation(), *this);
17875     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17876       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17877                          *this);
17878     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17879       for (VarDecl *VD : *FP)
17880         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17881     } else {
17882       llvm_unreachable("Unexpected expression");
17883     }
17884   }
17885 
17886   assert(MaybeODRUseExprs.empty() &&
17887          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17888 }
17889 
17890 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17891                                     VarDecl *Var, Expr *E) {
17892   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17893           isa<FunctionParmPackExpr>(E)) &&
17894          "Invalid Expr argument to DoMarkVarDeclReferenced");
17895   Var->setReferenced();
17896 
17897   if (Var->isInvalidDecl())
17898     return;
17899 
17900   auto *MSI = Var->getMemberSpecializationInfo();
17901   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17902                                        : Var->getTemplateSpecializationKind();
17903 
17904   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17905   bool UsableInConstantExpr =
17906       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17907 
17908   // C++20 [expr.const]p12:
17909   //   A variable [...] is needed for constant evaluation if it is [...] a
17910   //   variable whose name appears as a potentially constant evaluated
17911   //   expression that is either a contexpr variable or is of non-volatile
17912   //   const-qualified integral type or of reference type
17913   bool NeededForConstantEvaluation =
17914       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17915 
17916   bool NeedDefinition =
17917       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17918 
17919   VarTemplateSpecializationDecl *VarSpec =
17920       dyn_cast<VarTemplateSpecializationDecl>(Var);
17921   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17922          "Can't instantiate a partial template specialization.");
17923 
17924   // If this might be a member specialization of a static data member, check
17925   // the specialization is visible. We already did the checks for variable
17926   // template specializations when we created them.
17927   if (NeedDefinition && TSK != TSK_Undeclared &&
17928       !isa<VarTemplateSpecializationDecl>(Var))
17929     SemaRef.checkSpecializationVisibility(Loc, Var);
17930 
17931   // Perform implicit instantiation of static data members, static data member
17932   // templates of class templates, and variable template specializations. Delay
17933   // instantiations of variable templates, except for those that could be used
17934   // in a constant expression.
17935   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17936     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17937     // instantiation declaration if a variable is usable in a constant
17938     // expression (among other cases).
17939     bool TryInstantiating =
17940         TSK == TSK_ImplicitInstantiation ||
17941         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17942 
17943     if (TryInstantiating) {
17944       SourceLocation PointOfInstantiation =
17945           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17946       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17947       if (FirstInstantiation) {
17948         PointOfInstantiation = Loc;
17949         if (MSI)
17950           MSI->setPointOfInstantiation(PointOfInstantiation);
17951         else
17952           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17953       }
17954 
17955       bool InstantiationDependent = false;
17956       bool IsNonDependent =
17957           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17958                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17959                   : true;
17960 
17961       // Do not instantiate specializations that are still type-dependent.
17962       if (IsNonDependent) {
17963         if (UsableInConstantExpr) {
17964           // Do not defer instantiations of variables that could be used in a
17965           // constant expression.
17966           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17967             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17968           });
17969         } else if (FirstInstantiation ||
17970                    isa<VarTemplateSpecializationDecl>(Var)) {
17971           // FIXME: For a specialization of a variable template, we don't
17972           // distinguish between "declaration and type implicitly instantiated"
17973           // and "implicit instantiation of definition requested", so we have
17974           // no direct way to avoid enqueueing the pending instantiation
17975           // multiple times.
17976           SemaRef.PendingInstantiations
17977               .push_back(std::make_pair(Var, PointOfInstantiation));
17978         }
17979       }
17980     }
17981   }
17982 
17983   // C++2a [basic.def.odr]p4:
17984   //   A variable x whose name appears as a potentially-evaluated expression e
17985   //   is odr-used by e unless
17986   //   -- x is a reference that is usable in constant expressions
17987   //   -- x is a variable of non-reference type that is usable in constant
17988   //      expressions and has no mutable subobjects [FIXME], and e is an
17989   //      element of the set of potential results of an expression of
17990   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17991   //      conversion is applied
17992   //   -- x is a variable of non-reference type, and e is an element of the set
17993   //      of potential results of a discarded-value expression to which the
17994   //      lvalue-to-rvalue conversion is not applied [FIXME]
17995   //
17996   // We check the first part of the second bullet here, and
17997   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17998   // FIXME: To get the third bullet right, we need to delay this even for
17999   // variables that are not usable in constant expressions.
18000 
18001   // If we already know this isn't an odr-use, there's nothing more to do.
18002   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18003     if (DRE->isNonOdrUse())
18004       return;
18005   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18006     if (ME->isNonOdrUse())
18007       return;
18008 
18009   switch (OdrUse) {
18010   case OdrUseContext::None:
18011     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18012            "missing non-odr-use marking for unevaluated decl ref");
18013     break;
18014 
18015   case OdrUseContext::FormallyOdrUsed:
18016     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18017     // behavior.
18018     break;
18019 
18020   case OdrUseContext::Used:
18021     // If we might later find that this expression isn't actually an odr-use,
18022     // delay the marking.
18023     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18024       SemaRef.MaybeODRUseExprs.insert(E);
18025     else
18026       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18027     break;
18028 
18029   case OdrUseContext::Dependent:
18030     // If this is a dependent context, we don't need to mark variables as
18031     // odr-used, but we may still need to track them for lambda capture.
18032     // FIXME: Do we also need to do this inside dependent typeid expressions
18033     // (which are modeled as unevaluated at this point)?
18034     const bool RefersToEnclosingScope =
18035         (SemaRef.CurContext != Var->getDeclContext() &&
18036          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18037     if (RefersToEnclosingScope) {
18038       LambdaScopeInfo *const LSI =
18039           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18040       if (LSI && (!LSI->CallOperator ||
18041                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18042         // If a variable could potentially be odr-used, defer marking it so
18043         // until we finish analyzing the full expression for any
18044         // lvalue-to-rvalue
18045         // or discarded value conversions that would obviate odr-use.
18046         // Add it to the list of potential captures that will be analyzed
18047         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18048         // unless the variable is a reference that was initialized by a constant
18049         // expression (this will never need to be captured or odr-used).
18050         //
18051         // FIXME: We can simplify this a lot after implementing P0588R1.
18052         assert(E && "Capture variable should be used in an expression.");
18053         if (!Var->getType()->isReferenceType() ||
18054             !Var->isUsableInConstantExpressions(SemaRef.Context))
18055           LSI->addPotentialCapture(E->IgnoreParens());
18056       }
18057     }
18058     break;
18059   }
18060 }
18061 
18062 /// Mark a variable referenced, and check whether it is odr-used
18063 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18064 /// used directly for normal expressions referring to VarDecl.
18065 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18066   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18067 }
18068 
18069 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18070                                Decl *D, Expr *E, bool MightBeOdrUse) {
18071   if (SemaRef.isInOpenMPDeclareTargetContext())
18072     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18073 
18074   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18075     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18076     return;
18077   }
18078 
18079   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18080 
18081   // If this is a call to a method via a cast, also mark the method in the
18082   // derived class used in case codegen can devirtualize the call.
18083   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18084   if (!ME)
18085     return;
18086   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18087   if (!MD)
18088     return;
18089   // Only attempt to devirtualize if this is truly a virtual call.
18090   bool IsVirtualCall = MD->isVirtual() &&
18091                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18092   if (!IsVirtualCall)
18093     return;
18094 
18095   // If it's possible to devirtualize the call, mark the called function
18096   // referenced.
18097   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18098       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18099   if (DM)
18100     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18101 }
18102 
18103 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18104 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18105   // TODO: update this with DR# once a defect report is filed.
18106   // C++11 defect. The address of a pure member should not be an ODR use, even
18107   // if it's a qualified reference.
18108   bool OdrUse = true;
18109   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18110     if (Method->isVirtual() &&
18111         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18112       OdrUse = false;
18113 
18114   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18115     if (!isConstantEvaluated() && FD->isConsteval() &&
18116         !RebuildingImmediateInvocation)
18117       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18118   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18119 }
18120 
18121 /// Perform reference-marking and odr-use handling for a MemberExpr.
18122 void Sema::MarkMemberReferenced(MemberExpr *E) {
18123   // C++11 [basic.def.odr]p2:
18124   //   A non-overloaded function whose name appears as a potentially-evaluated
18125   //   expression or a member of a set of candidate functions, if selected by
18126   //   overload resolution when referred to from a potentially-evaluated
18127   //   expression, is odr-used, unless it is a pure virtual function and its
18128   //   name is not explicitly qualified.
18129   bool MightBeOdrUse = true;
18130   if (E->performsVirtualDispatch(getLangOpts())) {
18131     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18132       if (Method->isPure())
18133         MightBeOdrUse = false;
18134   }
18135   SourceLocation Loc =
18136       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18137   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18138 }
18139 
18140 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18141 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18142   for (VarDecl *VD : *E)
18143     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18144 }
18145 
18146 /// Perform marking for a reference to an arbitrary declaration.  It
18147 /// marks the declaration referenced, and performs odr-use checking for
18148 /// functions and variables. This method should not be used when building a
18149 /// normal expression which refers to a variable.
18150 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18151                                  bool MightBeOdrUse) {
18152   if (MightBeOdrUse) {
18153     if (auto *VD = dyn_cast<VarDecl>(D)) {
18154       MarkVariableReferenced(Loc, VD);
18155       return;
18156     }
18157   }
18158   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18159     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18160     return;
18161   }
18162   D->setReferenced();
18163 }
18164 
18165 namespace {
18166   // Mark all of the declarations used by a type as referenced.
18167   // FIXME: Not fully implemented yet! We need to have a better understanding
18168   // of when we're entering a context we should not recurse into.
18169   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18170   // TreeTransforms rebuilding the type in a new context. Rather than
18171   // duplicating the TreeTransform logic, we should consider reusing it here.
18172   // Currently that causes problems when rebuilding LambdaExprs.
18173   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18174     Sema &S;
18175     SourceLocation Loc;
18176 
18177   public:
18178     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18179 
18180     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18181 
18182     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18183   };
18184 }
18185 
18186 bool MarkReferencedDecls::TraverseTemplateArgument(
18187     const TemplateArgument &Arg) {
18188   {
18189     // A non-type template argument is a constant-evaluated context.
18190     EnterExpressionEvaluationContext Evaluated(
18191         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18192     if (Arg.getKind() == TemplateArgument::Declaration) {
18193       if (Decl *D = Arg.getAsDecl())
18194         S.MarkAnyDeclReferenced(Loc, D, true);
18195     } else if (Arg.getKind() == TemplateArgument::Expression) {
18196       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18197     }
18198   }
18199 
18200   return Inherited::TraverseTemplateArgument(Arg);
18201 }
18202 
18203 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18204   MarkReferencedDecls Marker(*this, Loc);
18205   Marker.TraverseType(T);
18206 }
18207 
18208 namespace {
18209 /// Helper class that marks all of the declarations referenced by
18210 /// potentially-evaluated subexpressions as "referenced".
18211 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18212 public:
18213   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18214   bool SkipLocalVariables;
18215 
18216   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18217       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18218 
18219   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18220     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18221   }
18222 
18223   void VisitDeclRefExpr(DeclRefExpr *E) {
18224     // If we were asked not to visit local variables, don't.
18225     if (SkipLocalVariables) {
18226       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18227         if (VD->hasLocalStorage())
18228           return;
18229     }
18230     S.MarkDeclRefReferenced(E);
18231   }
18232 
18233   void VisitMemberExpr(MemberExpr *E) {
18234     S.MarkMemberReferenced(E);
18235     Visit(E->getBase());
18236   }
18237 };
18238 } // namespace
18239 
18240 /// Mark any declarations that appear within this expression or any
18241 /// potentially-evaluated subexpressions as "referenced".
18242 ///
18243 /// \param SkipLocalVariables If true, don't mark local variables as
18244 /// 'referenced'.
18245 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18246                                             bool SkipLocalVariables) {
18247   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18248 }
18249 
18250 /// Emit a diagnostic that describes an effect on the run-time behavior
18251 /// of the program being compiled.
18252 ///
18253 /// This routine emits the given diagnostic when the code currently being
18254 /// type-checked is "potentially evaluated", meaning that there is a
18255 /// possibility that the code will actually be executable. Code in sizeof()
18256 /// expressions, code used only during overload resolution, etc., are not
18257 /// potentially evaluated. This routine will suppress such diagnostics or,
18258 /// in the absolutely nutty case of potentially potentially evaluated
18259 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18260 /// later.
18261 ///
18262 /// This routine should be used for all diagnostics that describe the run-time
18263 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18264 /// Failure to do so will likely result in spurious diagnostics or failures
18265 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18266 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18267                                const PartialDiagnostic &PD) {
18268   switch (ExprEvalContexts.back().Context) {
18269   case ExpressionEvaluationContext::Unevaluated:
18270   case ExpressionEvaluationContext::UnevaluatedList:
18271   case ExpressionEvaluationContext::UnevaluatedAbstract:
18272   case ExpressionEvaluationContext::DiscardedStatement:
18273     // The argument will never be evaluated, so don't complain.
18274     break;
18275 
18276   case ExpressionEvaluationContext::ConstantEvaluated:
18277     // Relevant diagnostics should be produced by constant evaluation.
18278     break;
18279 
18280   case ExpressionEvaluationContext::PotentiallyEvaluated:
18281   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18282     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18283       FunctionScopes.back()->PossiblyUnreachableDiags.
18284         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18285       return true;
18286     }
18287 
18288     // The initializer of a constexpr variable or of the first declaration of a
18289     // static data member is not syntactically a constant evaluated constant,
18290     // but nonetheless is always required to be a constant expression, so we
18291     // can skip diagnosing.
18292     // FIXME: Using the mangling context here is a hack.
18293     if (auto *VD = dyn_cast_or_null<VarDecl>(
18294             ExprEvalContexts.back().ManglingContextDecl)) {
18295       if (VD->isConstexpr() ||
18296           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18297         break;
18298       // FIXME: For any other kind of variable, we should build a CFG for its
18299       // initializer and check whether the context in question is reachable.
18300     }
18301 
18302     Diag(Loc, PD);
18303     return true;
18304   }
18305 
18306   return false;
18307 }
18308 
18309 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18310                                const PartialDiagnostic &PD) {
18311   return DiagRuntimeBehavior(
18312       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18313 }
18314 
18315 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18316                                CallExpr *CE, FunctionDecl *FD) {
18317   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18318     return false;
18319 
18320   // If we're inside a decltype's expression, don't check for a valid return
18321   // type or construct temporaries until we know whether this is the last call.
18322   if (ExprEvalContexts.back().ExprContext ==
18323       ExpressionEvaluationContextRecord::EK_Decltype) {
18324     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18325     return false;
18326   }
18327 
18328   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18329     FunctionDecl *FD;
18330     CallExpr *CE;
18331 
18332   public:
18333     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18334       : FD(FD), CE(CE) { }
18335 
18336     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18337       if (!FD) {
18338         S.Diag(Loc, diag::err_call_incomplete_return)
18339           << T << CE->getSourceRange();
18340         return;
18341       }
18342 
18343       S.Diag(Loc, diag::err_call_function_incomplete_return)
18344         << CE->getSourceRange() << FD->getDeclName() << T;
18345       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18346           << FD->getDeclName();
18347     }
18348   } Diagnoser(FD, CE);
18349 
18350   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18351     return true;
18352 
18353   return false;
18354 }
18355 
18356 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18357 // will prevent this condition from triggering, which is what we want.
18358 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18359   SourceLocation Loc;
18360 
18361   unsigned diagnostic = diag::warn_condition_is_assignment;
18362   bool IsOrAssign = false;
18363 
18364   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18365     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18366       return;
18367 
18368     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18369 
18370     // Greylist some idioms by putting them into a warning subcategory.
18371     if (ObjCMessageExpr *ME
18372           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18373       Selector Sel = ME->getSelector();
18374 
18375       // self = [<foo> init...]
18376       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18377         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18378 
18379       // <foo> = [<bar> nextObject]
18380       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18381         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18382     }
18383 
18384     Loc = Op->getOperatorLoc();
18385   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18386     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18387       return;
18388 
18389     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18390     Loc = Op->getOperatorLoc();
18391   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18392     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18393   else {
18394     // Not an assignment.
18395     return;
18396   }
18397 
18398   Diag(Loc, diagnostic) << E->getSourceRange();
18399 
18400   SourceLocation Open = E->getBeginLoc();
18401   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18402   Diag(Loc, diag::note_condition_assign_silence)
18403         << FixItHint::CreateInsertion(Open, "(")
18404         << FixItHint::CreateInsertion(Close, ")");
18405 
18406   if (IsOrAssign)
18407     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18408       << FixItHint::CreateReplacement(Loc, "!=");
18409   else
18410     Diag(Loc, diag::note_condition_assign_to_comparison)
18411       << FixItHint::CreateReplacement(Loc, "==");
18412 }
18413 
18414 /// Redundant parentheses over an equality comparison can indicate
18415 /// that the user intended an assignment used as condition.
18416 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18417   // Don't warn if the parens came from a macro.
18418   SourceLocation parenLoc = ParenE->getBeginLoc();
18419   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18420     return;
18421   // Don't warn for dependent expressions.
18422   if (ParenE->isTypeDependent())
18423     return;
18424 
18425   Expr *E = ParenE->IgnoreParens();
18426 
18427   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18428     if (opE->getOpcode() == BO_EQ &&
18429         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18430                                                            == Expr::MLV_Valid) {
18431       SourceLocation Loc = opE->getOperatorLoc();
18432 
18433       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18434       SourceRange ParenERange = ParenE->getSourceRange();
18435       Diag(Loc, diag::note_equality_comparison_silence)
18436         << FixItHint::CreateRemoval(ParenERange.getBegin())
18437         << FixItHint::CreateRemoval(ParenERange.getEnd());
18438       Diag(Loc, diag::note_equality_comparison_to_assign)
18439         << FixItHint::CreateReplacement(Loc, "=");
18440     }
18441 }
18442 
18443 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18444                                        bool IsConstexpr) {
18445   DiagnoseAssignmentAsCondition(E);
18446   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18447     DiagnoseEqualityWithExtraParens(parenE);
18448 
18449   ExprResult result = CheckPlaceholderExpr(E);
18450   if (result.isInvalid()) return ExprError();
18451   E = result.get();
18452 
18453   if (!E->isTypeDependent()) {
18454     if (getLangOpts().CPlusPlus)
18455       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18456 
18457     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18458     if (ERes.isInvalid())
18459       return ExprError();
18460     E = ERes.get();
18461 
18462     QualType T = E->getType();
18463     if (!T->isScalarType()) { // C99 6.8.4.1p1
18464       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18465         << T << E->getSourceRange();
18466       return ExprError();
18467     }
18468     CheckBoolLikeConversion(E, Loc);
18469   }
18470 
18471   return E;
18472 }
18473 
18474 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18475                                            Expr *SubExpr, ConditionKind CK) {
18476   // Empty conditions are valid in for-statements.
18477   if (!SubExpr)
18478     return ConditionResult();
18479 
18480   ExprResult Cond;
18481   switch (CK) {
18482   case ConditionKind::Boolean:
18483     Cond = CheckBooleanCondition(Loc, SubExpr);
18484     break;
18485 
18486   case ConditionKind::ConstexprIf:
18487     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18488     break;
18489 
18490   case ConditionKind::Switch:
18491     Cond = CheckSwitchCondition(Loc, SubExpr);
18492     break;
18493   }
18494   if (Cond.isInvalid())
18495     return ConditionError();
18496 
18497   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18498   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18499   if (!FullExpr.get())
18500     return ConditionError();
18501 
18502   return ConditionResult(*this, nullptr, FullExpr,
18503                          CK == ConditionKind::ConstexprIf);
18504 }
18505 
18506 namespace {
18507   /// A visitor for rebuilding a call to an __unknown_any expression
18508   /// to have an appropriate type.
18509   struct RebuildUnknownAnyFunction
18510     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18511 
18512     Sema &S;
18513 
18514     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18515 
18516     ExprResult VisitStmt(Stmt *S) {
18517       llvm_unreachable("unexpected statement!");
18518     }
18519 
18520     ExprResult VisitExpr(Expr *E) {
18521       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18522         << E->getSourceRange();
18523       return ExprError();
18524     }
18525 
18526     /// Rebuild an expression which simply semantically wraps another
18527     /// expression which it shares the type and value kind of.
18528     template <class T> ExprResult rebuildSugarExpr(T *E) {
18529       ExprResult SubResult = Visit(E->getSubExpr());
18530       if (SubResult.isInvalid()) return ExprError();
18531 
18532       Expr *SubExpr = SubResult.get();
18533       E->setSubExpr(SubExpr);
18534       E->setType(SubExpr->getType());
18535       E->setValueKind(SubExpr->getValueKind());
18536       assert(E->getObjectKind() == OK_Ordinary);
18537       return E;
18538     }
18539 
18540     ExprResult VisitParenExpr(ParenExpr *E) {
18541       return rebuildSugarExpr(E);
18542     }
18543 
18544     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18545       return rebuildSugarExpr(E);
18546     }
18547 
18548     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18549       ExprResult SubResult = Visit(E->getSubExpr());
18550       if (SubResult.isInvalid()) return ExprError();
18551 
18552       Expr *SubExpr = SubResult.get();
18553       E->setSubExpr(SubExpr);
18554       E->setType(S.Context.getPointerType(SubExpr->getType()));
18555       assert(E->getValueKind() == VK_RValue);
18556       assert(E->getObjectKind() == OK_Ordinary);
18557       return E;
18558     }
18559 
18560     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18561       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18562 
18563       E->setType(VD->getType());
18564 
18565       assert(E->getValueKind() == VK_RValue);
18566       if (S.getLangOpts().CPlusPlus &&
18567           !(isa<CXXMethodDecl>(VD) &&
18568             cast<CXXMethodDecl>(VD)->isInstance()))
18569         E->setValueKind(VK_LValue);
18570 
18571       return E;
18572     }
18573 
18574     ExprResult VisitMemberExpr(MemberExpr *E) {
18575       return resolveDecl(E, E->getMemberDecl());
18576     }
18577 
18578     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18579       return resolveDecl(E, E->getDecl());
18580     }
18581   };
18582 }
18583 
18584 /// Given a function expression of unknown-any type, try to rebuild it
18585 /// to have a function type.
18586 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18587   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18588   if (Result.isInvalid()) return ExprError();
18589   return S.DefaultFunctionArrayConversion(Result.get());
18590 }
18591 
18592 namespace {
18593   /// A visitor for rebuilding an expression of type __unknown_anytype
18594   /// into one which resolves the type directly on the referring
18595   /// expression.  Strict preservation of the original source
18596   /// structure is not a goal.
18597   struct RebuildUnknownAnyExpr
18598     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18599 
18600     Sema &S;
18601 
18602     /// The current destination type.
18603     QualType DestType;
18604 
18605     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18606       : S(S), DestType(CastType) {}
18607 
18608     ExprResult VisitStmt(Stmt *S) {
18609       llvm_unreachable("unexpected statement!");
18610     }
18611 
18612     ExprResult VisitExpr(Expr *E) {
18613       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18614         << E->getSourceRange();
18615       return ExprError();
18616     }
18617 
18618     ExprResult VisitCallExpr(CallExpr *E);
18619     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18620 
18621     /// Rebuild an expression which simply semantically wraps another
18622     /// expression which it shares the type and value kind of.
18623     template <class T> ExprResult rebuildSugarExpr(T *E) {
18624       ExprResult SubResult = Visit(E->getSubExpr());
18625       if (SubResult.isInvalid()) return ExprError();
18626       Expr *SubExpr = SubResult.get();
18627       E->setSubExpr(SubExpr);
18628       E->setType(SubExpr->getType());
18629       E->setValueKind(SubExpr->getValueKind());
18630       assert(E->getObjectKind() == OK_Ordinary);
18631       return E;
18632     }
18633 
18634     ExprResult VisitParenExpr(ParenExpr *E) {
18635       return rebuildSugarExpr(E);
18636     }
18637 
18638     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18639       return rebuildSugarExpr(E);
18640     }
18641 
18642     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18643       const PointerType *Ptr = DestType->getAs<PointerType>();
18644       if (!Ptr) {
18645         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18646           << E->getSourceRange();
18647         return ExprError();
18648       }
18649 
18650       if (isa<CallExpr>(E->getSubExpr())) {
18651         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18652           << E->getSourceRange();
18653         return ExprError();
18654       }
18655 
18656       assert(E->getValueKind() == VK_RValue);
18657       assert(E->getObjectKind() == OK_Ordinary);
18658       E->setType(DestType);
18659 
18660       // Build the sub-expression as if it were an object of the pointee type.
18661       DestType = Ptr->getPointeeType();
18662       ExprResult SubResult = Visit(E->getSubExpr());
18663       if (SubResult.isInvalid()) return ExprError();
18664       E->setSubExpr(SubResult.get());
18665       return E;
18666     }
18667 
18668     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18669 
18670     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18671 
18672     ExprResult VisitMemberExpr(MemberExpr *E) {
18673       return resolveDecl(E, E->getMemberDecl());
18674     }
18675 
18676     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18677       return resolveDecl(E, E->getDecl());
18678     }
18679   };
18680 }
18681 
18682 /// Rebuilds a call expression which yielded __unknown_anytype.
18683 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18684   Expr *CalleeExpr = E->getCallee();
18685 
18686   enum FnKind {
18687     FK_MemberFunction,
18688     FK_FunctionPointer,
18689     FK_BlockPointer
18690   };
18691 
18692   FnKind Kind;
18693   QualType CalleeType = CalleeExpr->getType();
18694   if (CalleeType == S.Context.BoundMemberTy) {
18695     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18696     Kind = FK_MemberFunction;
18697     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18698   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18699     CalleeType = Ptr->getPointeeType();
18700     Kind = FK_FunctionPointer;
18701   } else {
18702     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18703     Kind = FK_BlockPointer;
18704   }
18705   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18706 
18707   // Verify that this is a legal result type of a function.
18708   if (DestType->isArrayType() || DestType->isFunctionType()) {
18709     unsigned diagID = diag::err_func_returning_array_function;
18710     if (Kind == FK_BlockPointer)
18711       diagID = diag::err_block_returning_array_function;
18712 
18713     S.Diag(E->getExprLoc(), diagID)
18714       << DestType->isFunctionType() << DestType;
18715     return ExprError();
18716   }
18717 
18718   // Otherwise, go ahead and set DestType as the call's result.
18719   E->setType(DestType.getNonLValueExprType(S.Context));
18720   E->setValueKind(Expr::getValueKindForType(DestType));
18721   assert(E->getObjectKind() == OK_Ordinary);
18722 
18723   // Rebuild the function type, replacing the result type with DestType.
18724   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18725   if (Proto) {
18726     // __unknown_anytype(...) is a special case used by the debugger when
18727     // it has no idea what a function's signature is.
18728     //
18729     // We want to build this call essentially under the K&R
18730     // unprototyped rules, but making a FunctionNoProtoType in C++
18731     // would foul up all sorts of assumptions.  However, we cannot
18732     // simply pass all arguments as variadic arguments, nor can we
18733     // portably just call the function under a non-variadic type; see
18734     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18735     // However, it turns out that in practice it is generally safe to
18736     // call a function declared as "A foo(B,C,D);" under the prototype
18737     // "A foo(B,C,D,...);".  The only known exception is with the
18738     // Windows ABI, where any variadic function is implicitly cdecl
18739     // regardless of its normal CC.  Therefore we change the parameter
18740     // types to match the types of the arguments.
18741     //
18742     // This is a hack, but it is far superior to moving the
18743     // corresponding target-specific code from IR-gen to Sema/AST.
18744 
18745     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18746     SmallVector<QualType, 8> ArgTypes;
18747     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18748       ArgTypes.reserve(E->getNumArgs());
18749       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18750         Expr *Arg = E->getArg(i);
18751         QualType ArgType = Arg->getType();
18752         if (E->isLValue()) {
18753           ArgType = S.Context.getLValueReferenceType(ArgType);
18754         } else if (E->isXValue()) {
18755           ArgType = S.Context.getRValueReferenceType(ArgType);
18756         }
18757         ArgTypes.push_back(ArgType);
18758       }
18759       ParamTypes = ArgTypes;
18760     }
18761     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18762                                          Proto->getExtProtoInfo());
18763   } else {
18764     DestType = S.Context.getFunctionNoProtoType(DestType,
18765                                                 FnType->getExtInfo());
18766   }
18767 
18768   // Rebuild the appropriate pointer-to-function type.
18769   switch (Kind) {
18770   case FK_MemberFunction:
18771     // Nothing to do.
18772     break;
18773 
18774   case FK_FunctionPointer:
18775     DestType = S.Context.getPointerType(DestType);
18776     break;
18777 
18778   case FK_BlockPointer:
18779     DestType = S.Context.getBlockPointerType(DestType);
18780     break;
18781   }
18782 
18783   // Finally, we can recurse.
18784   ExprResult CalleeResult = Visit(CalleeExpr);
18785   if (!CalleeResult.isUsable()) return ExprError();
18786   E->setCallee(CalleeResult.get());
18787 
18788   // Bind a temporary if necessary.
18789   return S.MaybeBindToTemporary(E);
18790 }
18791 
18792 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18793   // Verify that this is a legal result type of a call.
18794   if (DestType->isArrayType() || DestType->isFunctionType()) {
18795     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18796       << DestType->isFunctionType() << DestType;
18797     return ExprError();
18798   }
18799 
18800   // Rewrite the method result type if available.
18801   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18802     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18803     Method->setReturnType(DestType);
18804   }
18805 
18806   // Change the type of the message.
18807   E->setType(DestType.getNonReferenceType());
18808   E->setValueKind(Expr::getValueKindForType(DestType));
18809 
18810   return S.MaybeBindToTemporary(E);
18811 }
18812 
18813 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18814   // The only case we should ever see here is a function-to-pointer decay.
18815   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18816     assert(E->getValueKind() == VK_RValue);
18817     assert(E->getObjectKind() == OK_Ordinary);
18818 
18819     E->setType(DestType);
18820 
18821     // Rebuild the sub-expression as the pointee (function) type.
18822     DestType = DestType->castAs<PointerType>()->getPointeeType();
18823 
18824     ExprResult Result = Visit(E->getSubExpr());
18825     if (!Result.isUsable()) return ExprError();
18826 
18827     E->setSubExpr(Result.get());
18828     return E;
18829   } else if (E->getCastKind() == CK_LValueToRValue) {
18830     assert(E->getValueKind() == VK_RValue);
18831     assert(E->getObjectKind() == OK_Ordinary);
18832 
18833     assert(isa<BlockPointerType>(E->getType()));
18834 
18835     E->setType(DestType);
18836 
18837     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18838     DestType = S.Context.getLValueReferenceType(DestType);
18839 
18840     ExprResult Result = Visit(E->getSubExpr());
18841     if (!Result.isUsable()) return ExprError();
18842 
18843     E->setSubExpr(Result.get());
18844     return E;
18845   } else {
18846     llvm_unreachable("Unhandled cast type!");
18847   }
18848 }
18849 
18850 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18851   ExprValueKind ValueKind = VK_LValue;
18852   QualType Type = DestType;
18853 
18854   // We know how to make this work for certain kinds of decls:
18855 
18856   //  - functions
18857   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18858     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18859       DestType = Ptr->getPointeeType();
18860       ExprResult Result = resolveDecl(E, VD);
18861       if (Result.isInvalid()) return ExprError();
18862       return S.ImpCastExprToType(Result.get(), Type,
18863                                  CK_FunctionToPointerDecay, VK_RValue);
18864     }
18865 
18866     if (!Type->isFunctionType()) {
18867       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18868         << VD << E->getSourceRange();
18869       return ExprError();
18870     }
18871     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18872       // We must match the FunctionDecl's type to the hack introduced in
18873       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18874       // type. See the lengthy commentary in that routine.
18875       QualType FDT = FD->getType();
18876       const FunctionType *FnType = FDT->castAs<FunctionType>();
18877       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18878       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18879       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18880         SourceLocation Loc = FD->getLocation();
18881         FunctionDecl *NewFD = FunctionDecl::Create(
18882             S.Context, FD->getDeclContext(), Loc, Loc,
18883             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18884             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18885             /*ConstexprKind*/ CSK_unspecified);
18886 
18887         if (FD->getQualifier())
18888           NewFD->setQualifierInfo(FD->getQualifierLoc());
18889 
18890         SmallVector<ParmVarDecl*, 16> Params;
18891         for (const auto &AI : FT->param_types()) {
18892           ParmVarDecl *Param =
18893             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18894           Param->setScopeInfo(0, Params.size());
18895           Params.push_back(Param);
18896         }
18897         NewFD->setParams(Params);
18898         DRE->setDecl(NewFD);
18899         VD = DRE->getDecl();
18900       }
18901     }
18902 
18903     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18904       if (MD->isInstance()) {
18905         ValueKind = VK_RValue;
18906         Type = S.Context.BoundMemberTy;
18907       }
18908 
18909     // Function references aren't l-values in C.
18910     if (!S.getLangOpts().CPlusPlus)
18911       ValueKind = VK_RValue;
18912 
18913   //  - variables
18914   } else if (isa<VarDecl>(VD)) {
18915     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18916       Type = RefTy->getPointeeType();
18917     } else if (Type->isFunctionType()) {
18918       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18919         << VD << E->getSourceRange();
18920       return ExprError();
18921     }
18922 
18923   //  - nothing else
18924   } else {
18925     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18926       << VD << E->getSourceRange();
18927     return ExprError();
18928   }
18929 
18930   // Modifying the declaration like this is friendly to IR-gen but
18931   // also really dangerous.
18932   VD->setType(DestType);
18933   E->setType(Type);
18934   E->setValueKind(ValueKind);
18935   return E;
18936 }
18937 
18938 /// Check a cast of an unknown-any type.  We intentionally only
18939 /// trigger this for C-style casts.
18940 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18941                                      Expr *CastExpr, CastKind &CastKind,
18942                                      ExprValueKind &VK, CXXCastPath &Path) {
18943   // The type we're casting to must be either void or complete.
18944   if (!CastType->isVoidType() &&
18945       RequireCompleteType(TypeRange.getBegin(), CastType,
18946                           diag::err_typecheck_cast_to_incomplete))
18947     return ExprError();
18948 
18949   // Rewrite the casted expression from scratch.
18950   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18951   if (!result.isUsable()) return ExprError();
18952 
18953   CastExpr = result.get();
18954   VK = CastExpr->getValueKind();
18955   CastKind = CK_NoOp;
18956 
18957   return CastExpr;
18958 }
18959 
18960 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18961   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18962 }
18963 
18964 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18965                                     Expr *arg, QualType &paramType) {
18966   // If the syntactic form of the argument is not an explicit cast of
18967   // any sort, just do default argument promotion.
18968   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18969   if (!castArg) {
18970     ExprResult result = DefaultArgumentPromotion(arg);
18971     if (result.isInvalid()) return ExprError();
18972     paramType = result.get()->getType();
18973     return result;
18974   }
18975 
18976   // Otherwise, use the type that was written in the explicit cast.
18977   assert(!arg->hasPlaceholderType());
18978   paramType = castArg->getTypeAsWritten();
18979 
18980   // Copy-initialize a parameter of that type.
18981   InitializedEntity entity =
18982     InitializedEntity::InitializeParameter(Context, paramType,
18983                                            /*consumed*/ false);
18984   return PerformCopyInitialization(entity, callLoc, arg);
18985 }
18986 
18987 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18988   Expr *orig = E;
18989   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18990   while (true) {
18991     E = E->IgnoreParenImpCasts();
18992     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18993       E = call->getCallee();
18994       diagID = diag::err_uncasted_call_of_unknown_any;
18995     } else {
18996       break;
18997     }
18998   }
18999 
19000   SourceLocation loc;
19001   NamedDecl *d;
19002   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19003     loc = ref->getLocation();
19004     d = ref->getDecl();
19005   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19006     loc = mem->getMemberLoc();
19007     d = mem->getMemberDecl();
19008   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19009     diagID = diag::err_uncasted_call_of_unknown_any;
19010     loc = msg->getSelectorStartLoc();
19011     d = msg->getMethodDecl();
19012     if (!d) {
19013       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19014         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19015         << orig->getSourceRange();
19016       return ExprError();
19017     }
19018   } else {
19019     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19020       << E->getSourceRange();
19021     return ExprError();
19022   }
19023 
19024   S.Diag(loc, diagID) << d << orig->getSourceRange();
19025 
19026   // Never recoverable.
19027   return ExprError();
19028 }
19029 
19030 /// Check for operands with placeholder types and complain if found.
19031 /// Returns ExprError() if there was an error and no recovery was possible.
19032 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19033   if (!getLangOpts().CPlusPlus) {
19034     // C cannot handle TypoExpr nodes on either side of a binop because it
19035     // doesn't handle dependent types properly, so make sure any TypoExprs have
19036     // been dealt with before checking the operands.
19037     ExprResult Result = CorrectDelayedTyposInExpr(E);
19038     if (!Result.isUsable()) return ExprError();
19039     E = Result.get();
19040   }
19041 
19042   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19043   if (!placeholderType) return E;
19044 
19045   switch (placeholderType->getKind()) {
19046 
19047   // Overloaded expressions.
19048   case BuiltinType::Overload: {
19049     // Try to resolve a single function template specialization.
19050     // This is obligatory.
19051     ExprResult Result = E;
19052     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19053       return Result;
19054 
19055     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19056     // leaves Result unchanged on failure.
19057     Result = E;
19058     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19059       return Result;
19060 
19061     // If that failed, try to recover with a call.
19062     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19063                          /*complain*/ true);
19064     return Result;
19065   }
19066 
19067   // Bound member functions.
19068   case BuiltinType::BoundMember: {
19069     ExprResult result = E;
19070     const Expr *BME = E->IgnoreParens();
19071     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19072     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19073     if (isa<CXXPseudoDestructorExpr>(BME)) {
19074       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19075     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19076       if (ME->getMemberNameInfo().getName().getNameKind() ==
19077           DeclarationName::CXXDestructorName)
19078         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19079     }
19080     tryToRecoverWithCall(result, PD,
19081                          /*complain*/ true);
19082     return result;
19083   }
19084 
19085   // ARC unbridged casts.
19086   case BuiltinType::ARCUnbridgedCast: {
19087     Expr *realCast = stripARCUnbridgedCast(E);
19088     diagnoseARCUnbridgedCast(realCast);
19089     return realCast;
19090   }
19091 
19092   // Expressions of unknown type.
19093   case BuiltinType::UnknownAny:
19094     return diagnoseUnknownAnyExpr(*this, E);
19095 
19096   // Pseudo-objects.
19097   case BuiltinType::PseudoObject:
19098     return checkPseudoObjectRValue(E);
19099 
19100   case BuiltinType::BuiltinFn: {
19101     // Accept __noop without parens by implicitly converting it to a call expr.
19102     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19103     if (DRE) {
19104       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19105       if (FD->getBuiltinID() == Builtin::BI__noop) {
19106         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19107                               CK_BuiltinFnToFnPtr)
19108                 .get();
19109         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19110                                 VK_RValue, SourceLocation());
19111       }
19112     }
19113 
19114     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19115     return ExprError();
19116   }
19117 
19118   case BuiltinType::IncompleteMatrixIdx:
19119     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19120              ->getRowIdx()
19121              ->getBeginLoc(),
19122          diag::err_matrix_incomplete_index);
19123     return ExprError();
19124 
19125   // Expressions of unknown type.
19126   case BuiltinType::OMPArraySection:
19127     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19128     return ExprError();
19129 
19130   // Expressions of unknown type.
19131   case BuiltinType::OMPArrayShaping:
19132     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19133 
19134   case BuiltinType::OMPIterator:
19135     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19136 
19137   // Everything else should be impossible.
19138 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19139   case BuiltinType::Id:
19140 #include "clang/Basic/OpenCLImageTypes.def"
19141 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19142   case BuiltinType::Id:
19143 #include "clang/Basic/OpenCLExtensionTypes.def"
19144 #define SVE_TYPE(Name, Id, SingletonId) \
19145   case BuiltinType::Id:
19146 #include "clang/Basic/AArch64SVEACLETypes.def"
19147 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19148 #define PLACEHOLDER_TYPE(Id, SingletonId)
19149 #include "clang/AST/BuiltinTypes.def"
19150     break;
19151   }
19152 
19153   llvm_unreachable("invalid placeholder type!");
19154 }
19155 
19156 bool Sema::CheckCaseExpression(Expr *E) {
19157   if (E->isTypeDependent())
19158     return true;
19159   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19160     return E->getType()->isIntegralOrEnumerationType();
19161   return false;
19162 }
19163 
19164 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19165 ExprResult
19166 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19167   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19168          "Unknown Objective-C Boolean value!");
19169   QualType BoolT = Context.ObjCBuiltinBoolTy;
19170   if (!Context.getBOOLDecl()) {
19171     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19172                         Sema::LookupOrdinaryName);
19173     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19174       NamedDecl *ND = Result.getFoundDecl();
19175       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19176         Context.setBOOLDecl(TD);
19177     }
19178   }
19179   if (Context.getBOOLDecl())
19180     BoolT = Context.getBOOLType();
19181   return new (Context)
19182       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19183 }
19184 
19185 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19186     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19187     SourceLocation RParen) {
19188 
19189   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19190 
19191   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19192     return Spec.getPlatform() == Platform;
19193   });
19194 
19195   VersionTuple Version;
19196   if (Spec != AvailSpecs.end())
19197     Version = Spec->getVersion();
19198 
19199   // The use of `@available` in the enclosing function should be analyzed to
19200   // warn when it's used inappropriately (i.e. not if(@available)).
19201   if (getCurFunctionOrMethodDecl())
19202     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19203   else if (getCurBlock() || getCurLambda())
19204     getCurFunction()->HasPotentialAvailabilityViolations = true;
19205 
19206   return new (Context)
19207       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19208 }
19209 
19210 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19211                                     ArrayRef<Expr *> SubExprs, QualType T) {
19212   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
19213   // bogus diagnostics and this trick does not work in C.
19214   // FIXME: use containsErrors() to suppress unwanted diags in C.
19215   if (!Context.getLangOpts().RecoveryAST)
19216     return ExprError();
19217 
19218   if (isSFINAEContext())
19219     return ExprError();
19220 
19221   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19222     // We don't know the concrete type, fallback to dependent type.
19223     T = Context.DependentTy;
19224   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19225 }
19226