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;
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(),
3638                                PP.getSourceManager(), PP.getLangOpts(),
3639                                PP.getTargetInfo(), PP.getDiagnostics());
3640   if (Literal.hadError)
3641     return ExprError();
3642 
3643   if (Literal.hasUDSuffix()) {
3644     // We're building a user-defined literal.
3645     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3646     SourceLocation UDSuffixLoc =
3647       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3648 
3649     // Make sure we're allowed user-defined literals here.
3650     if (!UDLScope)
3651       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3652 
3653     QualType CookedTy;
3654     if (Literal.isFloatingLiteral()) {
3655       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3656       // long double, the literal is treated as a call of the form
3657       //   operator "" X (f L)
3658       CookedTy = Context.LongDoubleTy;
3659     } else {
3660       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3661       // unsigned long long, the literal is treated as a call of the form
3662       //   operator "" X (n ULL)
3663       CookedTy = Context.UnsignedLongLongTy;
3664     }
3665 
3666     DeclarationName OpName =
3667       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3668     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3669     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3670 
3671     SourceLocation TokLoc = Tok.getLocation();
3672 
3673     // Perform literal operator lookup to determine if we're building a raw
3674     // literal or a cooked one.
3675     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3676     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3677                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3678                                   /*AllowStringTemplate*/ false,
3679                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3680     case LOLR_ErrorNoDiagnostic:
3681       // Lookup failure for imaginary constants isn't fatal, there's still the
3682       // GNU extension producing _Complex types.
3683       break;
3684     case LOLR_Error:
3685       return ExprError();
3686     case LOLR_Cooked: {
3687       Expr *Lit;
3688       if (Literal.isFloatingLiteral()) {
3689         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3690       } else {
3691         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3692         if (Literal.GetIntegerValue(ResultVal))
3693           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3694               << /* Unsigned */ 1;
3695         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3696                                      Tok.getLocation());
3697       }
3698       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3699     }
3700 
3701     case LOLR_Raw: {
3702       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3703       // literal is treated as a call of the form
3704       //   operator "" X ("n")
3705       unsigned Length = Literal.getUDSuffixOffset();
3706       QualType StrTy = Context.getConstantArrayType(
3707           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3708           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3709       Expr *Lit = StringLiteral::Create(
3710           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3711           /*Pascal*/false, StrTy, &TokLoc, 1);
3712       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3713     }
3714 
3715     case LOLR_Template: {
3716       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3717       // template), L is treated as a call fo the form
3718       //   operator "" X <'c1', 'c2', ... 'ck'>()
3719       // where n is the source character sequence c1 c2 ... ck.
3720       TemplateArgumentListInfo ExplicitArgs;
3721       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3722       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3723       llvm::APSInt Value(CharBits, CharIsUnsigned);
3724       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3725         Value = TokSpelling[I];
3726         TemplateArgument Arg(Context, Value, Context.CharTy);
3727         TemplateArgumentLocInfo ArgInfo;
3728         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3729       }
3730       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3731                                       &ExplicitArgs);
3732     }
3733     case LOLR_StringTemplate:
3734       llvm_unreachable("unexpected literal operator lookup result");
3735     }
3736   }
3737 
3738   Expr *Res;
3739 
3740   if (Literal.isFixedPointLiteral()) {
3741     QualType Ty;
3742 
3743     if (Literal.isAccum) {
3744       if (Literal.isHalf) {
3745         Ty = Context.ShortAccumTy;
3746       } else if (Literal.isLong) {
3747         Ty = Context.LongAccumTy;
3748       } else {
3749         Ty = Context.AccumTy;
3750       }
3751     } else if (Literal.isFract) {
3752       if (Literal.isHalf) {
3753         Ty = Context.ShortFractTy;
3754       } else if (Literal.isLong) {
3755         Ty = Context.LongFractTy;
3756       } else {
3757         Ty = Context.FractTy;
3758       }
3759     }
3760 
3761     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3762 
3763     bool isSigned = !Literal.isUnsigned;
3764     unsigned scale = Context.getFixedPointScale(Ty);
3765     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3766 
3767     llvm::APInt Val(bit_width, 0, isSigned);
3768     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3769     bool ValIsZero = Val.isNullValue() && !Overflowed;
3770 
3771     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3772     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3773       // Clause 6.4.4 - The value of a constant shall be in the range of
3774       // representable values for its type, with exception for constants of a
3775       // fract type with a value of exactly 1; such a constant shall denote
3776       // the maximal value for the type.
3777       --Val;
3778     else if (Val.ugt(MaxVal) || Overflowed)
3779       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3780 
3781     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3782                                               Tok.getLocation(), scale);
3783   } else if (Literal.isFloatingLiteral()) {
3784     QualType Ty;
3785     if (Literal.isHalf){
3786       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3787         Ty = Context.HalfTy;
3788       else {
3789         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3790         return ExprError();
3791       }
3792     } else if (Literal.isFloat)
3793       Ty = Context.FloatTy;
3794     else if (Literal.isLong)
3795       Ty = Context.LongDoubleTy;
3796     else if (Literal.isFloat16)
3797       Ty = Context.Float16Ty;
3798     else if (Literal.isFloat128)
3799       Ty = Context.Float128Ty;
3800     else
3801       Ty = Context.DoubleTy;
3802 
3803     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3804 
3805     if (Ty == Context.DoubleTy) {
3806       if (getLangOpts().SinglePrecisionConstants) {
3807         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3808         if (BTy->getKind() != BuiltinType::Float) {
3809           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3810         }
3811       } else if (getLangOpts().OpenCL &&
3812                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3813         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3814         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3815         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3816       }
3817     }
3818   } else if (!Literal.isIntegerLiteral()) {
3819     return ExprError();
3820   } else {
3821     QualType Ty;
3822 
3823     // 'long long' is a C99 or C++11 feature.
3824     if (!getLangOpts().C99 && Literal.isLongLong) {
3825       if (getLangOpts().CPlusPlus)
3826         Diag(Tok.getLocation(),
3827              getLangOpts().CPlusPlus11 ?
3828              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3829       else
3830         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3831     }
3832 
3833     // Get the value in the widest-possible width.
3834     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3835     llvm::APInt ResultVal(MaxWidth, 0);
3836 
3837     if (Literal.GetIntegerValue(ResultVal)) {
3838       // If this value didn't fit into uintmax_t, error and force to ull.
3839       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3840           << /* Unsigned */ 1;
3841       Ty = Context.UnsignedLongLongTy;
3842       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3843              "long long is not intmax_t?");
3844     } else {
3845       // If this value fits into a ULL, try to figure out what else it fits into
3846       // according to the rules of C99 6.4.4.1p5.
3847 
3848       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3849       // be an unsigned int.
3850       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3851 
3852       // Check from smallest to largest, picking the smallest type we can.
3853       unsigned Width = 0;
3854 
3855       // Microsoft specific integer suffixes are explicitly sized.
3856       if (Literal.MicrosoftInteger) {
3857         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3858           Width = 8;
3859           Ty = Context.CharTy;
3860         } else {
3861           Width = Literal.MicrosoftInteger;
3862           Ty = Context.getIntTypeForBitwidth(Width,
3863                                              /*Signed=*/!Literal.isUnsigned);
3864         }
3865       }
3866 
3867       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3868         // Are int/unsigned possibilities?
3869         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3870 
3871         // Does it fit in a unsigned int?
3872         if (ResultVal.isIntN(IntSize)) {
3873           // Does it fit in a signed int?
3874           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3875             Ty = Context.IntTy;
3876           else if (AllowUnsigned)
3877             Ty = Context.UnsignedIntTy;
3878           Width = IntSize;
3879         }
3880       }
3881 
3882       // Are long/unsigned long possibilities?
3883       if (Ty.isNull() && !Literal.isLongLong) {
3884         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3885 
3886         // Does it fit in a unsigned long?
3887         if (ResultVal.isIntN(LongSize)) {
3888           // Does it fit in a signed long?
3889           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3890             Ty = Context.LongTy;
3891           else if (AllowUnsigned)
3892             Ty = Context.UnsignedLongTy;
3893           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3894           // is compatible.
3895           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3896             const unsigned LongLongSize =
3897                 Context.getTargetInfo().getLongLongWidth();
3898             Diag(Tok.getLocation(),
3899                  getLangOpts().CPlusPlus
3900                      ? Literal.isLong
3901                            ? diag::warn_old_implicitly_unsigned_long_cxx
3902                            : /*C++98 UB*/ diag::
3903                                  ext_old_implicitly_unsigned_long_cxx
3904                      : diag::warn_old_implicitly_unsigned_long)
3905                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3906                                             : /*will be ill-formed*/ 1);
3907             Ty = Context.UnsignedLongTy;
3908           }
3909           Width = LongSize;
3910         }
3911       }
3912 
3913       // Check long long if needed.
3914       if (Ty.isNull()) {
3915         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3916 
3917         // Does it fit in a unsigned long long?
3918         if (ResultVal.isIntN(LongLongSize)) {
3919           // Does it fit in a signed long long?
3920           // To be compatible with MSVC, hex integer literals ending with the
3921           // LL or i64 suffix are always signed in Microsoft mode.
3922           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3923               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3924             Ty = Context.LongLongTy;
3925           else if (AllowUnsigned)
3926             Ty = Context.UnsignedLongLongTy;
3927           Width = LongLongSize;
3928         }
3929       }
3930 
3931       // If we still couldn't decide a type, we probably have something that
3932       // does not fit in a signed long long, but has no U suffix.
3933       if (Ty.isNull()) {
3934         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3935         Ty = Context.UnsignedLongLongTy;
3936         Width = Context.getTargetInfo().getLongLongWidth();
3937       }
3938 
3939       if (ResultVal.getBitWidth() != Width)
3940         ResultVal = ResultVal.trunc(Width);
3941     }
3942     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3943   }
3944 
3945   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3946   if (Literal.isImaginary) {
3947     Res = new (Context) ImaginaryLiteral(Res,
3948                                         Context.getComplexType(Res->getType()));
3949 
3950     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3951   }
3952   return Res;
3953 }
3954 
3955 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3956   assert(E && "ActOnParenExpr() missing expr");
3957   return new (Context) ParenExpr(L, R, E);
3958 }
3959 
3960 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3961                                          SourceLocation Loc,
3962                                          SourceRange ArgRange) {
3963   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3964   // scalar or vector data type argument..."
3965   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3966   // type (C99 6.2.5p18) or void.
3967   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3968     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3969       << T << ArgRange;
3970     return true;
3971   }
3972 
3973   assert((T->isVoidType() || !T->isIncompleteType()) &&
3974          "Scalar types should always be complete");
3975   return false;
3976 }
3977 
3978 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3979                                            SourceLocation Loc,
3980                                            SourceRange ArgRange,
3981                                            UnaryExprOrTypeTrait TraitKind) {
3982   // Invalid types must be hard errors for SFINAE in C++.
3983   if (S.LangOpts.CPlusPlus)
3984     return true;
3985 
3986   // C99 6.5.3.4p1:
3987   if (T->isFunctionType() &&
3988       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3989        TraitKind == UETT_PreferredAlignOf)) {
3990     // sizeof(function)/alignof(function) is allowed as an extension.
3991     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3992         << getTraitSpelling(TraitKind) << ArgRange;
3993     return false;
3994   }
3995 
3996   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3997   // this is an error (OpenCL v1.1 s6.3.k)
3998   if (T->isVoidType()) {
3999     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4000                                         : diag::ext_sizeof_alignof_void_type;
4001     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4002     return false;
4003   }
4004 
4005   return true;
4006 }
4007 
4008 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4009                                              SourceLocation Loc,
4010                                              SourceRange ArgRange,
4011                                              UnaryExprOrTypeTrait TraitKind) {
4012   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4013   // runtime doesn't allow it.
4014   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4015     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4016       << T << (TraitKind == UETT_SizeOf)
4017       << ArgRange;
4018     return true;
4019   }
4020 
4021   return false;
4022 }
4023 
4024 /// Check whether E is a pointer from a decayed array type (the decayed
4025 /// pointer type is equal to T) and emit a warning if it is.
4026 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4027                                      Expr *E) {
4028   // Don't warn if the operation changed the type.
4029   if (T != E->getType())
4030     return;
4031 
4032   // Now look for array decays.
4033   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4034   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4035     return;
4036 
4037   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4038                                              << ICE->getType()
4039                                              << ICE->getSubExpr()->getType();
4040 }
4041 
4042 /// Check the constraints on expression operands to unary type expression
4043 /// and type traits.
4044 ///
4045 /// Completes any types necessary and validates the constraints on the operand
4046 /// expression. The logic mostly mirrors the type-based overload, but may modify
4047 /// the expression as it completes the type for that expression through template
4048 /// instantiation, etc.
4049 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4050                                             UnaryExprOrTypeTrait ExprKind) {
4051   QualType ExprTy = E->getType();
4052   assert(!ExprTy->isReferenceType());
4053 
4054   bool IsUnevaluatedOperand =
4055       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4056        ExprKind == UETT_PreferredAlignOf);
4057   if (IsUnevaluatedOperand) {
4058     ExprResult Result = CheckUnevaluatedOperand(E);
4059     if (Result.isInvalid())
4060       return true;
4061     E = Result.get();
4062   }
4063 
4064   if (ExprKind == UETT_VecStep)
4065     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4066                                         E->getSourceRange());
4067 
4068   // Explicitly list some types as extensions.
4069   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070                                       E->getSourceRange(), ExprKind))
4071     return false;
4072 
4073   // 'alignof' applied to an expression only requires the base element type of
4074   // the expression to be complete. 'sizeof' requires the expression's type to
4075   // be complete (and will attempt to complete it if it's an array of unknown
4076   // bound).
4077   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4078     if (RequireCompleteSizedType(
4079             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4080             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4081             getTraitSpelling(ExprKind), E->getSourceRange()))
4082       return true;
4083   } else {
4084     if (RequireCompleteSizedExprType(
4085             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4086             getTraitSpelling(ExprKind), E->getSourceRange()))
4087       return true;
4088   }
4089 
4090   // Completing the expression's type may have changed it.
4091   ExprTy = E->getType();
4092   assert(!ExprTy->isReferenceType());
4093 
4094   if (ExprTy->isFunctionType()) {
4095     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4096         << getTraitSpelling(ExprKind) << E->getSourceRange();
4097     return true;
4098   }
4099 
4100   // The operand for sizeof and alignof is in an unevaluated expression context,
4101   // so side effects could result in unintended consequences.
4102   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4103       E->HasSideEffects(Context, false))
4104     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4105 
4106   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4107                                        E->getSourceRange(), ExprKind))
4108     return true;
4109 
4110   if (ExprKind == UETT_SizeOf) {
4111     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4112       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4113         QualType OType = PVD->getOriginalType();
4114         QualType Type = PVD->getType();
4115         if (Type->isPointerType() && OType->isArrayType()) {
4116           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4117             << Type << OType;
4118           Diag(PVD->getLocation(), diag::note_declared_at);
4119         }
4120       }
4121     }
4122 
4123     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4124     // decays into a pointer and returns an unintended result. This is most
4125     // likely a typo for "sizeof(array) op x".
4126     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4127       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4128                                BO->getLHS());
4129       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4130                                BO->getRHS());
4131     }
4132   }
4133 
4134   return false;
4135 }
4136 
4137 /// Check the constraints on operands to unary expression and type
4138 /// traits.
4139 ///
4140 /// This will complete any types necessary, and validate the various constraints
4141 /// on those operands.
4142 ///
4143 /// The UsualUnaryConversions() function is *not* called by this routine.
4144 /// C99 6.3.2.1p[2-4] all state:
4145 ///   Except when it is the operand of the sizeof operator ...
4146 ///
4147 /// C++ [expr.sizeof]p4
4148 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4149 ///   standard conversions are not applied to the operand of sizeof.
4150 ///
4151 /// This policy is followed for all of the unary trait expressions.
4152 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4153                                             SourceLocation OpLoc,
4154                                             SourceRange ExprRange,
4155                                             UnaryExprOrTypeTrait ExprKind) {
4156   if (ExprType->isDependentType())
4157     return false;
4158 
4159   // C++ [expr.sizeof]p2:
4160   //     When applied to a reference or a reference type, the result
4161   //     is the size of the referenced type.
4162   // C++11 [expr.alignof]p3:
4163   //     When alignof is applied to a reference type, the result
4164   //     shall be the alignment of the referenced type.
4165   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4166     ExprType = Ref->getPointeeType();
4167 
4168   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4169   //   When alignof or _Alignof is applied to an array type, the result
4170   //   is the alignment of the element type.
4171   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4172       ExprKind == UETT_OpenMPRequiredSimdAlign)
4173     ExprType = Context.getBaseElementType(ExprType);
4174 
4175   if (ExprKind == UETT_VecStep)
4176     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4177 
4178   // Explicitly list some types as extensions.
4179   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4180                                       ExprKind))
4181     return false;
4182 
4183   if (RequireCompleteSizedType(
4184           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4185           getTraitSpelling(ExprKind), ExprRange))
4186     return true;
4187 
4188   if (ExprType->isFunctionType()) {
4189     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4190         << getTraitSpelling(ExprKind) << ExprRange;
4191     return true;
4192   }
4193 
4194   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4195                                        ExprKind))
4196     return true;
4197 
4198   return false;
4199 }
4200 
4201 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4202   // Cannot know anything else if the expression is dependent.
4203   if (E->isTypeDependent())
4204     return false;
4205 
4206   if (E->getObjectKind() == OK_BitField) {
4207     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4208        << 1 << E->getSourceRange();
4209     return true;
4210   }
4211 
4212   ValueDecl *D = nullptr;
4213   Expr *Inner = E->IgnoreParens();
4214   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4215     D = DRE->getDecl();
4216   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4217     D = ME->getMemberDecl();
4218   }
4219 
4220   // If it's a field, require the containing struct to have a
4221   // complete definition so that we can compute the layout.
4222   //
4223   // This can happen in C++11 onwards, either by naming the member
4224   // in a way that is not transformed into a member access expression
4225   // (in an unevaluated operand, for instance), or by naming the member
4226   // in a trailing-return-type.
4227   //
4228   // For the record, since __alignof__ on expressions is a GCC
4229   // extension, GCC seems to permit this but always gives the
4230   // nonsensical answer 0.
4231   //
4232   // We don't really need the layout here --- we could instead just
4233   // directly check for all the appropriate alignment-lowing
4234   // attributes --- but that would require duplicating a lot of
4235   // logic that just isn't worth duplicating for such a marginal
4236   // use-case.
4237   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4238     // Fast path this check, since we at least know the record has a
4239     // definition if we can find a member of it.
4240     if (!FD->getParent()->isCompleteDefinition()) {
4241       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4242         << E->getSourceRange();
4243       return true;
4244     }
4245 
4246     // Otherwise, if it's a field, and the field doesn't have
4247     // reference type, then it must have a complete type (or be a
4248     // flexible array member, which we explicitly want to
4249     // white-list anyway), which makes the following checks trivial.
4250     if (!FD->getType()->isReferenceType())
4251       return false;
4252   }
4253 
4254   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4255 }
4256 
4257 bool Sema::CheckVecStepExpr(Expr *E) {
4258   E = E->IgnoreParens();
4259 
4260   // Cannot know anything else if the expression is dependent.
4261   if (E->isTypeDependent())
4262     return false;
4263 
4264   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4265 }
4266 
4267 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4268                                         CapturingScopeInfo *CSI) {
4269   assert(T->isVariablyModifiedType());
4270   assert(CSI != nullptr);
4271 
4272   // We're going to walk down into the type and look for VLA expressions.
4273   do {
4274     const Type *Ty = T.getTypePtr();
4275     switch (Ty->getTypeClass()) {
4276 #define TYPE(Class, Base)
4277 #define ABSTRACT_TYPE(Class, Base)
4278 #define NON_CANONICAL_TYPE(Class, Base)
4279 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4280 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4281 #include "clang/AST/TypeNodes.inc"
4282       T = QualType();
4283       break;
4284     // These types are never variably-modified.
4285     case Type::Builtin:
4286     case Type::Complex:
4287     case Type::Vector:
4288     case Type::ExtVector:
4289     case Type::ConstantMatrix:
4290     case Type::Record:
4291     case Type::Enum:
4292     case Type::Elaborated:
4293     case Type::TemplateSpecialization:
4294     case Type::ObjCObject:
4295     case Type::ObjCInterface:
4296     case Type::ObjCObjectPointer:
4297     case Type::ObjCTypeParam:
4298     case Type::Pipe:
4299     case Type::ExtInt:
4300       llvm_unreachable("type class is never variably-modified!");
4301     case Type::Adjusted:
4302       T = cast<AdjustedType>(Ty)->getOriginalType();
4303       break;
4304     case Type::Decayed:
4305       T = cast<DecayedType>(Ty)->getPointeeType();
4306       break;
4307     case Type::Pointer:
4308       T = cast<PointerType>(Ty)->getPointeeType();
4309       break;
4310     case Type::BlockPointer:
4311       T = cast<BlockPointerType>(Ty)->getPointeeType();
4312       break;
4313     case Type::LValueReference:
4314     case Type::RValueReference:
4315       T = cast<ReferenceType>(Ty)->getPointeeType();
4316       break;
4317     case Type::MemberPointer:
4318       T = cast<MemberPointerType>(Ty)->getPointeeType();
4319       break;
4320     case Type::ConstantArray:
4321     case Type::IncompleteArray:
4322       // Losing element qualification here is fine.
4323       T = cast<ArrayType>(Ty)->getElementType();
4324       break;
4325     case Type::VariableArray: {
4326       // Losing element qualification here is fine.
4327       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4328 
4329       // Unknown size indication requires no size computation.
4330       // Otherwise, evaluate and record it.
4331       auto Size = VAT->getSizeExpr();
4332       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4333           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4334         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4335 
4336       T = VAT->getElementType();
4337       break;
4338     }
4339     case Type::FunctionProto:
4340     case Type::FunctionNoProto:
4341       T = cast<FunctionType>(Ty)->getReturnType();
4342       break;
4343     case Type::Paren:
4344     case Type::TypeOf:
4345     case Type::UnaryTransform:
4346     case Type::Attributed:
4347     case Type::SubstTemplateTypeParm:
4348     case Type::MacroQualified:
4349       // Keep walking after single level desugaring.
4350       T = T.getSingleStepDesugaredType(Context);
4351       break;
4352     case Type::Typedef:
4353       T = cast<TypedefType>(Ty)->desugar();
4354       break;
4355     case Type::Decltype:
4356       T = cast<DecltypeType>(Ty)->desugar();
4357       break;
4358     case Type::Auto:
4359     case Type::DeducedTemplateSpecialization:
4360       T = cast<DeducedType>(Ty)->getDeducedType();
4361       break;
4362     case Type::TypeOfExpr:
4363       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4364       break;
4365     case Type::Atomic:
4366       T = cast<AtomicType>(Ty)->getValueType();
4367       break;
4368     }
4369   } while (!T.isNull() && T->isVariablyModifiedType());
4370 }
4371 
4372 /// Build a sizeof or alignof expression given a type operand.
4373 ExprResult
4374 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4375                                      SourceLocation OpLoc,
4376                                      UnaryExprOrTypeTrait ExprKind,
4377                                      SourceRange R) {
4378   if (!TInfo)
4379     return ExprError();
4380 
4381   QualType T = TInfo->getType();
4382 
4383   if (!T->isDependentType() &&
4384       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4385     return ExprError();
4386 
4387   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4388     if (auto *TT = T->getAs<TypedefType>()) {
4389       for (auto I = FunctionScopes.rbegin(),
4390                 E = std::prev(FunctionScopes.rend());
4391            I != E; ++I) {
4392         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4393         if (CSI == nullptr)
4394           break;
4395         DeclContext *DC = nullptr;
4396         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4397           DC = LSI->CallOperator;
4398         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4399           DC = CRSI->TheCapturedDecl;
4400         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4401           DC = BSI->TheDecl;
4402         if (DC) {
4403           if (DC->containsDecl(TT->getDecl()))
4404             break;
4405           captureVariablyModifiedType(Context, T, CSI);
4406         }
4407       }
4408     }
4409   }
4410 
4411   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4412   return new (Context) UnaryExprOrTypeTraitExpr(
4413       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4414 }
4415 
4416 /// Build a sizeof or alignof expression given an expression
4417 /// operand.
4418 ExprResult
4419 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4420                                      UnaryExprOrTypeTrait ExprKind) {
4421   ExprResult PE = CheckPlaceholderExpr(E);
4422   if (PE.isInvalid())
4423     return ExprError();
4424 
4425   E = PE.get();
4426 
4427   // Verify that the operand is valid.
4428   bool isInvalid = false;
4429   if (E->isTypeDependent()) {
4430     // Delay type-checking for type-dependent expressions.
4431   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4432     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4433   } else if (ExprKind == UETT_VecStep) {
4434     isInvalid = CheckVecStepExpr(E);
4435   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4436       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4437       isInvalid = true;
4438   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4439     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4440     isInvalid = true;
4441   } else {
4442     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4443   }
4444 
4445   if (isInvalid)
4446     return ExprError();
4447 
4448   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4449     PE = TransformToPotentiallyEvaluated(E);
4450     if (PE.isInvalid()) return ExprError();
4451     E = PE.get();
4452   }
4453 
4454   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4455   return new (Context) UnaryExprOrTypeTraitExpr(
4456       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4457 }
4458 
4459 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4460 /// expr and the same for @c alignof and @c __alignof
4461 /// Note that the ArgRange is invalid if isType is false.
4462 ExprResult
4463 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4464                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4465                                     void *TyOrEx, SourceRange ArgRange) {
4466   // If error parsing type, ignore.
4467   if (!TyOrEx) return ExprError();
4468 
4469   if (IsType) {
4470     TypeSourceInfo *TInfo;
4471     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4472     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4473   }
4474 
4475   Expr *ArgEx = (Expr *)TyOrEx;
4476   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4477   return Result;
4478 }
4479 
4480 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4481                                      bool IsReal) {
4482   if (V.get()->isTypeDependent())
4483     return S.Context.DependentTy;
4484 
4485   // _Real and _Imag are only l-values for normal l-values.
4486   if (V.get()->getObjectKind() != OK_Ordinary) {
4487     V = S.DefaultLvalueConversion(V.get());
4488     if (V.isInvalid())
4489       return QualType();
4490   }
4491 
4492   // These operators return the element type of a complex type.
4493   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4494     return CT->getElementType();
4495 
4496   // Otherwise they pass through real integer and floating point types here.
4497   if (V.get()->getType()->isArithmeticType())
4498     return V.get()->getType();
4499 
4500   // Test for placeholders.
4501   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4502   if (PR.isInvalid()) return QualType();
4503   if (PR.get() != V.get()) {
4504     V = PR;
4505     return CheckRealImagOperand(S, V, Loc, IsReal);
4506   }
4507 
4508   // Reject anything else.
4509   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4510     << (IsReal ? "__real" : "__imag");
4511   return QualType();
4512 }
4513 
4514 
4515 
4516 ExprResult
4517 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4518                           tok::TokenKind Kind, Expr *Input) {
4519   UnaryOperatorKind Opc;
4520   switch (Kind) {
4521   default: llvm_unreachable("Unknown unary op!");
4522   case tok::plusplus:   Opc = UO_PostInc; break;
4523   case tok::minusminus: Opc = UO_PostDec; break;
4524   }
4525 
4526   // Since this might is a postfix expression, get rid of ParenListExprs.
4527   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4528   if (Result.isInvalid()) return ExprError();
4529   Input = Result.get();
4530 
4531   return BuildUnaryOp(S, OpLoc, Opc, Input);
4532 }
4533 
4534 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4535 ///
4536 /// \return true on error
4537 static bool checkArithmeticOnObjCPointer(Sema &S,
4538                                          SourceLocation opLoc,
4539                                          Expr *op) {
4540   assert(op->getType()->isObjCObjectPointerType());
4541   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4542       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4543     return false;
4544 
4545   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4546     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4547     << op->getSourceRange();
4548   return true;
4549 }
4550 
4551 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4552   auto *BaseNoParens = Base->IgnoreParens();
4553   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4554     return MSProp->getPropertyDecl()->getType()->isArrayType();
4555   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4556 }
4557 
4558 ExprResult
4559 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4560                               Expr *idx, SourceLocation rbLoc) {
4561   if (base && !base->getType().isNull() &&
4562       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4563     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4564                                     SourceLocation(), /*Length*/ nullptr,
4565                                     /*Stride=*/nullptr, rbLoc);
4566 
4567   // Since this might be a postfix expression, get rid of ParenListExprs.
4568   if (isa<ParenListExpr>(base)) {
4569     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4570     if (result.isInvalid()) return ExprError();
4571     base = result.get();
4572   }
4573 
4574   // Check if base and idx form a MatrixSubscriptExpr.
4575   //
4576   // Helper to check for comma expressions, which are not allowed as indices for
4577   // matrix subscript expressions.
4578   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4579     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4580       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4581           << SourceRange(base->getBeginLoc(), rbLoc);
4582       return true;
4583     }
4584     return false;
4585   };
4586   // The matrix subscript operator ([][])is considered a single operator.
4587   // Separating the index expressions by parenthesis is not allowed.
4588   if (base->getType()->isSpecificPlaceholderType(
4589           BuiltinType::IncompleteMatrixIdx) &&
4590       !isa<MatrixSubscriptExpr>(base)) {
4591     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4592         << SourceRange(base->getBeginLoc(), rbLoc);
4593     return ExprError();
4594   }
4595   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4596   // a new MatrixSubscriptExpr.
4597   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4598   if (matSubscriptE) {
4599     if (CheckAndReportCommaError(idx))
4600       return ExprError();
4601 
4602     assert(matSubscriptE->isIncomplete() &&
4603            "base has to be an incomplete matrix subscript");
4604     return CreateBuiltinMatrixSubscriptExpr(
4605         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4606   }
4607   Expr *matrixBase = base;
4608   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4609   if (!IsMSPropertySubscript) {
4610     ExprResult result = CheckPlaceholderExpr(base);
4611     if (!result.isInvalid())
4612       matrixBase = result.get();
4613   }
4614   if (matrixBase->getType()->isMatrixType()) {
4615     if (CheckAndReportCommaError(idx))
4616       return ExprError();
4617 
4618     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4619   }
4620 
4621   // A comma-expression as the index is deprecated in C++2a onwards.
4622   if (getLangOpts().CPlusPlus20 &&
4623       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4624        (isa<CXXOperatorCallExpr>(idx) &&
4625         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4626     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4627       << SourceRange(base->getBeginLoc(), rbLoc);
4628   }
4629 
4630   // Handle any non-overload placeholder types in the base and index
4631   // expressions.  We can't handle overloads here because the other
4632   // operand might be an overloadable type, in which case the overload
4633   // resolution for the operator overload should get the first crack
4634   // at the overload.
4635   if (base->getType()->isNonOverloadPlaceholderType()) {
4636     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4637     if (!IsMSPropertySubscript) {
4638       ExprResult result = CheckPlaceholderExpr(base);
4639       if (result.isInvalid())
4640         return ExprError();
4641       base = result.get();
4642     }
4643   }
4644   if (idx->getType()->isNonOverloadPlaceholderType()) {
4645     ExprResult result = CheckPlaceholderExpr(idx);
4646     if (result.isInvalid()) return ExprError();
4647     idx = result.get();
4648   }
4649 
4650   // Build an unanalyzed expression if either operand is type-dependent.
4651   if (getLangOpts().CPlusPlus &&
4652       (base->isTypeDependent() || idx->isTypeDependent())) {
4653     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4654                                             VK_LValue, OK_Ordinary, rbLoc);
4655   }
4656 
4657   // MSDN, property (C++)
4658   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4659   // This attribute can also be used in the declaration of an empty array in a
4660   // class or structure definition. For example:
4661   // __declspec(property(get=GetX, put=PutX)) int x[];
4662   // The above statement indicates that x[] can be used with one or more array
4663   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4664   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4665   if (IsMSPropertySubscript) {
4666     // Build MS property subscript expression if base is MS property reference
4667     // or MS property subscript.
4668     return new (Context) MSPropertySubscriptExpr(
4669         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4670   }
4671 
4672   // Use C++ overloaded-operator rules if either operand has record
4673   // type.  The spec says to do this if either type is *overloadable*,
4674   // but enum types can't declare subscript operators or conversion
4675   // operators, so there's nothing interesting for overload resolution
4676   // to do if there aren't any record types involved.
4677   //
4678   // ObjC pointers have their own subscripting logic that is not tied
4679   // to overload resolution and so should not take this path.
4680   if (getLangOpts().CPlusPlus &&
4681       (base->getType()->isRecordType() ||
4682        (!base->getType()->isObjCObjectPointerType() &&
4683         idx->getType()->isRecordType()))) {
4684     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4685   }
4686 
4687   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4688 
4689   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4690     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4691 
4692   return Res;
4693 }
4694 
4695 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4696   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4697   InitializationKind Kind =
4698       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4699   InitializationSequence InitSeq(*this, Entity, Kind, E);
4700   return InitSeq.Perform(*this, Entity, Kind, E);
4701 }
4702 
4703 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4704                                                   Expr *ColumnIdx,
4705                                                   SourceLocation RBLoc) {
4706   ExprResult BaseR = CheckPlaceholderExpr(Base);
4707   if (BaseR.isInvalid())
4708     return BaseR;
4709   Base = BaseR.get();
4710 
4711   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4712   if (RowR.isInvalid())
4713     return RowR;
4714   RowIdx = RowR.get();
4715 
4716   if (!ColumnIdx)
4717     return new (Context) MatrixSubscriptExpr(
4718         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4719 
4720   // Build an unanalyzed expression if any of the operands is type-dependent.
4721   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4722       ColumnIdx->isTypeDependent())
4723     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4724                                              Context.DependentTy, RBLoc);
4725 
4726   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4727   if (ColumnR.isInvalid())
4728     return ColumnR;
4729   ColumnIdx = ColumnR.get();
4730 
4731   // Check that IndexExpr is an integer expression. If it is a constant
4732   // expression, check that it is less than Dim (= the number of elements in the
4733   // corresponding dimension).
4734   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4735                           bool IsColumnIdx) -> Expr * {
4736     if (!IndexExpr->getType()->isIntegerType() &&
4737         !IndexExpr->isTypeDependent()) {
4738       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4739           << IsColumnIdx;
4740       return nullptr;
4741     }
4742 
4743     if (Optional<llvm::APSInt> Idx =
4744             IndexExpr->getIntegerConstantExpr(Context)) {
4745       if ((*Idx < 0 || *Idx >= Dim)) {
4746         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4747             << IsColumnIdx << Dim;
4748         return nullptr;
4749       }
4750     }
4751 
4752     ExprResult ConvExpr =
4753         tryConvertExprToType(IndexExpr, Context.getSizeType());
4754     assert(!ConvExpr.isInvalid() &&
4755            "should be able to convert any integer type to size type");
4756     return ConvExpr.get();
4757   };
4758 
4759   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762   if (!RowIdx || !ColumnIdx)
4763     return ExprError();
4764 
4765   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766                                            MTy->getElementType(), RBLoc);
4767 }
4768 
4769 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4772 
4773   // For expressions like `&(*s).b`, the base is recorded and what should be
4774   // checked.
4775   const MemberExpr *Member = nullptr;
4776   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4778 
4779   LastRecord.PossibleDerefs.erase(StrippedExpr);
4780 }
4781 
4782 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783   QualType ResultTy = E->getType();
4784   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4785 
4786   // Bail if the element is an array since it is not memory access.
4787   if (isa<ArrayType>(ResultTy))
4788     return;
4789 
4790   if (ResultTy->hasAttr(attr::NoDeref)) {
4791     LastRecord.PossibleDerefs.insert(E);
4792     return;
4793   }
4794 
4795   // Check if the base type is a pointer to a member access of a struct
4796   // marked with noderef.
4797   const Expr *Base = E->getBase();
4798   QualType BaseTy = Base->getType();
4799   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800     // Not a pointer access
4801     return;
4802 
4803   const MemberExpr *Member = nullptr;
4804   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4805          Member->isArrow())
4806     Base = Member->getBase();
4807 
4808   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810       LastRecord.PossibleDerefs.insert(E);
4811   }
4812 }
4813 
4814 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4815                                           Expr *LowerBound,
4816                                           SourceLocation ColonLocFirst,
4817                                           SourceLocation ColonLocSecond,
4818                                           Expr *Length, Expr *Stride,
4819                                           SourceLocation RBLoc) {
4820   if (Base->getType()->isPlaceholderType() &&
4821       !Base->getType()->isSpecificPlaceholderType(
4822           BuiltinType::OMPArraySection)) {
4823     ExprResult Result = CheckPlaceholderExpr(Base);
4824     if (Result.isInvalid())
4825       return ExprError();
4826     Base = Result.get();
4827   }
4828   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830     if (Result.isInvalid())
4831       return ExprError();
4832     Result = DefaultLvalueConversion(Result.get());
4833     if (Result.isInvalid())
4834       return ExprError();
4835     LowerBound = Result.get();
4836   }
4837   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838     ExprResult Result = CheckPlaceholderExpr(Length);
4839     if (Result.isInvalid())
4840       return ExprError();
4841     Result = DefaultLvalueConversion(Result.get());
4842     if (Result.isInvalid())
4843       return ExprError();
4844     Length = Result.get();
4845   }
4846   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847     ExprResult Result = CheckPlaceholderExpr(Stride);
4848     if (Result.isInvalid())
4849       return ExprError();
4850     Result = DefaultLvalueConversion(Result.get());
4851     if (Result.isInvalid())
4852       return ExprError();
4853     Stride = Result.get();
4854   }
4855 
4856   // Build an unanalyzed expression if either operand is type-dependent.
4857   if (Base->isTypeDependent() ||
4858       (LowerBound &&
4859        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862     return new (Context) OMPArraySectionExpr(
4863         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4865   }
4866 
4867   // Perform default conversions.
4868   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4869   QualType ResultTy;
4870   if (OriginalTy->isAnyPointerType()) {
4871     ResultTy = OriginalTy->getPointeeType();
4872   } else if (OriginalTy->isArrayType()) {
4873     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4874   } else {
4875     return ExprError(
4876         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877         << Base->getSourceRange());
4878   }
4879   // C99 6.5.2.1p1
4880   if (LowerBound) {
4881     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4882                                                       LowerBound);
4883     if (Res.isInvalid())
4884       return ExprError(Diag(LowerBound->getExprLoc(),
4885                             diag::err_omp_typecheck_section_not_integer)
4886                        << 0 << LowerBound->getSourceRange());
4887     LowerBound = Res.get();
4888 
4889     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892           << 0 << LowerBound->getSourceRange();
4893   }
4894   if (Length) {
4895     auto Res =
4896         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897     if (Res.isInvalid())
4898       return ExprError(Diag(Length->getExprLoc(),
4899                             diag::err_omp_typecheck_section_not_integer)
4900                        << 1 << Length->getSourceRange());
4901     Length = Res.get();
4902 
4903     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906           << 1 << Length->getSourceRange();
4907   }
4908   if (Stride) {
4909     ExprResult Res =
4910         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911     if (Res.isInvalid())
4912       return ExprError(Diag(Stride->getExprLoc(),
4913                             diag::err_omp_typecheck_section_not_integer)
4914                        << 1 << Stride->getSourceRange());
4915     Stride = Res.get();
4916 
4917     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920           << 1 << Stride->getSourceRange();
4921   }
4922 
4923   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925   // type. Note that functions are not objects, and that (in C99 parlance)
4926   // incomplete types are not object types.
4927   if (ResultTy->isFunctionType()) {
4928     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929         << ResultTy << Base->getSourceRange();
4930     return ExprError();
4931   }
4932 
4933   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934                           diag::err_omp_section_incomplete_type, Base))
4935     return ExprError();
4936 
4937   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938     Expr::EvalResult Result;
4939     if (LowerBound->EvaluateAsInt(Result, Context)) {
4940       // OpenMP 5.0, [2.1.5 Array Sections]
4941       // The array section must be a subset of the original array.
4942       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943       if (LowerBoundValue.isNegative()) {
4944         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945             << LowerBound->getSourceRange();
4946         return ExprError();
4947       }
4948     }
4949   }
4950 
4951   if (Length) {
4952     Expr::EvalResult Result;
4953     if (Length->EvaluateAsInt(Result, Context)) {
4954       // OpenMP 5.0, [2.1.5 Array Sections]
4955       // The length must evaluate to non-negative integers.
4956       llvm::APSInt LengthValue = Result.Val.getInt();
4957       if (LengthValue.isNegative()) {
4958         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960             << Length->getSourceRange();
4961         return ExprError();
4962       }
4963     }
4964   } else if (ColonLocFirst.isValid() &&
4965              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966                                       !OriginalTy->isVariableArrayType()))) {
4967     // OpenMP 5.0, [2.1.5 Array Sections]
4968     // When the size of the array dimension is not known, the length must be
4969     // specified explicitly.
4970     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4972     return ExprError();
4973   }
4974 
4975   if (Stride) {
4976     Expr::EvalResult Result;
4977     if (Stride->EvaluateAsInt(Result, Context)) {
4978       // OpenMP 5.0, [2.1.5 Array Sections]
4979       // The stride must evaluate to a positive integer.
4980       llvm::APSInt StrideValue = Result.Val.getInt();
4981       if (!StrideValue.isStrictlyPositive()) {
4982         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984             << Stride->getSourceRange();
4985         return ExprError();
4986       }
4987     }
4988   }
4989 
4990   if (!Base->getType()->isSpecificPlaceholderType(
4991           BuiltinType::OMPArraySection)) {
4992     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993     if (Result.isInvalid())
4994       return ExprError();
4995     Base = Result.get();
4996   }
4997   return new (Context) OMPArraySectionExpr(
4998       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5000 }
5001 
5002 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003                                           SourceLocation RParenLoc,
5004                                           ArrayRef<Expr *> Dims,
5005                                           ArrayRef<SourceRange> Brackets) {
5006   if (Base->getType()->isPlaceholderType()) {
5007     ExprResult Result = CheckPlaceholderExpr(Base);
5008     if (Result.isInvalid())
5009       return ExprError();
5010     Result = DefaultLvalueConversion(Result.get());
5011     if (Result.isInvalid())
5012       return ExprError();
5013     Base = Result.get();
5014   }
5015   QualType BaseTy = Base->getType();
5016   // Delay analysis of the types/expressions if instantiation/specialization is
5017   // required.
5018   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020                                        LParenLoc, RParenLoc, Dims, Brackets);
5021   if (!BaseTy->isPointerType() ||
5022       (!Base->isTypeDependent() &&
5023        BaseTy->getPointeeType()->isIncompleteType()))
5024     return ExprError(Diag(Base->getExprLoc(),
5025                           diag::err_omp_non_pointer_type_array_shaping_base)
5026                      << Base->getSourceRange());
5027 
5028   SmallVector<Expr *, 4> NewDims;
5029   bool ErrorFound = false;
5030   for (Expr *Dim : Dims) {
5031     if (Dim->getType()->isPlaceholderType()) {
5032       ExprResult Result = CheckPlaceholderExpr(Dim);
5033       if (Result.isInvalid()) {
5034         ErrorFound = true;
5035         continue;
5036       }
5037       Result = DefaultLvalueConversion(Result.get());
5038       if (Result.isInvalid()) {
5039         ErrorFound = true;
5040         continue;
5041       }
5042       Dim = Result.get();
5043     }
5044     if (!Dim->isTypeDependent()) {
5045       ExprResult Result =
5046           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047       if (Result.isInvalid()) {
5048         ErrorFound = true;
5049         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050             << Dim->getSourceRange();
5051         continue;
5052       }
5053       Dim = Result.get();
5054       Expr::EvalResult EvResult;
5055       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056         // OpenMP 5.0, [2.1.4 Array Shaping]
5057         // Each si is an integral type expression that must evaluate to a
5058         // positive integer.
5059         llvm::APSInt Value = EvResult.Val.getInt();
5060         if (!Value.isStrictlyPositive()) {
5061           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063               << Dim->getSourceRange();
5064           ErrorFound = true;
5065           continue;
5066         }
5067       }
5068     }
5069     NewDims.push_back(Dim);
5070   }
5071   if (ErrorFound)
5072     return ExprError();
5073   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074                                      LParenLoc, RParenLoc, NewDims, Brackets);
5075 }
5076 
5077 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078                                       SourceLocation LLoc, SourceLocation RLoc,
5079                                       ArrayRef<OMPIteratorData> Data) {
5080   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081   bool IsCorrect = true;
5082   for (const OMPIteratorData &D : Data) {
5083     TypeSourceInfo *TInfo = nullptr;
5084     SourceLocation StartLoc;
5085     QualType DeclTy;
5086     if (!D.Type.getAsOpaquePtr()) {
5087       // OpenMP 5.0, 2.1.6 Iterators
5088       // In an iterator-specifier, if the iterator-type is not specified then
5089       // the type of that iterator is of int type.
5090       DeclTy = Context.IntTy;
5091       StartLoc = D.DeclIdentLoc;
5092     } else {
5093       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5095     }
5096 
5097     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098                              DeclTy->containsUnexpandedParameterPack() ||
5099                              DeclTy->isInstantiationDependentType();
5100     if (!IsDeclTyDependent) {
5101       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103         // The iterator-type must be an integral or pointer type.
5104         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5105             << DeclTy;
5106         IsCorrect = false;
5107         continue;
5108       }
5109       if (DeclTy.isConstant(Context)) {
5110         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111         // The iterator-type must not be const qualified.
5112         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113             << DeclTy;
5114         IsCorrect = false;
5115         continue;
5116       }
5117     }
5118 
5119     // Iterator declaration.
5120     assert(D.DeclIdent && "Identifier expected.");
5121     // Always try to create iterator declarator to avoid extra error messages
5122     // about unknown declarations use.
5123     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124                                D.DeclIdent, DeclTy, TInfo, SC_None);
5125     VD->setImplicit();
5126     if (S) {
5127       // Check for conflicting previous declaration.
5128       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130                             ForVisibleRedeclaration);
5131       Previous.suppressDiagnostics();
5132       LookupName(Previous, S);
5133 
5134       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135                            /*AllowInlineNamespace=*/false);
5136       if (!Previous.empty()) {
5137         NamedDecl *Old = Previous.getRepresentativeDecl();
5138         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139         Diag(Old->getLocation(), diag::note_previous_definition);
5140       } else {
5141         PushOnScopeChains(VD, S);
5142       }
5143     } else {
5144       CurContext->addDecl(VD);
5145     }
5146     Expr *Begin = D.Range.Begin;
5147     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148       ExprResult BeginRes =
5149           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150       Begin = BeginRes.get();
5151     }
5152     Expr *End = D.Range.End;
5153     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5155       End = EndRes.get();
5156     }
5157     Expr *Step = D.Range.Step;
5158     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159       if (!Step->getType()->isIntegralType(Context)) {
5160         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161             << Step << Step->getSourceRange();
5162         IsCorrect = false;
5163         continue;
5164       }
5165       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5166       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5167       // If the step expression of a range-specification equals zero, the
5168       // behavior is unspecified.
5169       if (Result && Result->isNullValue()) {
5170         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5171             << Step << Step->getSourceRange();
5172         IsCorrect = false;
5173         continue;
5174       }
5175     }
5176     if (!Begin || !End || !IsCorrect) {
5177       IsCorrect = false;
5178       continue;
5179     }
5180     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5181     IDElem.IteratorDecl = VD;
5182     IDElem.AssignmentLoc = D.AssignLoc;
5183     IDElem.Range.Begin = Begin;
5184     IDElem.Range.End = End;
5185     IDElem.Range.Step = Step;
5186     IDElem.ColonLoc = D.ColonLoc;
5187     IDElem.SecondColonLoc = D.SecColonLoc;
5188   }
5189   if (!IsCorrect) {
5190     // Invalidate all created iterator declarations if error is found.
5191     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5192       if (Decl *ID = D.IteratorDecl)
5193         ID->setInvalidDecl();
5194     }
5195     return ExprError();
5196   }
5197   SmallVector<OMPIteratorHelperData, 4> Helpers;
5198   if (!CurContext->isDependentContext()) {
5199     // Build number of ityeration for each iteration range.
5200     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5201     // ((Begini-Stepi-1-Endi) / -Stepi);
5202     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5203       // (Endi - Begini)
5204       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5205                                           D.Range.Begin);
5206       if(!Res.isUsable()) {
5207         IsCorrect = false;
5208         continue;
5209       }
5210       ExprResult St, St1;
5211       if (D.Range.Step) {
5212         St = D.Range.Step;
5213         // (Endi - Begini) + Stepi
5214         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5215         if (!Res.isUsable()) {
5216           IsCorrect = false;
5217           continue;
5218         }
5219         // (Endi - Begini) + Stepi - 1
5220         Res =
5221             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5222                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5223         if (!Res.isUsable()) {
5224           IsCorrect = false;
5225           continue;
5226         }
5227         // ((Endi - Begini) + Stepi - 1) / Stepi
5228         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5229         if (!Res.isUsable()) {
5230           IsCorrect = false;
5231           continue;
5232         }
5233         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5234         // (Begini - Endi)
5235         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5236                                              D.Range.Begin, D.Range.End);
5237         if (!Res1.isUsable()) {
5238           IsCorrect = false;
5239           continue;
5240         }
5241         // (Begini - Endi) - Stepi
5242         Res1 =
5243             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5244         if (!Res1.isUsable()) {
5245           IsCorrect = false;
5246           continue;
5247         }
5248         // (Begini - Endi) - Stepi - 1
5249         Res1 =
5250             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5251                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5252         if (!Res1.isUsable()) {
5253           IsCorrect = false;
5254           continue;
5255         }
5256         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5257         Res1 =
5258             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5259         if (!Res1.isUsable()) {
5260           IsCorrect = false;
5261           continue;
5262         }
5263         // Stepi > 0.
5264         ExprResult CmpRes =
5265             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5266                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5267         if (!CmpRes.isUsable()) {
5268           IsCorrect = false;
5269           continue;
5270         }
5271         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5272                                  Res.get(), Res1.get());
5273         if (!Res.isUsable()) {
5274           IsCorrect = false;
5275           continue;
5276         }
5277       }
5278       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5279       if (!Res.isUsable()) {
5280         IsCorrect = false;
5281         continue;
5282       }
5283 
5284       // Build counter update.
5285       // Build counter.
5286       auto *CounterVD =
5287           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5288                           D.IteratorDecl->getBeginLoc(), nullptr,
5289                           Res.get()->getType(), nullptr, SC_None);
5290       CounterVD->setImplicit();
5291       ExprResult RefRes =
5292           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5293                            D.IteratorDecl->getBeginLoc());
5294       // Build counter update.
5295       // I = Begini + counter * Stepi;
5296       ExprResult UpdateRes;
5297       if (D.Range.Step) {
5298         UpdateRes = CreateBuiltinBinOp(
5299             D.AssignmentLoc, BO_Mul,
5300             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5301       } else {
5302         UpdateRes = DefaultLvalueConversion(RefRes.get());
5303       }
5304       if (!UpdateRes.isUsable()) {
5305         IsCorrect = false;
5306         continue;
5307       }
5308       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5309                                      UpdateRes.get());
5310       if (!UpdateRes.isUsable()) {
5311         IsCorrect = false;
5312         continue;
5313       }
5314       ExprResult VDRes =
5315           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5316                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5317                            D.IteratorDecl->getBeginLoc());
5318       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5319                                      UpdateRes.get());
5320       if (!UpdateRes.isUsable()) {
5321         IsCorrect = false;
5322         continue;
5323       }
5324       UpdateRes =
5325           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5326       if (!UpdateRes.isUsable()) {
5327         IsCorrect = false;
5328         continue;
5329       }
5330       ExprResult CounterUpdateRes =
5331           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5332       if (!CounterUpdateRes.isUsable()) {
5333         IsCorrect = false;
5334         continue;
5335       }
5336       CounterUpdateRes =
5337           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5338       if (!CounterUpdateRes.isUsable()) {
5339         IsCorrect = false;
5340         continue;
5341       }
5342       OMPIteratorHelperData &HD = Helpers.emplace_back();
5343       HD.CounterVD = CounterVD;
5344       HD.Upper = Res.get();
5345       HD.Update = UpdateRes.get();
5346       HD.CounterUpdate = CounterUpdateRes.get();
5347     }
5348   } else {
5349     Helpers.assign(ID.size(), {});
5350   }
5351   if (!IsCorrect) {
5352     // Invalidate all created iterator declarations if error is found.
5353     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5354       if (Decl *ID = D.IteratorDecl)
5355         ID->setInvalidDecl();
5356     }
5357     return ExprError();
5358   }
5359   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5360                                  LLoc, RLoc, ID, Helpers);
5361 }
5362 
5363 ExprResult
5364 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5365                                       Expr *Idx, SourceLocation RLoc) {
5366   Expr *LHSExp = Base;
5367   Expr *RHSExp = Idx;
5368 
5369   ExprValueKind VK = VK_LValue;
5370   ExprObjectKind OK = OK_Ordinary;
5371 
5372   // Per C++ core issue 1213, the result is an xvalue if either operand is
5373   // a non-lvalue array, and an lvalue otherwise.
5374   if (getLangOpts().CPlusPlus11) {
5375     for (auto *Op : {LHSExp, RHSExp}) {
5376       Op = Op->IgnoreImplicit();
5377       if (Op->getType()->isArrayType() && !Op->isLValue())
5378         VK = VK_XValue;
5379     }
5380   }
5381 
5382   // Perform default conversions.
5383   if (!LHSExp->getType()->getAs<VectorType>()) {
5384     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5385     if (Result.isInvalid())
5386       return ExprError();
5387     LHSExp = Result.get();
5388   }
5389   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5390   if (Result.isInvalid())
5391     return ExprError();
5392   RHSExp = Result.get();
5393 
5394   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5395 
5396   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5397   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5398   // in the subscript position. As a result, we need to derive the array base
5399   // and index from the expression types.
5400   Expr *BaseExpr, *IndexExpr;
5401   QualType ResultType;
5402   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5403     BaseExpr = LHSExp;
5404     IndexExpr = RHSExp;
5405     ResultType = Context.DependentTy;
5406   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5407     BaseExpr = LHSExp;
5408     IndexExpr = RHSExp;
5409     ResultType = PTy->getPointeeType();
5410   } else if (const ObjCObjectPointerType *PTy =
5411                LHSTy->getAs<ObjCObjectPointerType>()) {
5412     BaseExpr = LHSExp;
5413     IndexExpr = RHSExp;
5414 
5415     // Use custom logic if this should be the pseudo-object subscript
5416     // expression.
5417     if (!LangOpts.isSubscriptPointerArithmetic())
5418       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5419                                           nullptr);
5420 
5421     ResultType = PTy->getPointeeType();
5422   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5423      // Handle the uncommon case of "123[Ptr]".
5424     BaseExpr = RHSExp;
5425     IndexExpr = LHSExp;
5426     ResultType = PTy->getPointeeType();
5427   } else if (const ObjCObjectPointerType *PTy =
5428                RHSTy->getAs<ObjCObjectPointerType>()) {
5429      // Handle the uncommon case of "123[Ptr]".
5430     BaseExpr = RHSExp;
5431     IndexExpr = LHSExp;
5432     ResultType = PTy->getPointeeType();
5433     if (!LangOpts.isSubscriptPointerArithmetic()) {
5434       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5435         << ResultType << BaseExpr->getSourceRange();
5436       return ExprError();
5437     }
5438   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5439     BaseExpr = LHSExp;    // vectors: V[123]
5440     IndexExpr = RHSExp;
5441     // We apply C++ DR1213 to vector subscripting too.
5442     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5443       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5444       if (Materialized.isInvalid())
5445         return ExprError();
5446       LHSExp = Materialized.get();
5447     }
5448     VK = LHSExp->getValueKind();
5449     if (VK != VK_RValue)
5450       OK = OK_VectorComponent;
5451 
5452     ResultType = VTy->getElementType();
5453     QualType BaseType = BaseExpr->getType();
5454     Qualifiers BaseQuals = BaseType.getQualifiers();
5455     Qualifiers MemberQuals = ResultType.getQualifiers();
5456     Qualifiers Combined = BaseQuals + MemberQuals;
5457     if (Combined != MemberQuals)
5458       ResultType = Context.getQualifiedType(ResultType, Combined);
5459   } else if (LHSTy->isArrayType()) {
5460     // If we see an array that wasn't promoted by
5461     // DefaultFunctionArrayLvalueConversion, it must be an array that
5462     // wasn't promoted because of the C90 rule that doesn't
5463     // allow promoting non-lvalue arrays.  Warn, then
5464     // force the promotion here.
5465     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5466         << LHSExp->getSourceRange();
5467     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5468                                CK_ArrayToPointerDecay).get();
5469     LHSTy = LHSExp->getType();
5470 
5471     BaseExpr = LHSExp;
5472     IndexExpr = RHSExp;
5473     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5474   } else if (RHSTy->isArrayType()) {
5475     // Same as previous, except for 123[f().a] case
5476     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5477         << RHSExp->getSourceRange();
5478     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5479                                CK_ArrayToPointerDecay).get();
5480     RHSTy = RHSExp->getType();
5481 
5482     BaseExpr = RHSExp;
5483     IndexExpr = LHSExp;
5484     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5485   } else {
5486     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5487        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5488   }
5489   // C99 6.5.2.1p1
5490   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5491     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5492                      << IndexExpr->getSourceRange());
5493 
5494   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5495        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5496          && !IndexExpr->isTypeDependent())
5497     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5498 
5499   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5500   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5501   // type. Note that Functions are not objects, and that (in C99 parlance)
5502   // incomplete types are not object types.
5503   if (ResultType->isFunctionType()) {
5504     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5505         << ResultType << BaseExpr->getSourceRange();
5506     return ExprError();
5507   }
5508 
5509   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5510     // GNU extension: subscripting on pointer to void
5511     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5512       << BaseExpr->getSourceRange();
5513 
5514     // C forbids expressions of unqualified void type from being l-values.
5515     // See IsCForbiddenLValueType.
5516     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5517   } else if (!ResultType->isDependentType() &&
5518              RequireCompleteSizedType(
5519                  LLoc, ResultType,
5520                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5521     return ExprError();
5522 
5523   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5524          !ResultType.isCForbiddenLValueType());
5525 
5526   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5527       FunctionScopes.size() > 1) {
5528     if (auto *TT =
5529             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5530       for (auto I = FunctionScopes.rbegin(),
5531                 E = std::prev(FunctionScopes.rend());
5532            I != E; ++I) {
5533         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5534         if (CSI == nullptr)
5535           break;
5536         DeclContext *DC = nullptr;
5537         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5538           DC = LSI->CallOperator;
5539         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5540           DC = CRSI->TheCapturedDecl;
5541         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5542           DC = BSI->TheDecl;
5543         if (DC) {
5544           if (DC->containsDecl(TT->getDecl()))
5545             break;
5546           captureVariablyModifiedType(
5547               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5548         }
5549       }
5550     }
5551   }
5552 
5553   return new (Context)
5554       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5555 }
5556 
5557 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5558                                   ParmVarDecl *Param) {
5559   if (Param->hasUnparsedDefaultArg()) {
5560     // If we've already cleared out the location for the default argument,
5561     // that means we're parsing it right now.
5562     if (!UnparsedDefaultArgLocs.count(Param)) {
5563       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5564       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5565       Param->setInvalidDecl();
5566       return true;
5567     }
5568 
5569     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5570         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5571     Diag(UnparsedDefaultArgLocs[Param],
5572          diag::note_default_argument_declared_here);
5573     return true;
5574   }
5575 
5576   if (Param->hasUninstantiatedDefaultArg() &&
5577       InstantiateDefaultArgument(CallLoc, FD, Param))
5578     return true;
5579 
5580   assert(Param->hasInit() && "default argument but no initializer?");
5581 
5582   // If the default expression creates temporaries, we need to
5583   // push them to the current stack of expression temporaries so they'll
5584   // be properly destroyed.
5585   // FIXME: We should really be rebuilding the default argument with new
5586   // bound temporaries; see the comment in PR5810.
5587   // We don't need to do that with block decls, though, because
5588   // blocks in default argument expression can never capture anything.
5589   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5590     // Set the "needs cleanups" bit regardless of whether there are
5591     // any explicit objects.
5592     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5593 
5594     // Append all the objects to the cleanup list.  Right now, this
5595     // should always be a no-op, because blocks in default argument
5596     // expressions should never be able to capture anything.
5597     assert(!Init->getNumObjects() &&
5598            "default argument expression has capturing blocks?");
5599   }
5600 
5601   // We already type-checked the argument, so we know it works.
5602   // Just mark all of the declarations in this potentially-evaluated expression
5603   // as being "referenced".
5604   EnterExpressionEvaluationContext EvalContext(
5605       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5606   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5607                                    /*SkipLocalVariables=*/true);
5608   return false;
5609 }
5610 
5611 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5612                                         FunctionDecl *FD, ParmVarDecl *Param) {
5613   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5614   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5615     return ExprError();
5616   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5617 }
5618 
5619 Sema::VariadicCallType
5620 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5621                           Expr *Fn) {
5622   if (Proto && Proto->isVariadic()) {
5623     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5624       return VariadicConstructor;
5625     else if (Fn && Fn->getType()->isBlockPointerType())
5626       return VariadicBlock;
5627     else if (FDecl) {
5628       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5629         if (Method->isInstance())
5630           return VariadicMethod;
5631     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5632       return VariadicMethod;
5633     return VariadicFunction;
5634   }
5635   return VariadicDoesNotApply;
5636 }
5637 
5638 namespace {
5639 class FunctionCallCCC final : public FunctionCallFilterCCC {
5640 public:
5641   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5642                   unsigned NumArgs, MemberExpr *ME)
5643       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5644         FunctionName(FuncName) {}
5645 
5646   bool ValidateCandidate(const TypoCorrection &candidate) override {
5647     if (!candidate.getCorrectionSpecifier() ||
5648         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5649       return false;
5650     }
5651 
5652     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5653   }
5654 
5655   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5656     return std::make_unique<FunctionCallCCC>(*this);
5657   }
5658 
5659 private:
5660   const IdentifierInfo *const FunctionName;
5661 };
5662 }
5663 
5664 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5665                                                FunctionDecl *FDecl,
5666                                                ArrayRef<Expr *> Args) {
5667   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5668   DeclarationName FuncName = FDecl->getDeclName();
5669   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5670 
5671   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5672   if (TypoCorrection Corrected = S.CorrectTypo(
5673           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5674           S.getScopeForContext(S.CurContext), nullptr, CCC,
5675           Sema::CTK_ErrorRecovery)) {
5676     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5677       if (Corrected.isOverloaded()) {
5678         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5679         OverloadCandidateSet::iterator Best;
5680         for (NamedDecl *CD : Corrected) {
5681           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5682             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5683                                    OCS);
5684         }
5685         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5686         case OR_Success:
5687           ND = Best->FoundDecl;
5688           Corrected.setCorrectionDecl(ND);
5689           break;
5690         default:
5691           break;
5692         }
5693       }
5694       ND = ND->getUnderlyingDecl();
5695       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5696         return Corrected;
5697     }
5698   }
5699   return TypoCorrection();
5700 }
5701 
5702 /// ConvertArgumentsForCall - Converts the arguments specified in
5703 /// Args/NumArgs to the parameter types of the function FDecl with
5704 /// function prototype Proto. Call is the call expression itself, and
5705 /// Fn is the function expression. For a C++ member function, this
5706 /// routine does not attempt to convert the object argument. Returns
5707 /// true if the call is ill-formed.
5708 bool
5709 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5710                               FunctionDecl *FDecl,
5711                               const FunctionProtoType *Proto,
5712                               ArrayRef<Expr *> Args,
5713                               SourceLocation RParenLoc,
5714                               bool IsExecConfig) {
5715   // Bail out early if calling a builtin with custom typechecking.
5716   if (FDecl)
5717     if (unsigned ID = FDecl->getBuiltinID())
5718       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5719         return false;
5720 
5721   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5722   // assignment, to the types of the corresponding parameter, ...
5723   unsigned NumParams = Proto->getNumParams();
5724   bool Invalid = false;
5725   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5726   unsigned FnKind = Fn->getType()->isBlockPointerType()
5727                        ? 1 /* block */
5728                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5729                                        : 0 /* function */);
5730 
5731   // If too few arguments are available (and we don't have default
5732   // arguments for the remaining parameters), don't make the call.
5733   if (Args.size() < NumParams) {
5734     if (Args.size() < MinArgs) {
5735       TypoCorrection TC;
5736       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5737         unsigned diag_id =
5738             MinArgs == NumParams && !Proto->isVariadic()
5739                 ? diag::err_typecheck_call_too_few_args_suggest
5740                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5741         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5742                                         << static_cast<unsigned>(Args.size())
5743                                         << TC.getCorrectionRange());
5744       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5745         Diag(RParenLoc,
5746              MinArgs == NumParams && !Proto->isVariadic()
5747                  ? diag::err_typecheck_call_too_few_args_one
5748                  : diag::err_typecheck_call_too_few_args_at_least_one)
5749             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5750       else
5751         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5752                             ? diag::err_typecheck_call_too_few_args
5753                             : diag::err_typecheck_call_too_few_args_at_least)
5754             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5755             << Fn->getSourceRange();
5756 
5757       // Emit the location of the prototype.
5758       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5759         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5760 
5761       return true;
5762     }
5763     // We reserve space for the default arguments when we create
5764     // the call expression, before calling ConvertArgumentsForCall.
5765     assert((Call->getNumArgs() == NumParams) &&
5766            "We should have reserved space for the default arguments before!");
5767   }
5768 
5769   // If too many are passed and not variadic, error on the extras and drop
5770   // them.
5771   if (Args.size() > NumParams) {
5772     if (!Proto->isVariadic()) {
5773       TypoCorrection TC;
5774       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5775         unsigned diag_id =
5776             MinArgs == NumParams && !Proto->isVariadic()
5777                 ? diag::err_typecheck_call_too_many_args_suggest
5778                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5779         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5780                                         << static_cast<unsigned>(Args.size())
5781                                         << TC.getCorrectionRange());
5782       } else if (NumParams == 1 && FDecl &&
5783                  FDecl->getParamDecl(0)->getDeclName())
5784         Diag(Args[NumParams]->getBeginLoc(),
5785              MinArgs == NumParams
5786                  ? diag::err_typecheck_call_too_many_args_one
5787                  : diag::err_typecheck_call_too_many_args_at_most_one)
5788             << FnKind << FDecl->getParamDecl(0)
5789             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5790             << SourceRange(Args[NumParams]->getBeginLoc(),
5791                            Args.back()->getEndLoc());
5792       else
5793         Diag(Args[NumParams]->getBeginLoc(),
5794              MinArgs == NumParams
5795                  ? diag::err_typecheck_call_too_many_args
5796                  : diag::err_typecheck_call_too_many_args_at_most)
5797             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5798             << Fn->getSourceRange()
5799             << SourceRange(Args[NumParams]->getBeginLoc(),
5800                            Args.back()->getEndLoc());
5801 
5802       // Emit the location of the prototype.
5803       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5804         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5805 
5806       // This deletes the extra arguments.
5807       Call->shrinkNumArgs(NumParams);
5808       return true;
5809     }
5810   }
5811   SmallVector<Expr *, 8> AllArgs;
5812   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5813 
5814   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5815                                    AllArgs, CallType);
5816   if (Invalid)
5817     return true;
5818   unsigned TotalNumArgs = AllArgs.size();
5819   for (unsigned i = 0; i < TotalNumArgs; ++i)
5820     Call->setArg(i, AllArgs[i]);
5821 
5822   return false;
5823 }
5824 
5825 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5826                                   const FunctionProtoType *Proto,
5827                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5828                                   SmallVectorImpl<Expr *> &AllArgs,
5829                                   VariadicCallType CallType, bool AllowExplicit,
5830                                   bool IsListInitialization) {
5831   unsigned NumParams = Proto->getNumParams();
5832   bool Invalid = false;
5833   size_t ArgIx = 0;
5834   // Continue to check argument types (even if we have too few/many args).
5835   for (unsigned i = FirstParam; i < NumParams; i++) {
5836     QualType ProtoArgType = Proto->getParamType(i);
5837 
5838     Expr *Arg;
5839     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5840     if (ArgIx < Args.size()) {
5841       Arg = Args[ArgIx++];
5842 
5843       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5844                               diag::err_call_incomplete_argument, Arg))
5845         return true;
5846 
5847       // Strip the unbridged-cast placeholder expression off, if applicable.
5848       bool CFAudited = false;
5849       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5850           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5851           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5852         Arg = stripARCUnbridgedCast(Arg);
5853       else if (getLangOpts().ObjCAutoRefCount &&
5854                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5855                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5856         CFAudited = true;
5857 
5858       if (Proto->getExtParameterInfo(i).isNoEscape())
5859         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5860           BE->getBlockDecl()->setDoesNotEscape();
5861 
5862       InitializedEntity Entity =
5863           Param ? InitializedEntity::InitializeParameter(Context, Param,
5864                                                          ProtoArgType)
5865                 : InitializedEntity::InitializeParameter(
5866                       Context, ProtoArgType, Proto->isParamConsumed(i));
5867 
5868       // Remember that parameter belongs to a CF audited API.
5869       if (CFAudited)
5870         Entity.setParameterCFAudited();
5871 
5872       ExprResult ArgE = PerformCopyInitialization(
5873           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5874       if (ArgE.isInvalid())
5875         return true;
5876 
5877       Arg = ArgE.getAs<Expr>();
5878     } else {
5879       assert(Param && "can't use default arguments without a known callee");
5880 
5881       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5882       if (ArgExpr.isInvalid())
5883         return true;
5884 
5885       Arg = ArgExpr.getAs<Expr>();
5886     }
5887 
5888     // Check for array bounds violations for each argument to the call. This
5889     // check only triggers warnings when the argument isn't a more complex Expr
5890     // with its own checking, such as a BinaryOperator.
5891     CheckArrayAccess(Arg);
5892 
5893     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5894     CheckStaticArrayArgument(CallLoc, Param, Arg);
5895 
5896     AllArgs.push_back(Arg);
5897   }
5898 
5899   // If this is a variadic call, handle args passed through "...".
5900   if (CallType != VariadicDoesNotApply) {
5901     // Assume that extern "C" functions with variadic arguments that
5902     // return __unknown_anytype aren't *really* variadic.
5903     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5904         FDecl->isExternC()) {
5905       for (Expr *A : Args.slice(ArgIx)) {
5906         QualType paramType; // ignored
5907         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5908         Invalid |= arg.isInvalid();
5909         AllArgs.push_back(arg.get());
5910       }
5911 
5912     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5913     } else {
5914       for (Expr *A : Args.slice(ArgIx)) {
5915         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5916         Invalid |= Arg.isInvalid();
5917         AllArgs.push_back(Arg.get());
5918       }
5919     }
5920 
5921     // Check for array bounds violations.
5922     for (Expr *A : Args.slice(ArgIx))
5923       CheckArrayAccess(A);
5924   }
5925   return Invalid;
5926 }
5927 
5928 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5929   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5930   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5931     TL = DTL.getOriginalLoc();
5932   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5933     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5934       << ATL.getLocalSourceRange();
5935 }
5936 
5937 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5938 /// array parameter, check that it is non-null, and that if it is formed by
5939 /// array-to-pointer decay, the underlying array is sufficiently large.
5940 ///
5941 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5942 /// array type derivation, then for each call to the function, the value of the
5943 /// corresponding actual argument shall provide access to the first element of
5944 /// an array with at least as many elements as specified by the size expression.
5945 void
5946 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5947                                ParmVarDecl *Param,
5948                                const Expr *ArgExpr) {
5949   // Static array parameters are not supported in C++.
5950   if (!Param || getLangOpts().CPlusPlus)
5951     return;
5952 
5953   QualType OrigTy = Param->getOriginalType();
5954 
5955   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5956   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5957     return;
5958 
5959   if (ArgExpr->isNullPointerConstant(Context,
5960                                      Expr::NPC_NeverValueDependent)) {
5961     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5962     DiagnoseCalleeStaticArrayParam(*this, Param);
5963     return;
5964   }
5965 
5966   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5967   if (!CAT)
5968     return;
5969 
5970   const ConstantArrayType *ArgCAT =
5971     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5972   if (!ArgCAT)
5973     return;
5974 
5975   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5976                                              ArgCAT->getElementType())) {
5977     if (ArgCAT->getSize().ult(CAT->getSize())) {
5978       Diag(CallLoc, diag::warn_static_array_too_small)
5979           << ArgExpr->getSourceRange()
5980           << (unsigned)ArgCAT->getSize().getZExtValue()
5981           << (unsigned)CAT->getSize().getZExtValue() << 0;
5982       DiagnoseCalleeStaticArrayParam(*this, Param);
5983     }
5984     return;
5985   }
5986 
5987   Optional<CharUnits> ArgSize =
5988       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5989   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5990   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5991     Diag(CallLoc, diag::warn_static_array_too_small)
5992         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5993         << (unsigned)ParmSize->getQuantity() << 1;
5994     DiagnoseCalleeStaticArrayParam(*this, Param);
5995   }
5996 }
5997 
5998 /// Given a function expression of unknown-any type, try to rebuild it
5999 /// to have a function type.
6000 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6001 
6002 /// Is the given type a placeholder that we need to lower out
6003 /// immediately during argument processing?
6004 static bool isPlaceholderToRemoveAsArg(QualType type) {
6005   // Placeholders are never sugared.
6006   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6007   if (!placeholder) return false;
6008 
6009   switch (placeholder->getKind()) {
6010   // Ignore all the non-placeholder types.
6011 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6012   case BuiltinType::Id:
6013 #include "clang/Basic/OpenCLImageTypes.def"
6014 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6015   case BuiltinType::Id:
6016 #include "clang/Basic/OpenCLExtensionTypes.def"
6017   // In practice we'll never use this, since all SVE types are sugared
6018   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6019 #define SVE_TYPE(Name, Id, SingletonId) \
6020   case BuiltinType::Id:
6021 #include "clang/Basic/AArch64SVEACLETypes.def"
6022 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6023 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6024 #include "clang/AST/BuiltinTypes.def"
6025     return false;
6026 
6027   // We cannot lower out overload sets; they might validly be resolved
6028   // by the call machinery.
6029   case BuiltinType::Overload:
6030     return false;
6031 
6032   // Unbridged casts in ARC can be handled in some call positions and
6033   // should be left in place.
6034   case BuiltinType::ARCUnbridgedCast:
6035     return false;
6036 
6037   // Pseudo-objects should be converted as soon as possible.
6038   case BuiltinType::PseudoObject:
6039     return true;
6040 
6041   // The debugger mode could theoretically but currently does not try
6042   // to resolve unknown-typed arguments based on known parameter types.
6043   case BuiltinType::UnknownAny:
6044     return true;
6045 
6046   // These are always invalid as call arguments and should be reported.
6047   case BuiltinType::BoundMember:
6048   case BuiltinType::BuiltinFn:
6049   case BuiltinType::IncompleteMatrixIdx:
6050   case BuiltinType::OMPArraySection:
6051   case BuiltinType::OMPArrayShaping:
6052   case BuiltinType::OMPIterator:
6053     return true;
6054 
6055   }
6056   llvm_unreachable("bad builtin type kind");
6057 }
6058 
6059 /// Check an argument list for placeholders that we won't try to
6060 /// handle later.
6061 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6062   // Apply this processing to all the arguments at once instead of
6063   // dying at the first failure.
6064   bool hasInvalid = false;
6065   for (size_t i = 0, e = args.size(); i != e; i++) {
6066     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6067       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6068       if (result.isInvalid()) hasInvalid = true;
6069       else args[i] = result.get();
6070     } else if (hasInvalid) {
6071       (void)S.CorrectDelayedTyposInExpr(args[i]);
6072     }
6073   }
6074   return hasInvalid;
6075 }
6076 
6077 /// If a builtin function has a pointer argument with no explicit address
6078 /// space, then it should be able to accept a pointer to any address
6079 /// space as input.  In order to do this, we need to replace the
6080 /// standard builtin declaration with one that uses the same address space
6081 /// as the call.
6082 ///
6083 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6084 ///                  it does not contain any pointer arguments without
6085 ///                  an address space qualifer.  Otherwise the rewritten
6086 ///                  FunctionDecl is returned.
6087 /// TODO: Handle pointer return types.
6088 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6089                                                 FunctionDecl *FDecl,
6090                                                 MultiExprArg ArgExprs) {
6091 
6092   QualType DeclType = FDecl->getType();
6093   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6094 
6095   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6096       ArgExprs.size() < FT->getNumParams())
6097     return nullptr;
6098 
6099   bool NeedsNewDecl = false;
6100   unsigned i = 0;
6101   SmallVector<QualType, 8> OverloadParams;
6102 
6103   for (QualType ParamType : FT->param_types()) {
6104 
6105     // Convert array arguments to pointer to simplify type lookup.
6106     ExprResult ArgRes =
6107         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6108     if (ArgRes.isInvalid())
6109       return nullptr;
6110     Expr *Arg = ArgRes.get();
6111     QualType ArgType = Arg->getType();
6112     if (!ParamType->isPointerType() ||
6113         ParamType.hasAddressSpace() ||
6114         !ArgType->isPointerType() ||
6115         !ArgType->getPointeeType().hasAddressSpace()) {
6116       OverloadParams.push_back(ParamType);
6117       continue;
6118     }
6119 
6120     QualType PointeeType = ParamType->getPointeeType();
6121     if (PointeeType.hasAddressSpace())
6122       continue;
6123 
6124     NeedsNewDecl = true;
6125     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6126 
6127     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6128     OverloadParams.push_back(Context.getPointerType(PointeeType));
6129   }
6130 
6131   if (!NeedsNewDecl)
6132     return nullptr;
6133 
6134   FunctionProtoType::ExtProtoInfo EPI;
6135   EPI.Variadic = FT->isVariadic();
6136   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6137                                                 OverloadParams, EPI);
6138   DeclContext *Parent = FDecl->getParent();
6139   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6140                                                     FDecl->getLocation(),
6141                                                     FDecl->getLocation(),
6142                                                     FDecl->getIdentifier(),
6143                                                     OverloadTy,
6144                                                     /*TInfo=*/nullptr,
6145                                                     SC_Extern, false,
6146                                                     /*hasPrototype=*/true);
6147   SmallVector<ParmVarDecl*, 16> Params;
6148   FT = cast<FunctionProtoType>(OverloadTy);
6149   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6150     QualType ParamType = FT->getParamType(i);
6151     ParmVarDecl *Parm =
6152         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6153                                 SourceLocation(), nullptr, ParamType,
6154                                 /*TInfo=*/nullptr, SC_None, nullptr);
6155     Parm->setScopeInfo(0, i);
6156     Params.push_back(Parm);
6157   }
6158   OverloadDecl->setParams(Params);
6159   return OverloadDecl;
6160 }
6161 
6162 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6163                                     FunctionDecl *Callee,
6164                                     MultiExprArg ArgExprs) {
6165   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6166   // similar attributes) really don't like it when functions are called with an
6167   // invalid number of args.
6168   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6169                          /*PartialOverloading=*/false) &&
6170       !Callee->isVariadic())
6171     return;
6172   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6173     return;
6174 
6175   if (const EnableIfAttr *Attr =
6176           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6177     S.Diag(Fn->getBeginLoc(),
6178            isa<CXXMethodDecl>(Callee)
6179                ? diag::err_ovl_no_viable_member_function_in_call
6180                : diag::err_ovl_no_viable_function_in_call)
6181         << Callee << Callee->getSourceRange();
6182     S.Diag(Callee->getLocation(),
6183            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6184         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6185     return;
6186   }
6187 }
6188 
6189 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6190     const UnresolvedMemberExpr *const UME, Sema &S) {
6191 
6192   const auto GetFunctionLevelDCIfCXXClass =
6193       [](Sema &S) -> const CXXRecordDecl * {
6194     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6195     if (!DC || !DC->getParent())
6196       return nullptr;
6197 
6198     // If the call to some member function was made from within a member
6199     // function body 'M' return return 'M's parent.
6200     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6201       return MD->getParent()->getCanonicalDecl();
6202     // else the call was made from within a default member initializer of a
6203     // class, so return the class.
6204     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6205       return RD->getCanonicalDecl();
6206     return nullptr;
6207   };
6208   // If our DeclContext is neither a member function nor a class (in the
6209   // case of a lambda in a default member initializer), we can't have an
6210   // enclosing 'this'.
6211 
6212   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6213   if (!CurParentClass)
6214     return false;
6215 
6216   // The naming class for implicit member functions call is the class in which
6217   // name lookup starts.
6218   const CXXRecordDecl *const NamingClass =
6219       UME->getNamingClass()->getCanonicalDecl();
6220   assert(NamingClass && "Must have naming class even for implicit access");
6221 
6222   // If the unresolved member functions were found in a 'naming class' that is
6223   // related (either the same or derived from) to the class that contains the
6224   // member function that itself contained the implicit member access.
6225 
6226   return CurParentClass == NamingClass ||
6227          CurParentClass->isDerivedFrom(NamingClass);
6228 }
6229 
6230 static void
6231 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6232     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6233 
6234   if (!UME)
6235     return;
6236 
6237   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6238   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6239   // already been captured, or if this is an implicit member function call (if
6240   // it isn't, an attempt to capture 'this' should already have been made).
6241   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6242       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6243     return;
6244 
6245   // Check if the naming class in which the unresolved members were found is
6246   // related (same as or is a base of) to the enclosing class.
6247 
6248   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6249     return;
6250 
6251 
6252   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6253   // If the enclosing function is not dependent, then this lambda is
6254   // capture ready, so if we can capture this, do so.
6255   if (!EnclosingFunctionCtx->isDependentContext()) {
6256     // If the current lambda and all enclosing lambdas can capture 'this' -
6257     // then go ahead and capture 'this' (since our unresolved overload set
6258     // contains at least one non-static member function).
6259     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6260       S.CheckCXXThisCapture(CallLoc);
6261   } else if (S.CurContext->isDependentContext()) {
6262     // ... since this is an implicit member reference, that might potentially
6263     // involve a 'this' capture, mark 'this' for potential capture in
6264     // enclosing lambdas.
6265     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6266       CurLSI->addPotentialThisCapture(CallLoc);
6267   }
6268 }
6269 
6270 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6271                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6272                                Expr *ExecConfig) {
6273   ExprResult Call =
6274       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6275   if (Call.isInvalid())
6276     return Call;
6277 
6278   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6279   // language modes.
6280   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6281     if (ULE->hasExplicitTemplateArgs() &&
6282         ULE->decls_begin() == ULE->decls_end()) {
6283       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6284                                  ? diag::warn_cxx17_compat_adl_only_template_id
6285                                  : diag::ext_adl_only_template_id)
6286           << ULE->getName();
6287     }
6288   }
6289 
6290   if (LangOpts.OpenMP)
6291     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6292                            ExecConfig);
6293 
6294   return Call;
6295 }
6296 
6297 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6298 /// This provides the location of the left/right parens and a list of comma
6299 /// locations.
6300 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6301                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6302                                Expr *ExecConfig, bool IsExecConfig) {
6303   // Since this might be a postfix expression, get rid of ParenListExprs.
6304   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6305   if (Result.isInvalid()) return ExprError();
6306   Fn = Result.get();
6307 
6308   if (checkArgsForPlaceholders(*this, ArgExprs))
6309     return ExprError();
6310 
6311   if (getLangOpts().CPlusPlus) {
6312     // If this is a pseudo-destructor expression, build the call immediately.
6313     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6314       if (!ArgExprs.empty()) {
6315         // Pseudo-destructor calls should not have any arguments.
6316         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6317             << FixItHint::CreateRemoval(
6318                    SourceRange(ArgExprs.front()->getBeginLoc(),
6319                                ArgExprs.back()->getEndLoc()));
6320       }
6321 
6322       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6323                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6324     }
6325     if (Fn->getType() == Context.PseudoObjectTy) {
6326       ExprResult result = CheckPlaceholderExpr(Fn);
6327       if (result.isInvalid()) return ExprError();
6328       Fn = result.get();
6329     }
6330 
6331     // Determine whether this is a dependent call inside a C++ template,
6332     // in which case we won't do any semantic analysis now.
6333     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6334       if (ExecConfig) {
6335         return CUDAKernelCallExpr::Create(
6336             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6337             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6338       } else {
6339 
6340         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6341             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6342             Fn->getBeginLoc());
6343 
6344         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6345                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6346       }
6347     }
6348 
6349     // Determine whether this is a call to an object (C++ [over.call.object]).
6350     if (Fn->getType()->isRecordType())
6351       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6352                                           RParenLoc);
6353 
6354     if (Fn->getType() == Context.UnknownAnyTy) {
6355       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6356       if (result.isInvalid()) return ExprError();
6357       Fn = result.get();
6358     }
6359 
6360     if (Fn->getType() == Context.BoundMemberTy) {
6361       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6362                                        RParenLoc);
6363     }
6364   }
6365 
6366   // Check for overloaded calls.  This can happen even in C due to extensions.
6367   if (Fn->getType() == Context.OverloadTy) {
6368     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6369 
6370     // We aren't supposed to apply this logic if there's an '&' involved.
6371     if (!find.HasFormOfMemberPointer) {
6372       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6373         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6374                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6375       OverloadExpr *ovl = find.Expression;
6376       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6377         return BuildOverloadedCallExpr(
6378             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6379             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6380       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6381                                        RParenLoc);
6382     }
6383   }
6384 
6385   // If we're directly calling a function, get the appropriate declaration.
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   Expr *NakedFn = Fn->IgnoreParens();
6393 
6394   bool CallingNDeclIndirectly = false;
6395   NamedDecl *NDecl = nullptr;
6396   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6397     if (UnOp->getOpcode() == UO_AddrOf) {
6398       CallingNDeclIndirectly = true;
6399       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6400     }
6401   }
6402 
6403   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6404     NDecl = DRE->getDecl();
6405 
6406     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6407     if (FDecl && FDecl->getBuiltinID()) {
6408       // Rewrite the function decl for this builtin by replacing parameters
6409       // with no explicit address space with the address space of the arguments
6410       // in ArgExprs.
6411       if ((FDecl =
6412                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6413         NDecl = FDecl;
6414         Fn = DeclRefExpr::Create(
6415             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6416             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6417             nullptr, DRE->isNonOdrUse());
6418       }
6419     }
6420   } else if (isa<MemberExpr>(NakedFn))
6421     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6422 
6423   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6424     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6425                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6426       return ExprError();
6427 
6428     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6429       return ExprError();
6430 
6431     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6432   }
6433 
6434   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6435                                ExecConfig, IsExecConfig);
6436 }
6437 
6438 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6439 ///
6440 /// __builtin_astype( value, dst type )
6441 ///
6442 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6443                                  SourceLocation BuiltinLoc,
6444                                  SourceLocation RParenLoc) {
6445   ExprValueKind VK = VK_RValue;
6446   ExprObjectKind OK = OK_Ordinary;
6447   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6448   QualType SrcTy = E->getType();
6449   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6450     return ExprError(Diag(BuiltinLoc,
6451                           diag::err_invalid_astype_of_different_size)
6452                      << DstTy
6453                      << SrcTy
6454                      << E->getSourceRange());
6455   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6456 }
6457 
6458 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6459 /// provided arguments.
6460 ///
6461 /// __builtin_convertvector( value, dst type )
6462 ///
6463 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6464                                         SourceLocation BuiltinLoc,
6465                                         SourceLocation RParenLoc) {
6466   TypeSourceInfo *TInfo;
6467   GetTypeFromParser(ParsedDestTy, &TInfo);
6468   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6469 }
6470 
6471 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6472 /// i.e. an expression not of \p OverloadTy.  The expression should
6473 /// unary-convert to an expression of function-pointer or
6474 /// block-pointer type.
6475 ///
6476 /// \param NDecl the declaration being called, if available
6477 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6478                                        SourceLocation LParenLoc,
6479                                        ArrayRef<Expr *> Args,
6480                                        SourceLocation RParenLoc, Expr *Config,
6481                                        bool IsExecConfig, ADLCallKind UsesADL) {
6482   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6483   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6484 
6485   // Functions with 'interrupt' attribute cannot be called directly.
6486   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6487     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6488     return ExprError();
6489   }
6490 
6491   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6492   // so there's some risk when calling out to non-interrupt handler functions
6493   // that the callee might not preserve them. This is easy to diagnose here,
6494   // but can be very challenging to debug.
6495   if (auto *Caller = getCurFunctionDecl())
6496     if (Caller->hasAttr<ARMInterruptAttr>()) {
6497       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6498       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6499         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6500     }
6501 
6502   // Promote the function operand.
6503   // We special-case function promotion here because we only allow promoting
6504   // builtin functions to function pointers in the callee of a call.
6505   ExprResult Result;
6506   QualType ResultTy;
6507   if (BuiltinID &&
6508       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6509     // Extract the return type from the (builtin) function pointer type.
6510     // FIXME Several builtins still have setType in
6511     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6512     // Builtins.def to ensure they are correct before removing setType calls.
6513     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6514     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6515     ResultTy = FDecl->getCallResultType();
6516   } else {
6517     Result = CallExprUnaryConversions(Fn);
6518     ResultTy = Context.BoolTy;
6519   }
6520   if (Result.isInvalid())
6521     return ExprError();
6522   Fn = Result.get();
6523 
6524   // Check for a valid function type, but only if it is not a builtin which
6525   // requires custom type checking. These will be handled by
6526   // CheckBuiltinFunctionCall below just after creation of the call expression.
6527   const FunctionType *FuncT = nullptr;
6528   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6529   retry:
6530     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6531       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6532       // have type pointer to function".
6533       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6534       if (!FuncT)
6535         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6536                          << Fn->getType() << Fn->getSourceRange());
6537     } else if (const BlockPointerType *BPT =
6538                    Fn->getType()->getAs<BlockPointerType>()) {
6539       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6540     } else {
6541       // Handle calls to expressions of unknown-any type.
6542       if (Fn->getType() == Context.UnknownAnyTy) {
6543         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6544         if (rewrite.isInvalid())
6545           return ExprError();
6546         Fn = rewrite.get();
6547         goto retry;
6548       }
6549 
6550       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6551                        << Fn->getType() << Fn->getSourceRange());
6552     }
6553   }
6554 
6555   // Get the number of parameters in the function prototype, if any.
6556   // We will allocate space for max(Args.size(), NumParams) arguments
6557   // in the call expression.
6558   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6559   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6560 
6561   CallExpr *TheCall;
6562   if (Config) {
6563     assert(UsesADL == ADLCallKind::NotADL &&
6564            "CUDAKernelCallExpr should not use ADL");
6565     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6566                                          Args, ResultTy, VK_RValue, RParenLoc,
6567                                          CurFPFeatureOverrides(), NumParams);
6568   } else {
6569     TheCall =
6570         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6571                          CurFPFeatureOverrides(), NumParams, UsesADL);
6572   }
6573 
6574   if (!getLangOpts().CPlusPlus) {
6575     // Forget about the nulled arguments since typo correction
6576     // do not handle them well.
6577     TheCall->shrinkNumArgs(Args.size());
6578     // C cannot always handle TypoExpr nodes in builtin calls and direct
6579     // function calls as their argument checking don't necessarily handle
6580     // dependent types properly, so make sure any TypoExprs have been
6581     // dealt with.
6582     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6583     if (!Result.isUsable()) return ExprError();
6584     CallExpr *TheOldCall = TheCall;
6585     TheCall = dyn_cast<CallExpr>(Result.get());
6586     bool CorrectedTypos = TheCall != TheOldCall;
6587     if (!TheCall) return Result;
6588     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6589 
6590     // A new call expression node was created if some typos were corrected.
6591     // However it may not have been constructed with enough storage. In this
6592     // case, rebuild the node with enough storage. The waste of space is
6593     // immaterial since this only happens when some typos were corrected.
6594     if (CorrectedTypos && Args.size() < NumParams) {
6595       if (Config)
6596         TheCall = CUDAKernelCallExpr::Create(
6597             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6598             RParenLoc, CurFPFeatureOverrides(), NumParams);
6599       else
6600         TheCall =
6601             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6602                              CurFPFeatureOverrides(), NumParams, UsesADL);
6603     }
6604     // We can now handle the nulled arguments for the default arguments.
6605     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6606   }
6607 
6608   // Bail out early if calling a builtin with custom type checking.
6609   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6610     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6611 
6612   if (getLangOpts().CUDA) {
6613     if (Config) {
6614       // CUDA: Kernel calls must be to global functions
6615       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6616         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6617             << FDecl << Fn->getSourceRange());
6618 
6619       // CUDA: Kernel function must have 'void' return type
6620       if (!FuncT->getReturnType()->isVoidType() &&
6621           !FuncT->getReturnType()->getAs<AutoType>() &&
6622           !FuncT->getReturnType()->isInstantiationDependentType())
6623         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6624             << Fn->getType() << Fn->getSourceRange());
6625     } else {
6626       // CUDA: Calls to global functions must be configured
6627       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6628         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6629             << FDecl << Fn->getSourceRange());
6630     }
6631   }
6632 
6633   // Check for a valid return type
6634   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6635                           FDecl))
6636     return ExprError();
6637 
6638   // We know the result type of the call, set it.
6639   TheCall->setType(FuncT->getCallResultType(Context));
6640   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6641 
6642   if (Proto) {
6643     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6644                                 IsExecConfig))
6645       return ExprError();
6646   } else {
6647     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6648 
6649     if (FDecl) {
6650       // Check if we have too few/too many template arguments, based
6651       // on our knowledge of the function definition.
6652       const FunctionDecl *Def = nullptr;
6653       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6654         Proto = Def->getType()->getAs<FunctionProtoType>();
6655        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6656           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6657           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6658       }
6659 
6660       // If the function we're calling isn't a function prototype, but we have
6661       // a function prototype from a prior declaratiom, use that prototype.
6662       if (!FDecl->hasPrototype())
6663         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6664     }
6665 
6666     // Promote the arguments (C99 6.5.2.2p6).
6667     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6668       Expr *Arg = Args[i];
6669 
6670       if (Proto && i < Proto->getNumParams()) {
6671         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6672             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6673         ExprResult ArgE =
6674             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6675         if (ArgE.isInvalid())
6676           return true;
6677 
6678         Arg = ArgE.getAs<Expr>();
6679 
6680       } else {
6681         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6682 
6683         if (ArgE.isInvalid())
6684           return true;
6685 
6686         Arg = ArgE.getAs<Expr>();
6687       }
6688 
6689       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6690                               diag::err_call_incomplete_argument, Arg))
6691         return ExprError();
6692 
6693       TheCall->setArg(i, Arg);
6694     }
6695   }
6696 
6697   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6698     if (!Method->isStatic())
6699       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6700         << Fn->getSourceRange());
6701 
6702   // Check for sentinels
6703   if (NDecl)
6704     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6705 
6706   // Warn for unions passing across security boundary (CMSE).
6707   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6708     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6709       if (const auto *RT =
6710               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6711         if (RT->getDecl()->isOrContainsUnion())
6712           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6713               << 0 << i;
6714       }
6715     }
6716   }
6717 
6718   // Do special checking on direct calls to functions.
6719   if (FDecl) {
6720     if (CheckFunctionCall(FDecl, TheCall, Proto))
6721       return ExprError();
6722 
6723     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6724 
6725     if (BuiltinID)
6726       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6727   } else if (NDecl) {
6728     if (CheckPointerCall(NDecl, TheCall, Proto))
6729       return ExprError();
6730   } else {
6731     if (CheckOtherCall(TheCall, Proto))
6732       return ExprError();
6733   }
6734 
6735   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6736 }
6737 
6738 ExprResult
6739 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6740                            SourceLocation RParenLoc, Expr *InitExpr) {
6741   assert(Ty && "ActOnCompoundLiteral(): missing type");
6742   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6743 
6744   TypeSourceInfo *TInfo;
6745   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6746   if (!TInfo)
6747     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6748 
6749   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6750 }
6751 
6752 ExprResult
6753 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6754                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6755   QualType literalType = TInfo->getType();
6756 
6757   if (literalType->isArrayType()) {
6758     if (RequireCompleteSizedType(
6759             LParenLoc, Context.getBaseElementType(literalType),
6760             diag::err_array_incomplete_or_sizeless_type,
6761             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6762       return ExprError();
6763     if (literalType->isVariableArrayType())
6764       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6765         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6766   } else if (!literalType->isDependentType() &&
6767              RequireCompleteType(LParenLoc, literalType,
6768                diag::err_typecheck_decl_incomplete_type,
6769                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6770     return ExprError();
6771 
6772   InitializedEntity Entity
6773     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6774   InitializationKind Kind
6775     = InitializationKind::CreateCStyleCast(LParenLoc,
6776                                            SourceRange(LParenLoc, RParenLoc),
6777                                            /*InitList=*/true);
6778   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6779   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6780                                       &literalType);
6781   if (Result.isInvalid())
6782     return ExprError();
6783   LiteralExpr = Result.get();
6784 
6785   bool isFileScope = !CurContext->isFunctionOrMethod();
6786 
6787   // In C, compound literals are l-values for some reason.
6788   // For GCC compatibility, in C++, file-scope array compound literals with
6789   // constant initializers are also l-values, and compound literals are
6790   // otherwise prvalues.
6791   //
6792   // (GCC also treats C++ list-initialized file-scope array prvalues with
6793   // constant initializers as l-values, but that's non-conforming, so we don't
6794   // follow it there.)
6795   //
6796   // FIXME: It would be better to handle the lvalue cases as materializing and
6797   // lifetime-extending a temporary object, but our materialized temporaries
6798   // representation only supports lifetime extension from a variable, not "out
6799   // of thin air".
6800   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6801   // is bound to the result of applying array-to-pointer decay to the compound
6802   // literal.
6803   // FIXME: GCC supports compound literals of reference type, which should
6804   // obviously have a value kind derived from the kind of reference involved.
6805   ExprValueKind VK =
6806       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6807           ? VK_RValue
6808           : VK_LValue;
6809 
6810   if (isFileScope)
6811     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6812       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6813         Expr *Init = ILE->getInit(i);
6814         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6815       }
6816 
6817   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6818                                               VK, LiteralExpr, isFileScope);
6819   if (isFileScope) {
6820     if (!LiteralExpr->isTypeDependent() &&
6821         !LiteralExpr->isValueDependent() &&
6822         !literalType->isDependentType()) // C99 6.5.2.5p3
6823       if (CheckForConstantInitializer(LiteralExpr, literalType))
6824         return ExprError();
6825   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6826              literalType.getAddressSpace() != LangAS::Default) {
6827     // Embedded-C extensions to C99 6.5.2.5:
6828     //   "If the compound literal occurs inside the body of a function, the
6829     //   type name shall not be qualified by an address-space qualifier."
6830     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6831       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6832     return ExprError();
6833   }
6834 
6835   if (!isFileScope && !getLangOpts().CPlusPlus) {
6836     // Compound literals that have automatic storage duration are destroyed at
6837     // the end of the scope in C; in C++, they're just temporaries.
6838 
6839     // Emit diagnostics if it is or contains a C union type that is non-trivial
6840     // to destruct.
6841     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6842       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6843                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6844 
6845     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6846     if (literalType.isDestructedType()) {
6847       Cleanup.setExprNeedsCleanups(true);
6848       ExprCleanupObjects.push_back(E);
6849       getCurFunction()->setHasBranchProtectedScope();
6850     }
6851   }
6852 
6853   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6854       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6855     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6856                                        E->getInitializer()->getExprLoc());
6857 
6858   return MaybeBindToTemporary(E);
6859 }
6860 
6861 ExprResult
6862 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6863                     SourceLocation RBraceLoc) {
6864   // Only produce each kind of designated initialization diagnostic once.
6865   SourceLocation FirstDesignator;
6866   bool DiagnosedArrayDesignator = false;
6867   bool DiagnosedNestedDesignator = false;
6868   bool DiagnosedMixedDesignator = false;
6869 
6870   // Check that any designated initializers are syntactically valid in the
6871   // current language mode.
6872   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6873     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6874       if (FirstDesignator.isInvalid())
6875         FirstDesignator = DIE->getBeginLoc();
6876 
6877       if (!getLangOpts().CPlusPlus)
6878         break;
6879 
6880       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6881         DiagnosedNestedDesignator = true;
6882         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6883           << DIE->getDesignatorsSourceRange();
6884       }
6885 
6886       for (auto &Desig : DIE->designators()) {
6887         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6888           DiagnosedArrayDesignator = true;
6889           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6890             << Desig.getSourceRange();
6891         }
6892       }
6893 
6894       if (!DiagnosedMixedDesignator &&
6895           !isa<DesignatedInitExpr>(InitArgList[0])) {
6896         DiagnosedMixedDesignator = true;
6897         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6898           << DIE->getSourceRange();
6899         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6900           << InitArgList[0]->getSourceRange();
6901       }
6902     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6903                isa<DesignatedInitExpr>(InitArgList[0])) {
6904       DiagnosedMixedDesignator = true;
6905       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6906       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6907         << DIE->getSourceRange();
6908       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6909         << InitArgList[I]->getSourceRange();
6910     }
6911   }
6912 
6913   if (FirstDesignator.isValid()) {
6914     // Only diagnose designated initiaization as a C++20 extension if we didn't
6915     // already diagnose use of (non-C++20) C99 designator syntax.
6916     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6917         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6918       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6919                                 ? diag::warn_cxx17_compat_designated_init
6920                                 : diag::ext_cxx_designated_init);
6921     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6922       Diag(FirstDesignator, diag::ext_designated_init);
6923     }
6924   }
6925 
6926   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6927 }
6928 
6929 ExprResult
6930 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6931                     SourceLocation RBraceLoc) {
6932   // Semantic analysis for initializers is done by ActOnDeclarator() and
6933   // CheckInitializer() - it requires knowledge of the object being initialized.
6934 
6935   // Immediately handle non-overload placeholders.  Overloads can be
6936   // resolved contextually, but everything else here can't.
6937   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6938     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6939       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6940 
6941       // Ignore failures; dropping the entire initializer list because
6942       // of one failure would be terrible for indexing/etc.
6943       if (result.isInvalid()) continue;
6944 
6945       InitArgList[I] = result.get();
6946     }
6947   }
6948 
6949   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6950                                                RBraceLoc);
6951   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6952   return E;
6953 }
6954 
6955 /// Do an explicit extend of the given block pointer if we're in ARC.
6956 void Sema::maybeExtendBlockObject(ExprResult &E) {
6957   assert(E.get()->getType()->isBlockPointerType());
6958   assert(E.get()->isRValue());
6959 
6960   // Only do this in an r-value context.
6961   if (!getLangOpts().ObjCAutoRefCount) return;
6962 
6963   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6964                                CK_ARCExtendBlockObject, E.get(),
6965                                /*base path*/ nullptr, VK_RValue);
6966   Cleanup.setExprNeedsCleanups(true);
6967 }
6968 
6969 /// Prepare a conversion of the given expression to an ObjC object
6970 /// pointer type.
6971 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6972   QualType type = E.get()->getType();
6973   if (type->isObjCObjectPointerType()) {
6974     return CK_BitCast;
6975   } else if (type->isBlockPointerType()) {
6976     maybeExtendBlockObject(E);
6977     return CK_BlockPointerToObjCPointerCast;
6978   } else {
6979     assert(type->isPointerType());
6980     return CK_CPointerToObjCPointerCast;
6981   }
6982 }
6983 
6984 /// Prepares for a scalar cast, performing all the necessary stages
6985 /// except the final cast and returning the kind required.
6986 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6987   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6988   // Also, callers should have filtered out the invalid cases with
6989   // pointers.  Everything else should be possible.
6990 
6991   QualType SrcTy = Src.get()->getType();
6992   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6993     return CK_NoOp;
6994 
6995   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6996   case Type::STK_MemberPointer:
6997     llvm_unreachable("member pointer type in C");
6998 
6999   case Type::STK_CPointer:
7000   case Type::STK_BlockPointer:
7001   case Type::STK_ObjCObjectPointer:
7002     switch (DestTy->getScalarTypeKind()) {
7003     case Type::STK_CPointer: {
7004       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7005       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7006       if (SrcAS != DestAS)
7007         return CK_AddressSpaceConversion;
7008       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7009         return CK_NoOp;
7010       return CK_BitCast;
7011     }
7012     case Type::STK_BlockPointer:
7013       return (SrcKind == Type::STK_BlockPointer
7014                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7015     case Type::STK_ObjCObjectPointer:
7016       if (SrcKind == Type::STK_ObjCObjectPointer)
7017         return CK_BitCast;
7018       if (SrcKind == Type::STK_CPointer)
7019         return CK_CPointerToObjCPointerCast;
7020       maybeExtendBlockObject(Src);
7021       return CK_BlockPointerToObjCPointerCast;
7022     case Type::STK_Bool:
7023       return CK_PointerToBoolean;
7024     case Type::STK_Integral:
7025       return CK_PointerToIntegral;
7026     case Type::STK_Floating:
7027     case Type::STK_FloatingComplex:
7028     case Type::STK_IntegralComplex:
7029     case Type::STK_MemberPointer:
7030     case Type::STK_FixedPoint:
7031       llvm_unreachable("illegal cast from pointer");
7032     }
7033     llvm_unreachable("Should have returned before this");
7034 
7035   case Type::STK_FixedPoint:
7036     switch (DestTy->getScalarTypeKind()) {
7037     case Type::STK_FixedPoint:
7038       return CK_FixedPointCast;
7039     case Type::STK_Bool:
7040       return CK_FixedPointToBoolean;
7041     case Type::STK_Integral:
7042       return CK_FixedPointToIntegral;
7043     case Type::STK_Floating:
7044     case Type::STK_IntegralComplex:
7045     case Type::STK_FloatingComplex:
7046       Diag(Src.get()->getExprLoc(),
7047            diag::err_unimplemented_conversion_with_fixed_point_type)
7048           << DestTy;
7049       return CK_IntegralCast;
7050     case Type::STK_CPointer:
7051     case Type::STK_ObjCObjectPointer:
7052     case Type::STK_BlockPointer:
7053     case Type::STK_MemberPointer:
7054       llvm_unreachable("illegal cast to pointer type");
7055     }
7056     llvm_unreachable("Should have returned before this");
7057 
7058   case Type::STK_Bool: // casting from bool is like casting from an integer
7059   case Type::STK_Integral:
7060     switch (DestTy->getScalarTypeKind()) {
7061     case Type::STK_CPointer:
7062     case Type::STK_ObjCObjectPointer:
7063     case Type::STK_BlockPointer:
7064       if (Src.get()->isNullPointerConstant(Context,
7065                                            Expr::NPC_ValueDependentIsNull))
7066         return CK_NullToPointer;
7067       return CK_IntegralToPointer;
7068     case Type::STK_Bool:
7069       return CK_IntegralToBoolean;
7070     case Type::STK_Integral:
7071       return CK_IntegralCast;
7072     case Type::STK_Floating:
7073       return CK_IntegralToFloating;
7074     case Type::STK_IntegralComplex:
7075       Src = ImpCastExprToType(Src.get(),
7076                       DestTy->castAs<ComplexType>()->getElementType(),
7077                       CK_IntegralCast);
7078       return CK_IntegralRealToComplex;
7079     case Type::STK_FloatingComplex:
7080       Src = ImpCastExprToType(Src.get(),
7081                       DestTy->castAs<ComplexType>()->getElementType(),
7082                       CK_IntegralToFloating);
7083       return CK_FloatingRealToComplex;
7084     case Type::STK_MemberPointer:
7085       llvm_unreachable("member pointer type in C");
7086     case Type::STK_FixedPoint:
7087       return CK_IntegralToFixedPoint;
7088     }
7089     llvm_unreachable("Should have returned before this");
7090 
7091   case Type::STK_Floating:
7092     switch (DestTy->getScalarTypeKind()) {
7093     case Type::STK_Floating:
7094       return CK_FloatingCast;
7095     case Type::STK_Bool:
7096       return CK_FloatingToBoolean;
7097     case Type::STK_Integral:
7098       return CK_FloatingToIntegral;
7099     case Type::STK_FloatingComplex:
7100       Src = ImpCastExprToType(Src.get(),
7101                               DestTy->castAs<ComplexType>()->getElementType(),
7102                               CK_FloatingCast);
7103       return CK_FloatingRealToComplex;
7104     case Type::STK_IntegralComplex:
7105       Src = ImpCastExprToType(Src.get(),
7106                               DestTy->castAs<ComplexType>()->getElementType(),
7107                               CK_FloatingToIntegral);
7108       return CK_IntegralRealToComplex;
7109     case Type::STK_CPointer:
7110     case Type::STK_ObjCObjectPointer:
7111     case Type::STK_BlockPointer:
7112       llvm_unreachable("valid float->pointer cast?");
7113     case Type::STK_MemberPointer:
7114       llvm_unreachable("member pointer type in C");
7115     case Type::STK_FixedPoint:
7116       Diag(Src.get()->getExprLoc(),
7117            diag::err_unimplemented_conversion_with_fixed_point_type)
7118           << SrcTy;
7119       return CK_IntegralCast;
7120     }
7121     llvm_unreachable("Should have returned before this");
7122 
7123   case Type::STK_FloatingComplex:
7124     switch (DestTy->getScalarTypeKind()) {
7125     case Type::STK_FloatingComplex:
7126       return CK_FloatingComplexCast;
7127     case Type::STK_IntegralComplex:
7128       return CK_FloatingComplexToIntegralComplex;
7129     case Type::STK_Floating: {
7130       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7131       if (Context.hasSameType(ET, DestTy))
7132         return CK_FloatingComplexToReal;
7133       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7134       return CK_FloatingCast;
7135     }
7136     case Type::STK_Bool:
7137       return CK_FloatingComplexToBoolean;
7138     case Type::STK_Integral:
7139       Src = ImpCastExprToType(Src.get(),
7140                               SrcTy->castAs<ComplexType>()->getElementType(),
7141                               CK_FloatingComplexToReal);
7142       return CK_FloatingToIntegral;
7143     case Type::STK_CPointer:
7144     case Type::STK_ObjCObjectPointer:
7145     case Type::STK_BlockPointer:
7146       llvm_unreachable("valid complex float->pointer cast?");
7147     case Type::STK_MemberPointer:
7148       llvm_unreachable("member pointer type in C");
7149     case Type::STK_FixedPoint:
7150       Diag(Src.get()->getExprLoc(),
7151            diag::err_unimplemented_conversion_with_fixed_point_type)
7152           << SrcTy;
7153       return CK_IntegralCast;
7154     }
7155     llvm_unreachable("Should have returned before this");
7156 
7157   case Type::STK_IntegralComplex:
7158     switch (DestTy->getScalarTypeKind()) {
7159     case Type::STK_FloatingComplex:
7160       return CK_IntegralComplexToFloatingComplex;
7161     case Type::STK_IntegralComplex:
7162       return CK_IntegralComplexCast;
7163     case Type::STK_Integral: {
7164       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7165       if (Context.hasSameType(ET, DestTy))
7166         return CK_IntegralComplexToReal;
7167       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7168       return CK_IntegralCast;
7169     }
7170     case Type::STK_Bool:
7171       return CK_IntegralComplexToBoolean;
7172     case Type::STK_Floating:
7173       Src = ImpCastExprToType(Src.get(),
7174                               SrcTy->castAs<ComplexType>()->getElementType(),
7175                               CK_IntegralComplexToReal);
7176       return CK_IntegralToFloating;
7177     case Type::STK_CPointer:
7178     case Type::STK_ObjCObjectPointer:
7179     case Type::STK_BlockPointer:
7180       llvm_unreachable("valid complex int->pointer cast?");
7181     case Type::STK_MemberPointer:
7182       llvm_unreachable("member pointer type in C");
7183     case Type::STK_FixedPoint:
7184       Diag(Src.get()->getExprLoc(),
7185            diag::err_unimplemented_conversion_with_fixed_point_type)
7186           << SrcTy;
7187       return CK_IntegralCast;
7188     }
7189     llvm_unreachable("Should have returned before this");
7190   }
7191 
7192   llvm_unreachable("Unhandled scalar cast");
7193 }
7194 
7195 static bool breakDownVectorType(QualType type, uint64_t &len,
7196                                 QualType &eltType) {
7197   // Vectors are simple.
7198   if (const VectorType *vecType = type->getAs<VectorType>()) {
7199     len = vecType->getNumElements();
7200     eltType = vecType->getElementType();
7201     assert(eltType->isScalarType());
7202     return true;
7203   }
7204 
7205   // We allow lax conversion to and from non-vector types, but only if
7206   // they're real types (i.e. non-complex, non-pointer scalar types).
7207   if (!type->isRealType()) return false;
7208 
7209   len = 1;
7210   eltType = type;
7211   return true;
7212 }
7213 
7214 /// Are the two types lax-compatible vector types?  That is, given
7215 /// that one of them is a vector, do they have equal storage sizes,
7216 /// where the storage size is the number of elements times the element
7217 /// size?
7218 ///
7219 /// This will also return false if either of the types is neither a
7220 /// vector nor a real type.
7221 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7222   assert(destTy->isVectorType() || srcTy->isVectorType());
7223 
7224   // Disallow lax conversions between scalars and ExtVectors (these
7225   // conversions are allowed for other vector types because common headers
7226   // depend on them).  Most scalar OP ExtVector cases are handled by the
7227   // splat path anyway, which does what we want (convert, not bitcast).
7228   // What this rules out for ExtVectors is crazy things like char4*float.
7229   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7230   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7231 
7232   uint64_t srcLen, destLen;
7233   QualType srcEltTy, destEltTy;
7234   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7235   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7236 
7237   // ASTContext::getTypeSize will return the size rounded up to a
7238   // power of 2, so instead of using that, we need to use the raw
7239   // element size multiplied by the element count.
7240   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7241   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7242 
7243   return (srcLen * srcEltSize == destLen * destEltSize);
7244 }
7245 
7246 /// Is this a legal conversion between two types, one of which is
7247 /// known to be a vector type?
7248 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7249   assert(destTy->isVectorType() || srcTy->isVectorType());
7250 
7251   switch (Context.getLangOpts().getLaxVectorConversions()) {
7252   case LangOptions::LaxVectorConversionKind::None:
7253     return false;
7254 
7255   case LangOptions::LaxVectorConversionKind::Integer:
7256     if (!srcTy->isIntegralOrEnumerationType()) {
7257       auto *Vec = srcTy->getAs<VectorType>();
7258       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7259         return false;
7260     }
7261     if (!destTy->isIntegralOrEnumerationType()) {
7262       auto *Vec = destTy->getAs<VectorType>();
7263       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7264         return false;
7265     }
7266     // OK, integer (vector) -> integer (vector) bitcast.
7267     break;
7268 
7269     case LangOptions::LaxVectorConversionKind::All:
7270     break;
7271   }
7272 
7273   return areLaxCompatibleVectorTypes(srcTy, destTy);
7274 }
7275 
7276 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7277                            CastKind &Kind) {
7278   assert(VectorTy->isVectorType() && "Not a vector type!");
7279 
7280   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7281     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7282       return Diag(R.getBegin(),
7283                   Ty->isVectorType() ?
7284                   diag::err_invalid_conversion_between_vectors :
7285                   diag::err_invalid_conversion_between_vector_and_integer)
7286         << VectorTy << Ty << R;
7287   } else
7288     return Diag(R.getBegin(),
7289                 diag::err_invalid_conversion_between_vector_and_scalar)
7290       << VectorTy << Ty << R;
7291 
7292   Kind = CK_BitCast;
7293   return false;
7294 }
7295 
7296 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7297   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7298 
7299   if (DestElemTy == SplattedExpr->getType())
7300     return SplattedExpr;
7301 
7302   assert(DestElemTy->isFloatingType() ||
7303          DestElemTy->isIntegralOrEnumerationType());
7304 
7305   CastKind CK;
7306   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7307     // OpenCL requires that we convert `true` boolean expressions to -1, but
7308     // only when splatting vectors.
7309     if (DestElemTy->isFloatingType()) {
7310       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7311       // in two steps: boolean to signed integral, then to floating.
7312       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7313                                                  CK_BooleanToSignedIntegral);
7314       SplattedExpr = CastExprRes.get();
7315       CK = CK_IntegralToFloating;
7316     } else {
7317       CK = CK_BooleanToSignedIntegral;
7318     }
7319   } else {
7320     ExprResult CastExprRes = SplattedExpr;
7321     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7322     if (CastExprRes.isInvalid())
7323       return ExprError();
7324     SplattedExpr = CastExprRes.get();
7325   }
7326   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7327 }
7328 
7329 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7330                                     Expr *CastExpr, CastKind &Kind) {
7331   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7332 
7333   QualType SrcTy = CastExpr->getType();
7334 
7335   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7336   // an ExtVectorType.
7337   // In OpenCL, casts between vectors of different types are not allowed.
7338   // (See OpenCL 6.2).
7339   if (SrcTy->isVectorType()) {
7340     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7341         (getLangOpts().OpenCL &&
7342          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7343       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7344         << DestTy << SrcTy << R;
7345       return ExprError();
7346     }
7347     Kind = CK_BitCast;
7348     return CastExpr;
7349   }
7350 
7351   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7352   // conversion will take place first from scalar to elt type, and then
7353   // splat from elt type to vector.
7354   if (SrcTy->isPointerType())
7355     return Diag(R.getBegin(),
7356                 diag::err_invalid_conversion_between_vector_and_scalar)
7357       << DestTy << SrcTy << R;
7358 
7359   Kind = CK_VectorSplat;
7360   return prepareVectorSplat(DestTy, CastExpr);
7361 }
7362 
7363 ExprResult
7364 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7365                     Declarator &D, ParsedType &Ty,
7366                     SourceLocation RParenLoc, Expr *CastExpr) {
7367   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7368          "ActOnCastExpr(): missing type or expr");
7369 
7370   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7371   if (D.isInvalidType())
7372     return ExprError();
7373 
7374   if (getLangOpts().CPlusPlus) {
7375     // Check that there are no default arguments (C++ only).
7376     CheckExtraCXXDefaultArguments(D);
7377   } else {
7378     // Make sure any TypoExprs have been dealt with.
7379     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7380     if (!Res.isUsable())
7381       return ExprError();
7382     CastExpr = Res.get();
7383   }
7384 
7385   checkUnusedDeclAttributes(D);
7386 
7387   QualType castType = castTInfo->getType();
7388   Ty = CreateParsedType(castType, castTInfo);
7389 
7390   bool isVectorLiteral = false;
7391 
7392   // Check for an altivec or OpenCL literal,
7393   // i.e. all the elements are integer constants.
7394   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7395   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7396   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7397        && castType->isVectorType() && (PE || PLE)) {
7398     if (PLE && PLE->getNumExprs() == 0) {
7399       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7400       return ExprError();
7401     }
7402     if (PE || PLE->getNumExprs() == 1) {
7403       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7404       if (!E->getType()->isVectorType())
7405         isVectorLiteral = true;
7406     }
7407     else
7408       isVectorLiteral = true;
7409   }
7410 
7411   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7412   // then handle it as such.
7413   if (isVectorLiteral)
7414     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7415 
7416   // If the Expr being casted is a ParenListExpr, handle it specially.
7417   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7418   // sequence of BinOp comma operators.
7419   if (isa<ParenListExpr>(CastExpr)) {
7420     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7421     if (Result.isInvalid()) return ExprError();
7422     CastExpr = Result.get();
7423   }
7424 
7425   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7426       !getSourceManager().isInSystemMacro(LParenLoc))
7427     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7428 
7429   CheckTollFreeBridgeCast(castType, CastExpr);
7430 
7431   CheckObjCBridgeRelatedCast(castType, CastExpr);
7432 
7433   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7434 
7435   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7436 }
7437 
7438 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7439                                     SourceLocation RParenLoc, Expr *E,
7440                                     TypeSourceInfo *TInfo) {
7441   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7442          "Expected paren or paren list expression");
7443 
7444   Expr **exprs;
7445   unsigned numExprs;
7446   Expr *subExpr;
7447   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7448   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7449     LiteralLParenLoc = PE->getLParenLoc();
7450     LiteralRParenLoc = PE->getRParenLoc();
7451     exprs = PE->getExprs();
7452     numExprs = PE->getNumExprs();
7453   } else { // isa<ParenExpr> by assertion at function entrance
7454     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7455     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7456     subExpr = cast<ParenExpr>(E)->getSubExpr();
7457     exprs = &subExpr;
7458     numExprs = 1;
7459   }
7460 
7461   QualType Ty = TInfo->getType();
7462   assert(Ty->isVectorType() && "Expected vector type");
7463 
7464   SmallVector<Expr *, 8> initExprs;
7465   const VectorType *VTy = Ty->castAs<VectorType>();
7466   unsigned numElems = VTy->getNumElements();
7467 
7468   // '(...)' form of vector initialization in AltiVec: the number of
7469   // initializers must be one or must match the size of the vector.
7470   // If a single value is specified in the initializer then it will be
7471   // replicated to all the components of the vector
7472   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7473     // The number of initializers must be one or must match the size of the
7474     // vector. If a single value is specified in the initializer then it will
7475     // be replicated to all the components of the vector
7476     if (numExprs == 1) {
7477       QualType ElemTy = VTy->getElementType();
7478       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7479       if (Literal.isInvalid())
7480         return ExprError();
7481       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7482                                   PrepareScalarCast(Literal, ElemTy));
7483       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7484     }
7485     else if (numExprs < numElems) {
7486       Diag(E->getExprLoc(),
7487            diag::err_incorrect_number_of_vector_initializers);
7488       return ExprError();
7489     }
7490     else
7491       initExprs.append(exprs, exprs + numExprs);
7492   }
7493   else {
7494     // For OpenCL, when the number of initializers is a single value,
7495     // it will be replicated to all components of the vector.
7496     if (getLangOpts().OpenCL &&
7497         VTy->getVectorKind() == VectorType::GenericVector &&
7498         numExprs == 1) {
7499         QualType ElemTy = VTy->getElementType();
7500         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7501         if (Literal.isInvalid())
7502           return ExprError();
7503         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7504                                     PrepareScalarCast(Literal, ElemTy));
7505         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7506     }
7507 
7508     initExprs.append(exprs, exprs + numExprs);
7509   }
7510   // FIXME: This means that pretty-printing the final AST will produce curly
7511   // braces instead of the original commas.
7512   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7513                                                    initExprs, LiteralRParenLoc);
7514   initE->setType(Ty);
7515   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7516 }
7517 
7518 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7519 /// the ParenListExpr into a sequence of comma binary operators.
7520 ExprResult
7521 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7522   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7523   if (!E)
7524     return OrigExpr;
7525 
7526   ExprResult Result(E->getExpr(0));
7527 
7528   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7529     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7530                         E->getExpr(i));
7531 
7532   if (Result.isInvalid()) return ExprError();
7533 
7534   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7535 }
7536 
7537 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7538                                     SourceLocation R,
7539                                     MultiExprArg Val) {
7540   return ParenListExpr::Create(Context, L, Val, R);
7541 }
7542 
7543 /// Emit a specialized diagnostic when one expression is a null pointer
7544 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7545 /// emitted.
7546 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7547                                       SourceLocation QuestionLoc) {
7548   Expr *NullExpr = LHSExpr;
7549   Expr *NonPointerExpr = RHSExpr;
7550   Expr::NullPointerConstantKind NullKind =
7551       NullExpr->isNullPointerConstant(Context,
7552                                       Expr::NPC_ValueDependentIsNotNull);
7553 
7554   if (NullKind == Expr::NPCK_NotNull) {
7555     NullExpr = RHSExpr;
7556     NonPointerExpr = LHSExpr;
7557     NullKind =
7558         NullExpr->isNullPointerConstant(Context,
7559                                         Expr::NPC_ValueDependentIsNotNull);
7560   }
7561 
7562   if (NullKind == Expr::NPCK_NotNull)
7563     return false;
7564 
7565   if (NullKind == Expr::NPCK_ZeroExpression)
7566     return false;
7567 
7568   if (NullKind == Expr::NPCK_ZeroLiteral) {
7569     // In this case, check to make sure that we got here from a "NULL"
7570     // string in the source code.
7571     NullExpr = NullExpr->IgnoreParenImpCasts();
7572     SourceLocation loc = NullExpr->getExprLoc();
7573     if (!findMacroSpelling(loc, "NULL"))
7574       return false;
7575   }
7576 
7577   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7578   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7579       << NonPointerExpr->getType() << DiagType
7580       << NonPointerExpr->getSourceRange();
7581   return true;
7582 }
7583 
7584 /// Return false if the condition expression is valid, true otherwise.
7585 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7586   QualType CondTy = Cond->getType();
7587 
7588   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7589   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7590     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7591       << CondTy << Cond->getSourceRange();
7592     return true;
7593   }
7594 
7595   // C99 6.5.15p2
7596   if (CondTy->isScalarType()) return false;
7597 
7598   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7599     << CondTy << Cond->getSourceRange();
7600   return true;
7601 }
7602 
7603 /// Handle when one or both operands are void type.
7604 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7605                                          ExprResult &RHS) {
7606     Expr *LHSExpr = LHS.get();
7607     Expr *RHSExpr = RHS.get();
7608 
7609     if (!LHSExpr->getType()->isVoidType())
7610       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7611           << RHSExpr->getSourceRange();
7612     if (!RHSExpr->getType()->isVoidType())
7613       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7614           << LHSExpr->getSourceRange();
7615     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7616     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7617     return S.Context.VoidTy;
7618 }
7619 
7620 /// Return false if the NullExpr can be promoted to PointerTy,
7621 /// true otherwise.
7622 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7623                                         QualType PointerTy) {
7624   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7625       !NullExpr.get()->isNullPointerConstant(S.Context,
7626                                             Expr::NPC_ValueDependentIsNull))
7627     return true;
7628 
7629   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7630   return false;
7631 }
7632 
7633 /// Checks compatibility between two pointers and return the resulting
7634 /// type.
7635 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7636                                                      ExprResult &RHS,
7637                                                      SourceLocation Loc) {
7638   QualType LHSTy = LHS.get()->getType();
7639   QualType RHSTy = RHS.get()->getType();
7640 
7641   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7642     // Two identical pointers types are always compatible.
7643     return LHSTy;
7644   }
7645 
7646   QualType lhptee, rhptee;
7647 
7648   // Get the pointee types.
7649   bool IsBlockPointer = false;
7650   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7651     lhptee = LHSBTy->getPointeeType();
7652     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7653     IsBlockPointer = true;
7654   } else {
7655     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7656     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7657   }
7658 
7659   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7660   // differently qualified versions of compatible types, the result type is
7661   // a pointer to an appropriately qualified version of the composite
7662   // type.
7663 
7664   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7665   // clause doesn't make sense for our extensions. E.g. address space 2 should
7666   // be incompatible with address space 3: they may live on different devices or
7667   // anything.
7668   Qualifiers lhQual = lhptee.getQualifiers();
7669   Qualifiers rhQual = rhptee.getQualifiers();
7670 
7671   LangAS ResultAddrSpace = LangAS::Default;
7672   LangAS LAddrSpace = lhQual.getAddressSpace();
7673   LangAS RAddrSpace = rhQual.getAddressSpace();
7674 
7675   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7676   // spaces is disallowed.
7677   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7678     ResultAddrSpace = LAddrSpace;
7679   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7680     ResultAddrSpace = RAddrSpace;
7681   else {
7682     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7683         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7684         << RHS.get()->getSourceRange();
7685     return QualType();
7686   }
7687 
7688   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7689   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7690   lhQual.removeCVRQualifiers();
7691   rhQual.removeCVRQualifiers();
7692 
7693   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7694   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7695   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7696   // qual types are compatible iff
7697   //  * corresponded types are compatible
7698   //  * CVR qualifiers are equal
7699   //  * address spaces are equal
7700   // Thus for conditional operator we merge CVR and address space unqualified
7701   // pointees and if there is a composite type we return a pointer to it with
7702   // merged qualifiers.
7703   LHSCastKind =
7704       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7705   RHSCastKind =
7706       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7707   lhQual.removeAddressSpace();
7708   rhQual.removeAddressSpace();
7709 
7710   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7711   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7712 
7713   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7714 
7715   if (CompositeTy.isNull()) {
7716     // In this situation, we assume void* type. No especially good
7717     // reason, but this is what gcc does, and we do have to pick
7718     // to get a consistent AST.
7719     QualType incompatTy;
7720     incompatTy = S.Context.getPointerType(
7721         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7722     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7723     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7724 
7725     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7726     // for casts between types with incompatible address space qualifiers.
7727     // For the following code the compiler produces casts between global and
7728     // local address spaces of the corresponded innermost pointees:
7729     // local int *global *a;
7730     // global int *global *b;
7731     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7732     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7733         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7734         << RHS.get()->getSourceRange();
7735 
7736     return incompatTy;
7737   }
7738 
7739   // The pointer types are compatible.
7740   // In case of OpenCL ResultTy should have the address space qualifier
7741   // which is a superset of address spaces of both the 2nd and the 3rd
7742   // operands of the conditional operator.
7743   QualType ResultTy = [&, ResultAddrSpace]() {
7744     if (S.getLangOpts().OpenCL) {
7745       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7746       CompositeQuals.setAddressSpace(ResultAddrSpace);
7747       return S.Context
7748           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7749           .withCVRQualifiers(MergedCVRQual);
7750     }
7751     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7752   }();
7753   if (IsBlockPointer)
7754     ResultTy = S.Context.getBlockPointerType(ResultTy);
7755   else
7756     ResultTy = S.Context.getPointerType(ResultTy);
7757 
7758   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7759   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7760   return ResultTy;
7761 }
7762 
7763 /// Return the resulting type when the operands are both block pointers.
7764 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7765                                                           ExprResult &LHS,
7766                                                           ExprResult &RHS,
7767                                                           SourceLocation Loc) {
7768   QualType LHSTy = LHS.get()->getType();
7769   QualType RHSTy = RHS.get()->getType();
7770 
7771   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7772     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7773       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7774       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7775       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7776       return destType;
7777     }
7778     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7779       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7780       << RHS.get()->getSourceRange();
7781     return QualType();
7782   }
7783 
7784   // We have 2 block pointer types.
7785   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7786 }
7787 
7788 /// Return the resulting type when the operands are both pointers.
7789 static QualType
7790 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7791                                             ExprResult &RHS,
7792                                             SourceLocation Loc) {
7793   // get the pointer types
7794   QualType LHSTy = LHS.get()->getType();
7795   QualType RHSTy = RHS.get()->getType();
7796 
7797   // get the "pointed to" types
7798   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7799   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7800 
7801   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7802   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7803     // Figure out necessary qualifiers (C99 6.5.15p6)
7804     QualType destPointee
7805       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7806     QualType destType = S.Context.getPointerType(destPointee);
7807     // Add qualifiers if necessary.
7808     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7809     // Promote to void*.
7810     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7811     return destType;
7812   }
7813   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7814     QualType destPointee
7815       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7816     QualType destType = S.Context.getPointerType(destPointee);
7817     // Add qualifiers if necessary.
7818     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7819     // Promote to void*.
7820     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7821     return destType;
7822   }
7823 
7824   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7825 }
7826 
7827 /// Return false if the first expression is not an integer and the second
7828 /// expression is not a pointer, true otherwise.
7829 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7830                                         Expr* PointerExpr, SourceLocation Loc,
7831                                         bool IsIntFirstExpr) {
7832   if (!PointerExpr->getType()->isPointerType() ||
7833       !Int.get()->getType()->isIntegerType())
7834     return false;
7835 
7836   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7837   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7838 
7839   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7840     << Expr1->getType() << Expr2->getType()
7841     << Expr1->getSourceRange() << Expr2->getSourceRange();
7842   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7843                             CK_IntegralToPointer);
7844   return true;
7845 }
7846 
7847 /// Simple conversion between integer and floating point types.
7848 ///
7849 /// Used when handling the OpenCL conditional operator where the
7850 /// condition is a vector while the other operands are scalar.
7851 ///
7852 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7853 /// types are either integer or floating type. Between the two
7854 /// operands, the type with the higher rank is defined as the "result
7855 /// type". The other operand needs to be promoted to the same type. No
7856 /// other type promotion is allowed. We cannot use
7857 /// UsualArithmeticConversions() for this purpose, since it always
7858 /// promotes promotable types.
7859 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7860                                             ExprResult &RHS,
7861                                             SourceLocation QuestionLoc) {
7862   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7863   if (LHS.isInvalid())
7864     return QualType();
7865   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7866   if (RHS.isInvalid())
7867     return QualType();
7868 
7869   // For conversion purposes, we ignore any qualifiers.
7870   // For example, "const float" and "float" are equivalent.
7871   QualType LHSType =
7872     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7873   QualType RHSType =
7874     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7875 
7876   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7877     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7878       << LHSType << LHS.get()->getSourceRange();
7879     return QualType();
7880   }
7881 
7882   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7883     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7884       << RHSType << RHS.get()->getSourceRange();
7885     return QualType();
7886   }
7887 
7888   // If both types are identical, no conversion is needed.
7889   if (LHSType == RHSType)
7890     return LHSType;
7891 
7892   // Now handle "real" floating types (i.e. float, double, long double).
7893   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7894     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7895                                  /*IsCompAssign = */ false);
7896 
7897   // Finally, we have two differing integer types.
7898   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7899   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7900 }
7901 
7902 /// Convert scalar operands to a vector that matches the
7903 ///        condition in length.
7904 ///
7905 /// Used when handling the OpenCL conditional operator where the
7906 /// condition is a vector while the other operands are scalar.
7907 ///
7908 /// We first compute the "result type" for the scalar operands
7909 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7910 /// into a vector of that type where the length matches the condition
7911 /// vector type. s6.11.6 requires that the element types of the result
7912 /// and the condition must have the same number of bits.
7913 static QualType
7914 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7915                               QualType CondTy, SourceLocation QuestionLoc) {
7916   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7917   if (ResTy.isNull()) return QualType();
7918 
7919   const VectorType *CV = CondTy->getAs<VectorType>();
7920   assert(CV);
7921 
7922   // Determine the vector result type
7923   unsigned NumElements = CV->getNumElements();
7924   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7925 
7926   // Ensure that all types have the same number of bits
7927   if (S.Context.getTypeSize(CV->getElementType())
7928       != S.Context.getTypeSize(ResTy)) {
7929     // Since VectorTy is created internally, it does not pretty print
7930     // with an OpenCL name. Instead, we just print a description.
7931     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7932     SmallString<64> Str;
7933     llvm::raw_svector_ostream OS(Str);
7934     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7935     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7936       << CondTy << OS.str();
7937     return QualType();
7938   }
7939 
7940   // Convert operands to the vector result type
7941   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7942   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7943 
7944   return VectorTy;
7945 }
7946 
7947 /// Return false if this is a valid OpenCL condition vector
7948 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7949                                        SourceLocation QuestionLoc) {
7950   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7951   // integral type.
7952   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7953   assert(CondTy);
7954   QualType EleTy = CondTy->getElementType();
7955   if (EleTy->isIntegerType()) return false;
7956 
7957   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7958     << Cond->getType() << Cond->getSourceRange();
7959   return true;
7960 }
7961 
7962 /// Return false if the vector condition type and the vector
7963 ///        result type are compatible.
7964 ///
7965 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7966 /// number of elements, and their element types have the same number
7967 /// of bits.
7968 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7969                               SourceLocation QuestionLoc) {
7970   const VectorType *CV = CondTy->getAs<VectorType>();
7971   const VectorType *RV = VecResTy->getAs<VectorType>();
7972   assert(CV && RV);
7973 
7974   if (CV->getNumElements() != RV->getNumElements()) {
7975     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7976       << CondTy << VecResTy;
7977     return true;
7978   }
7979 
7980   QualType CVE = CV->getElementType();
7981   QualType RVE = RV->getElementType();
7982 
7983   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7984     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7985       << CondTy << VecResTy;
7986     return true;
7987   }
7988 
7989   return false;
7990 }
7991 
7992 /// Return the resulting type for the conditional operator in
7993 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7994 ///        s6.3.i) when the condition is a vector type.
7995 static QualType
7996 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7997                              ExprResult &LHS, ExprResult &RHS,
7998                              SourceLocation QuestionLoc) {
7999   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8000   if (Cond.isInvalid())
8001     return QualType();
8002   QualType CondTy = Cond.get()->getType();
8003 
8004   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8005     return QualType();
8006 
8007   // If either operand is a vector then find the vector type of the
8008   // result as specified in OpenCL v1.1 s6.3.i.
8009   if (LHS.get()->getType()->isVectorType() ||
8010       RHS.get()->getType()->isVectorType()) {
8011     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8012                                               /*isCompAssign*/false,
8013                                               /*AllowBothBool*/true,
8014                                               /*AllowBoolConversions*/false);
8015     if (VecResTy.isNull()) return QualType();
8016     // The result type must match the condition type as specified in
8017     // OpenCL v1.1 s6.11.6.
8018     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8019       return QualType();
8020     return VecResTy;
8021   }
8022 
8023   // Both operands are scalar.
8024   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8025 }
8026 
8027 /// Return true if the Expr is block type
8028 static bool checkBlockType(Sema &S, const Expr *E) {
8029   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8030     QualType Ty = CE->getCallee()->getType();
8031     if (Ty->isBlockPointerType()) {
8032       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8033       return true;
8034     }
8035   }
8036   return false;
8037 }
8038 
8039 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8040 /// In that case, LHS = cond.
8041 /// C99 6.5.15
8042 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8043                                         ExprResult &RHS, ExprValueKind &VK,
8044                                         ExprObjectKind &OK,
8045                                         SourceLocation QuestionLoc) {
8046 
8047   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8048   if (!LHSResult.isUsable()) return QualType();
8049   LHS = LHSResult;
8050 
8051   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8052   if (!RHSResult.isUsable()) return QualType();
8053   RHS = RHSResult;
8054 
8055   // C++ is sufficiently different to merit its own checker.
8056   if (getLangOpts().CPlusPlus)
8057     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8058 
8059   VK = VK_RValue;
8060   OK = OK_Ordinary;
8061 
8062   // The OpenCL operator with a vector condition is sufficiently
8063   // different to merit its own checker.
8064   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8065       Cond.get()->getType()->isExtVectorType())
8066     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8067 
8068   // First, check the condition.
8069   Cond = UsualUnaryConversions(Cond.get());
8070   if (Cond.isInvalid())
8071     return QualType();
8072   if (checkCondition(*this, Cond.get(), QuestionLoc))
8073     return QualType();
8074 
8075   // Now check the two expressions.
8076   if (LHS.get()->getType()->isVectorType() ||
8077       RHS.get()->getType()->isVectorType())
8078     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8079                                /*AllowBothBool*/true,
8080                                /*AllowBoolConversions*/false);
8081 
8082   QualType ResTy =
8083       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8084   if (LHS.isInvalid() || RHS.isInvalid())
8085     return QualType();
8086 
8087   QualType LHSTy = LHS.get()->getType();
8088   QualType RHSTy = RHS.get()->getType();
8089 
8090   // Diagnose attempts to convert between __float128 and long double where
8091   // such conversions currently can't be handled.
8092   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8093     Diag(QuestionLoc,
8094          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8095       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8096     return QualType();
8097   }
8098 
8099   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8100   // selection operator (?:).
8101   if (getLangOpts().OpenCL &&
8102       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8103     return QualType();
8104   }
8105 
8106   // If both operands have arithmetic type, do the usual arithmetic conversions
8107   // to find a common type: C99 6.5.15p3,5.
8108   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8109     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8110     // different sizes, or between ExtInts and other types.
8111     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8112       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8113           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8114           << RHS.get()->getSourceRange();
8115       return QualType();
8116     }
8117 
8118     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8119     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8120 
8121     return ResTy;
8122   }
8123 
8124   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8125   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8126     return LHSTy;
8127   }
8128 
8129   // If both operands are the same structure or union type, the result is that
8130   // type.
8131   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8132     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8133       if (LHSRT->getDecl() == RHSRT->getDecl())
8134         // "If both the operands have structure or union type, the result has
8135         // that type."  This implies that CV qualifiers are dropped.
8136         return LHSTy.getUnqualifiedType();
8137     // FIXME: Type of conditional expression must be complete in C mode.
8138   }
8139 
8140   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8141   // The following || allows only one side to be void (a GCC-ism).
8142   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8143     return checkConditionalVoidType(*this, LHS, RHS);
8144   }
8145 
8146   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8147   // the type of the other operand."
8148   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8149   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8150 
8151   // All objective-c pointer type analysis is done here.
8152   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8153                                                         QuestionLoc);
8154   if (LHS.isInvalid() || RHS.isInvalid())
8155     return QualType();
8156   if (!compositeType.isNull())
8157     return compositeType;
8158 
8159 
8160   // Handle block pointer types.
8161   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8162     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8163                                                      QuestionLoc);
8164 
8165   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8166   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8167     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8168                                                        QuestionLoc);
8169 
8170   // GCC compatibility: soften pointer/integer mismatch.  Note that
8171   // null pointers have been filtered out by this point.
8172   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8173       /*IsIntFirstExpr=*/true))
8174     return RHSTy;
8175   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8176       /*IsIntFirstExpr=*/false))
8177     return LHSTy;
8178 
8179   // Allow ?: operations in which both operands have the same
8180   // built-in sizeless type.
8181   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8182     return LHSTy;
8183 
8184   // Emit a better diagnostic if one of the expressions is a null pointer
8185   // constant and the other is not a pointer type. In this case, the user most
8186   // likely forgot to take the address of the other expression.
8187   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8188     return QualType();
8189 
8190   // Otherwise, the operands are not compatible.
8191   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8192     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8193     << RHS.get()->getSourceRange();
8194   return QualType();
8195 }
8196 
8197 /// FindCompositeObjCPointerType - Helper method to find composite type of
8198 /// two objective-c pointer types of the two input expressions.
8199 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8200                                             SourceLocation QuestionLoc) {
8201   QualType LHSTy = LHS.get()->getType();
8202   QualType RHSTy = RHS.get()->getType();
8203 
8204   // Handle things like Class and struct objc_class*.  Here we case the result
8205   // to the pseudo-builtin, because that will be implicitly cast back to the
8206   // redefinition type if an attempt is made to access its fields.
8207   if (LHSTy->isObjCClassType() &&
8208       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8209     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8210     return LHSTy;
8211   }
8212   if (RHSTy->isObjCClassType() &&
8213       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8214     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8215     return RHSTy;
8216   }
8217   // And the same for struct objc_object* / id
8218   if (LHSTy->isObjCIdType() &&
8219       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8220     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8221     return LHSTy;
8222   }
8223   if (RHSTy->isObjCIdType() &&
8224       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8225     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8226     return RHSTy;
8227   }
8228   // And the same for struct objc_selector* / SEL
8229   if (Context.isObjCSelType(LHSTy) &&
8230       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8231     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8232     return LHSTy;
8233   }
8234   if (Context.isObjCSelType(RHSTy) &&
8235       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8236     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8237     return RHSTy;
8238   }
8239   // Check constraints for Objective-C object pointers types.
8240   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8241 
8242     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8243       // Two identical object pointer types are always compatible.
8244       return LHSTy;
8245     }
8246     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8247     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8248     QualType compositeType = LHSTy;
8249 
8250     // If both operands are interfaces and either operand can be
8251     // assigned to the other, use that type as the composite
8252     // type. This allows
8253     //   xxx ? (A*) a : (B*) b
8254     // where B is a subclass of A.
8255     //
8256     // Additionally, as for assignment, if either type is 'id'
8257     // allow silent coercion. Finally, if the types are
8258     // incompatible then make sure to use 'id' as the composite
8259     // type so the result is acceptable for sending messages to.
8260 
8261     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8262     // It could return the composite type.
8263     if (!(compositeType =
8264           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8265       // Nothing more to do.
8266     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8267       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8268     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8269       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8270     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8271                 RHSOPT->isObjCQualifiedIdType()) &&
8272                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8273                                                          true)) {
8274       // Need to handle "id<xx>" explicitly.
8275       // GCC allows qualified id and any Objective-C type to devolve to
8276       // id. Currently localizing to here until clear this should be
8277       // part of ObjCQualifiedIdTypesAreCompatible.
8278       compositeType = Context.getObjCIdType();
8279     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8280       compositeType = Context.getObjCIdType();
8281     } else {
8282       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8283       << LHSTy << RHSTy
8284       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8285       QualType incompatTy = Context.getObjCIdType();
8286       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8287       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8288       return incompatTy;
8289     }
8290     // The object pointer types are compatible.
8291     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8292     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8293     return compositeType;
8294   }
8295   // Check Objective-C object pointer types and 'void *'
8296   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8297     if (getLangOpts().ObjCAutoRefCount) {
8298       // ARC forbids the implicit conversion of object pointers to 'void *',
8299       // so these types are not compatible.
8300       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8301           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8302       LHS = RHS = true;
8303       return QualType();
8304     }
8305     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8306     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8307     QualType destPointee
8308     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8309     QualType destType = Context.getPointerType(destPointee);
8310     // Add qualifiers if necessary.
8311     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8312     // Promote to void*.
8313     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8314     return destType;
8315   }
8316   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8317     if (getLangOpts().ObjCAutoRefCount) {
8318       // ARC forbids the implicit conversion of object pointers to 'void *',
8319       // so these types are not compatible.
8320       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8321           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8322       LHS = RHS = true;
8323       return QualType();
8324     }
8325     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8326     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8327     QualType destPointee
8328     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8329     QualType destType = Context.getPointerType(destPointee);
8330     // Add qualifiers if necessary.
8331     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8332     // Promote to void*.
8333     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8334     return destType;
8335   }
8336   return QualType();
8337 }
8338 
8339 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8340 /// ParenRange in parentheses.
8341 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8342                                const PartialDiagnostic &Note,
8343                                SourceRange ParenRange) {
8344   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8345   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8346       EndLoc.isValid()) {
8347     Self.Diag(Loc, Note)
8348       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8349       << FixItHint::CreateInsertion(EndLoc, ")");
8350   } else {
8351     // We can't display the parentheses, so just show the bare note.
8352     Self.Diag(Loc, Note) << ParenRange;
8353   }
8354 }
8355 
8356 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8357   return BinaryOperator::isAdditiveOp(Opc) ||
8358          BinaryOperator::isMultiplicativeOp(Opc) ||
8359          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8360   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8361   // not any of the logical operators.  Bitwise-xor is commonly used as a
8362   // logical-xor because there is no logical-xor operator.  The logical
8363   // operators, including uses of xor, have a high false positive rate for
8364   // precedence warnings.
8365 }
8366 
8367 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8368 /// expression, either using a built-in or overloaded operator,
8369 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8370 /// expression.
8371 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8372                                    Expr **RHSExprs) {
8373   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8374   E = E->IgnoreImpCasts();
8375   E = E->IgnoreConversionOperator();
8376   E = E->IgnoreImpCasts();
8377   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8378     E = MTE->getSubExpr();
8379     E = E->IgnoreImpCasts();
8380   }
8381 
8382   // Built-in binary operator.
8383   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8384     if (IsArithmeticOp(OP->getOpcode())) {
8385       *Opcode = OP->getOpcode();
8386       *RHSExprs = OP->getRHS();
8387       return true;
8388     }
8389   }
8390 
8391   // Overloaded operator.
8392   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8393     if (Call->getNumArgs() != 2)
8394       return false;
8395 
8396     // Make sure this is really a binary operator that is safe to pass into
8397     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8398     OverloadedOperatorKind OO = Call->getOperator();
8399     if (OO < OO_Plus || OO > OO_Arrow ||
8400         OO == OO_PlusPlus || OO == OO_MinusMinus)
8401       return false;
8402 
8403     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8404     if (IsArithmeticOp(OpKind)) {
8405       *Opcode = OpKind;
8406       *RHSExprs = Call->getArg(1);
8407       return true;
8408     }
8409   }
8410 
8411   return false;
8412 }
8413 
8414 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8415 /// or is a logical expression such as (x==y) which has int type, but is
8416 /// commonly interpreted as boolean.
8417 static bool ExprLooksBoolean(Expr *E) {
8418   E = E->IgnoreParenImpCasts();
8419 
8420   if (E->getType()->isBooleanType())
8421     return true;
8422   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8423     return OP->isComparisonOp() || OP->isLogicalOp();
8424   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8425     return OP->getOpcode() == UO_LNot;
8426   if (E->getType()->isPointerType())
8427     return true;
8428   // FIXME: What about overloaded operator calls returning "unspecified boolean
8429   // type"s (commonly pointer-to-members)?
8430 
8431   return false;
8432 }
8433 
8434 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8435 /// and binary operator are mixed in a way that suggests the programmer assumed
8436 /// the conditional operator has higher precedence, for example:
8437 /// "int x = a + someBinaryCondition ? 1 : 2".
8438 static void DiagnoseConditionalPrecedence(Sema &Self,
8439                                           SourceLocation OpLoc,
8440                                           Expr *Condition,
8441                                           Expr *LHSExpr,
8442                                           Expr *RHSExpr) {
8443   BinaryOperatorKind CondOpcode;
8444   Expr *CondRHS;
8445 
8446   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8447     return;
8448   if (!ExprLooksBoolean(CondRHS))
8449     return;
8450 
8451   // The condition is an arithmetic binary expression, with a right-
8452   // hand side that looks boolean, so warn.
8453 
8454   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8455                         ? diag::warn_precedence_bitwise_conditional
8456                         : diag::warn_precedence_conditional;
8457 
8458   Self.Diag(OpLoc, DiagID)
8459       << Condition->getSourceRange()
8460       << BinaryOperator::getOpcodeStr(CondOpcode);
8461 
8462   SuggestParentheses(
8463       Self, OpLoc,
8464       Self.PDiag(diag::note_precedence_silence)
8465           << BinaryOperator::getOpcodeStr(CondOpcode),
8466       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8467 
8468   SuggestParentheses(Self, OpLoc,
8469                      Self.PDiag(diag::note_precedence_conditional_first),
8470                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8471 }
8472 
8473 /// Compute the nullability of a conditional expression.
8474 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8475                                               QualType LHSTy, QualType RHSTy,
8476                                               ASTContext &Ctx) {
8477   if (!ResTy->isAnyPointerType())
8478     return ResTy;
8479 
8480   auto GetNullability = [&Ctx](QualType Ty) {
8481     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8482     if (Kind)
8483       return *Kind;
8484     return NullabilityKind::Unspecified;
8485   };
8486 
8487   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8488   NullabilityKind MergedKind;
8489 
8490   // Compute nullability of a binary conditional expression.
8491   if (IsBin) {
8492     if (LHSKind == NullabilityKind::NonNull)
8493       MergedKind = NullabilityKind::NonNull;
8494     else
8495       MergedKind = RHSKind;
8496   // Compute nullability of a normal conditional expression.
8497   } else {
8498     if (LHSKind == NullabilityKind::Nullable ||
8499         RHSKind == NullabilityKind::Nullable)
8500       MergedKind = NullabilityKind::Nullable;
8501     else if (LHSKind == NullabilityKind::NonNull)
8502       MergedKind = RHSKind;
8503     else if (RHSKind == NullabilityKind::NonNull)
8504       MergedKind = LHSKind;
8505     else
8506       MergedKind = NullabilityKind::Unspecified;
8507   }
8508 
8509   // Return if ResTy already has the correct nullability.
8510   if (GetNullability(ResTy) == MergedKind)
8511     return ResTy;
8512 
8513   // Strip all nullability from ResTy.
8514   while (ResTy->getNullability(Ctx))
8515     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8516 
8517   // Create a new AttributedType with the new nullability kind.
8518   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8519   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8520 }
8521 
8522 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8523 /// in the case of a the GNU conditional expr extension.
8524 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8525                                     SourceLocation ColonLoc,
8526                                     Expr *CondExpr, Expr *LHSExpr,
8527                                     Expr *RHSExpr) {
8528   if (!getLangOpts().CPlusPlus) {
8529     // C cannot handle TypoExpr nodes in the condition because it
8530     // doesn't handle dependent types properly, so make sure any TypoExprs have
8531     // been dealt with before checking the operands.
8532     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8533     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8534     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8535 
8536     if (!CondResult.isUsable())
8537       return ExprError();
8538 
8539     if (LHSExpr) {
8540       if (!LHSResult.isUsable())
8541         return ExprError();
8542     }
8543 
8544     if (!RHSResult.isUsable())
8545       return ExprError();
8546 
8547     CondExpr = CondResult.get();
8548     LHSExpr = LHSResult.get();
8549     RHSExpr = RHSResult.get();
8550   }
8551 
8552   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8553   // was the condition.
8554   OpaqueValueExpr *opaqueValue = nullptr;
8555   Expr *commonExpr = nullptr;
8556   if (!LHSExpr) {
8557     commonExpr = CondExpr;
8558     // Lower out placeholder types first.  This is important so that we don't
8559     // try to capture a placeholder. This happens in few cases in C++; such
8560     // as Objective-C++'s dictionary subscripting syntax.
8561     if (commonExpr->hasPlaceholderType()) {
8562       ExprResult result = CheckPlaceholderExpr(commonExpr);
8563       if (!result.isUsable()) return ExprError();
8564       commonExpr = result.get();
8565     }
8566     // We usually want to apply unary conversions *before* saving, except
8567     // in the special case of a C++ l-value conditional.
8568     if (!(getLangOpts().CPlusPlus
8569           && !commonExpr->isTypeDependent()
8570           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8571           && commonExpr->isGLValue()
8572           && commonExpr->isOrdinaryOrBitFieldObject()
8573           && RHSExpr->isOrdinaryOrBitFieldObject()
8574           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8575       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8576       if (commonRes.isInvalid())
8577         return ExprError();
8578       commonExpr = commonRes.get();
8579     }
8580 
8581     // If the common expression is a class or array prvalue, materialize it
8582     // so that we can safely refer to it multiple times.
8583     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8584                                    commonExpr->getType()->isArrayType())) {
8585       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8586       if (MatExpr.isInvalid())
8587         return ExprError();
8588       commonExpr = MatExpr.get();
8589     }
8590 
8591     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8592                                                 commonExpr->getType(),
8593                                                 commonExpr->getValueKind(),
8594                                                 commonExpr->getObjectKind(),
8595                                                 commonExpr);
8596     LHSExpr = CondExpr = opaqueValue;
8597   }
8598 
8599   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8600   ExprValueKind VK = VK_RValue;
8601   ExprObjectKind OK = OK_Ordinary;
8602   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8603   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8604                                              VK, OK, QuestionLoc);
8605   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8606       RHS.isInvalid())
8607     return ExprError();
8608 
8609   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8610                                 RHS.get());
8611 
8612   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8613 
8614   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8615                                          Context);
8616 
8617   if (!commonExpr)
8618     return new (Context)
8619         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8620                             RHS.get(), result, VK, OK);
8621 
8622   return new (Context) BinaryConditionalOperator(
8623       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8624       ColonLoc, result, VK, OK);
8625 }
8626 
8627 // Check if we have a conversion between incompatible cmse function pointer
8628 // types, that is, a conversion between a function pointer with the
8629 // cmse_nonsecure_call attribute and one without.
8630 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8631                                           QualType ToType) {
8632   if (const auto *ToFn =
8633           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8634     if (const auto *FromFn =
8635             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8636       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8637       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8638 
8639       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8640     }
8641   }
8642   return false;
8643 }
8644 
8645 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8646 // being closely modeled after the C99 spec:-). The odd characteristic of this
8647 // routine is it effectively iqnores the qualifiers on the top level pointee.
8648 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8649 // FIXME: add a couple examples in this comment.
8650 static Sema::AssignConvertType
8651 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8652   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8653   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8654 
8655   // get the "pointed to" type (ignoring qualifiers at the top level)
8656   const Type *lhptee, *rhptee;
8657   Qualifiers lhq, rhq;
8658   std::tie(lhptee, lhq) =
8659       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8660   std::tie(rhptee, rhq) =
8661       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8662 
8663   Sema::AssignConvertType ConvTy = Sema::Compatible;
8664 
8665   // C99 6.5.16.1p1: This following citation is common to constraints
8666   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8667   // qualifiers of the type *pointed to* by the right;
8668 
8669   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8670   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8671       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8672     // Ignore lifetime for further calculation.
8673     lhq.removeObjCLifetime();
8674     rhq.removeObjCLifetime();
8675   }
8676 
8677   if (!lhq.compatiblyIncludes(rhq)) {
8678     // Treat address-space mismatches as fatal.
8679     if (!lhq.isAddressSpaceSupersetOf(rhq))
8680       return Sema::IncompatiblePointerDiscardsQualifiers;
8681 
8682     // It's okay to add or remove GC or lifetime qualifiers when converting to
8683     // and from void*.
8684     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8685                         .compatiblyIncludes(
8686                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8687              && (lhptee->isVoidType() || rhptee->isVoidType()))
8688       ; // keep old
8689 
8690     // Treat lifetime mismatches as fatal.
8691     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8692       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8693 
8694     // For GCC/MS compatibility, other qualifier mismatches are treated
8695     // as still compatible in C.
8696     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8697   }
8698 
8699   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8700   // incomplete type and the other is a pointer to a qualified or unqualified
8701   // version of void...
8702   if (lhptee->isVoidType()) {
8703     if (rhptee->isIncompleteOrObjectType())
8704       return ConvTy;
8705 
8706     // As an extension, we allow cast to/from void* to function pointer.
8707     assert(rhptee->isFunctionType());
8708     return Sema::FunctionVoidPointer;
8709   }
8710 
8711   if (rhptee->isVoidType()) {
8712     if (lhptee->isIncompleteOrObjectType())
8713       return ConvTy;
8714 
8715     // As an extension, we allow cast to/from void* to function pointer.
8716     assert(lhptee->isFunctionType());
8717     return Sema::FunctionVoidPointer;
8718   }
8719 
8720   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8721   // unqualified versions of compatible types, ...
8722   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8723   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8724     // Check if the pointee types are compatible ignoring the sign.
8725     // We explicitly check for char so that we catch "char" vs
8726     // "unsigned char" on systems where "char" is unsigned.
8727     if (lhptee->isCharType())
8728       ltrans = S.Context.UnsignedCharTy;
8729     else if (lhptee->hasSignedIntegerRepresentation())
8730       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8731 
8732     if (rhptee->isCharType())
8733       rtrans = S.Context.UnsignedCharTy;
8734     else if (rhptee->hasSignedIntegerRepresentation())
8735       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8736 
8737     if (ltrans == rtrans) {
8738       // Types are compatible ignoring the sign. Qualifier incompatibility
8739       // takes priority over sign incompatibility because the sign
8740       // warning can be disabled.
8741       if (ConvTy != Sema::Compatible)
8742         return ConvTy;
8743 
8744       return Sema::IncompatiblePointerSign;
8745     }
8746 
8747     // If we are a multi-level pointer, it's possible that our issue is simply
8748     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8749     // the eventual target type is the same and the pointers have the same
8750     // level of indirection, this must be the issue.
8751     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8752       do {
8753         std::tie(lhptee, lhq) =
8754           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8755         std::tie(rhptee, rhq) =
8756           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8757 
8758         // Inconsistent address spaces at this point is invalid, even if the
8759         // address spaces would be compatible.
8760         // FIXME: This doesn't catch address space mismatches for pointers of
8761         // different nesting levels, like:
8762         //   __local int *** a;
8763         //   int ** b = a;
8764         // It's not clear how to actually determine when such pointers are
8765         // invalidly incompatible.
8766         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8767           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8768 
8769       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8770 
8771       if (lhptee == rhptee)
8772         return Sema::IncompatibleNestedPointerQualifiers;
8773     }
8774 
8775     // General pointer incompatibility takes priority over qualifiers.
8776     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8777       return Sema::IncompatibleFunctionPointer;
8778     return Sema::IncompatiblePointer;
8779   }
8780   if (!S.getLangOpts().CPlusPlus &&
8781       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8782     return Sema::IncompatibleFunctionPointer;
8783   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8784     return Sema::IncompatibleFunctionPointer;
8785   return ConvTy;
8786 }
8787 
8788 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8789 /// block pointer types are compatible or whether a block and normal pointer
8790 /// are compatible. It is more restrict than comparing two function pointer
8791 // types.
8792 static Sema::AssignConvertType
8793 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8794                                     QualType RHSType) {
8795   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8796   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8797 
8798   QualType lhptee, rhptee;
8799 
8800   // get the "pointed to" type (ignoring qualifiers at the top level)
8801   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8802   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8803 
8804   // In C++, the types have to match exactly.
8805   if (S.getLangOpts().CPlusPlus)
8806     return Sema::IncompatibleBlockPointer;
8807 
8808   Sema::AssignConvertType ConvTy = Sema::Compatible;
8809 
8810   // For blocks we enforce that qualifiers are identical.
8811   Qualifiers LQuals = lhptee.getLocalQualifiers();
8812   Qualifiers RQuals = rhptee.getLocalQualifiers();
8813   if (S.getLangOpts().OpenCL) {
8814     LQuals.removeAddressSpace();
8815     RQuals.removeAddressSpace();
8816   }
8817   if (LQuals != RQuals)
8818     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8819 
8820   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8821   // assignment.
8822   // The current behavior is similar to C++ lambdas. A block might be
8823   // assigned to a variable iff its return type and parameters are compatible
8824   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8825   // an assignment. Presumably it should behave in way that a function pointer
8826   // assignment does in C, so for each parameter and return type:
8827   //  * CVR and address space of LHS should be a superset of CVR and address
8828   //  space of RHS.
8829   //  * unqualified types should be compatible.
8830   if (S.getLangOpts().OpenCL) {
8831     if (!S.Context.typesAreBlockPointerCompatible(
8832             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8833             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8834       return Sema::IncompatibleBlockPointer;
8835   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8836     return Sema::IncompatibleBlockPointer;
8837 
8838   return ConvTy;
8839 }
8840 
8841 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8842 /// for assignment compatibility.
8843 static Sema::AssignConvertType
8844 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8845                                    QualType RHSType) {
8846   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8847   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8848 
8849   if (LHSType->isObjCBuiltinType()) {
8850     // Class is not compatible with ObjC object pointers.
8851     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8852         !RHSType->isObjCQualifiedClassType())
8853       return Sema::IncompatiblePointer;
8854     return Sema::Compatible;
8855   }
8856   if (RHSType->isObjCBuiltinType()) {
8857     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8858         !LHSType->isObjCQualifiedClassType())
8859       return Sema::IncompatiblePointer;
8860     return Sema::Compatible;
8861   }
8862   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8863   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8864 
8865   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8866       // make an exception for id<P>
8867       !LHSType->isObjCQualifiedIdType())
8868     return Sema::CompatiblePointerDiscardsQualifiers;
8869 
8870   if (S.Context.typesAreCompatible(LHSType, RHSType))
8871     return Sema::Compatible;
8872   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8873     return Sema::IncompatibleObjCQualifiedId;
8874   return Sema::IncompatiblePointer;
8875 }
8876 
8877 Sema::AssignConvertType
8878 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8879                                  QualType LHSType, QualType RHSType) {
8880   // Fake up an opaque expression.  We don't actually care about what
8881   // cast operations are required, so if CheckAssignmentConstraints
8882   // adds casts to this they'll be wasted, but fortunately that doesn't
8883   // usually happen on valid code.
8884   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8885   ExprResult RHSPtr = &RHSExpr;
8886   CastKind K;
8887 
8888   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8889 }
8890 
8891 /// This helper function returns true if QT is a vector type that has element
8892 /// type ElementType.
8893 static bool isVector(QualType QT, QualType ElementType) {
8894   if (const VectorType *VT = QT->getAs<VectorType>())
8895     return VT->getElementType().getCanonicalType() == ElementType;
8896   return false;
8897 }
8898 
8899 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8900 /// has code to accommodate several GCC extensions when type checking
8901 /// pointers. Here are some objectionable examples that GCC considers warnings:
8902 ///
8903 ///  int a, *pint;
8904 ///  short *pshort;
8905 ///  struct foo *pfoo;
8906 ///
8907 ///  pint = pshort; // warning: assignment from incompatible pointer type
8908 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8909 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8910 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8911 ///
8912 /// As a result, the code for dealing with pointers is more complex than the
8913 /// C99 spec dictates.
8914 ///
8915 /// Sets 'Kind' for any result kind except Incompatible.
8916 Sema::AssignConvertType
8917 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8918                                  CastKind &Kind, bool ConvertRHS) {
8919   QualType RHSType = RHS.get()->getType();
8920   QualType OrigLHSType = LHSType;
8921 
8922   // Get canonical types.  We're not formatting these types, just comparing
8923   // them.
8924   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8925   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8926 
8927   // Common case: no conversion required.
8928   if (LHSType == RHSType) {
8929     Kind = CK_NoOp;
8930     return Compatible;
8931   }
8932 
8933   // If we have an atomic type, try a non-atomic assignment, then just add an
8934   // atomic qualification step.
8935   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8936     Sema::AssignConvertType result =
8937       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8938     if (result != Compatible)
8939       return result;
8940     if (Kind != CK_NoOp && ConvertRHS)
8941       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8942     Kind = CK_NonAtomicToAtomic;
8943     return Compatible;
8944   }
8945 
8946   // If the left-hand side is a reference type, then we are in a
8947   // (rare!) case where we've allowed the use of references in C,
8948   // e.g., as a parameter type in a built-in function. In this case,
8949   // just make sure that the type referenced is compatible with the
8950   // right-hand side type. The caller is responsible for adjusting
8951   // LHSType so that the resulting expression does not have reference
8952   // type.
8953   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8954     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8955       Kind = CK_LValueBitCast;
8956       return Compatible;
8957     }
8958     return Incompatible;
8959   }
8960 
8961   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8962   // to the same ExtVector type.
8963   if (LHSType->isExtVectorType()) {
8964     if (RHSType->isExtVectorType())
8965       return Incompatible;
8966     if (RHSType->isArithmeticType()) {
8967       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8968       if (ConvertRHS)
8969         RHS = prepareVectorSplat(LHSType, RHS.get());
8970       Kind = CK_VectorSplat;
8971       return Compatible;
8972     }
8973   }
8974 
8975   // Conversions to or from vector type.
8976   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8977     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8978       // Allow assignments of an AltiVec vector type to an equivalent GCC
8979       // vector type and vice versa
8980       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8981         Kind = CK_BitCast;
8982         return Compatible;
8983       }
8984 
8985       // If we are allowing lax vector conversions, and LHS and RHS are both
8986       // vectors, the total size only needs to be the same. This is a bitcast;
8987       // no bits are changed but the result type is different.
8988       if (isLaxVectorConversion(RHSType, LHSType)) {
8989         Kind = CK_BitCast;
8990         return IncompatibleVectors;
8991       }
8992     }
8993 
8994     // When the RHS comes from another lax conversion (e.g. binops between
8995     // scalars and vectors) the result is canonicalized as a vector. When the
8996     // LHS is also a vector, the lax is allowed by the condition above. Handle
8997     // the case where LHS is a scalar.
8998     if (LHSType->isScalarType()) {
8999       const VectorType *VecType = RHSType->getAs<VectorType>();
9000       if (VecType && VecType->getNumElements() == 1 &&
9001           isLaxVectorConversion(RHSType, LHSType)) {
9002         ExprResult *VecExpr = &RHS;
9003         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9004         Kind = CK_BitCast;
9005         return Compatible;
9006       }
9007     }
9008 
9009     return Incompatible;
9010   }
9011 
9012   // Diagnose attempts to convert between __float128 and long double where
9013   // such conversions currently can't be handled.
9014   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9015     return Incompatible;
9016 
9017   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9018   // discards the imaginary part.
9019   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9020       !LHSType->getAs<ComplexType>())
9021     return Incompatible;
9022 
9023   // Arithmetic conversions.
9024   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9025       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9026     if (ConvertRHS)
9027       Kind = PrepareScalarCast(RHS, LHSType);
9028     return Compatible;
9029   }
9030 
9031   // Conversions to normal pointers.
9032   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9033     // U* -> T*
9034     if (isa<PointerType>(RHSType)) {
9035       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9036       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9037       if (AddrSpaceL != AddrSpaceR)
9038         Kind = CK_AddressSpaceConversion;
9039       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9040         Kind = CK_NoOp;
9041       else
9042         Kind = CK_BitCast;
9043       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9044     }
9045 
9046     // int -> T*
9047     if (RHSType->isIntegerType()) {
9048       Kind = CK_IntegralToPointer; // FIXME: null?
9049       return IntToPointer;
9050     }
9051 
9052     // C pointers are not compatible with ObjC object pointers,
9053     // with two exceptions:
9054     if (isa<ObjCObjectPointerType>(RHSType)) {
9055       //  - conversions to void*
9056       if (LHSPointer->getPointeeType()->isVoidType()) {
9057         Kind = CK_BitCast;
9058         return Compatible;
9059       }
9060 
9061       //  - conversions from 'Class' to the redefinition type
9062       if (RHSType->isObjCClassType() &&
9063           Context.hasSameType(LHSType,
9064                               Context.getObjCClassRedefinitionType())) {
9065         Kind = CK_BitCast;
9066         return Compatible;
9067       }
9068 
9069       Kind = CK_BitCast;
9070       return IncompatiblePointer;
9071     }
9072 
9073     // U^ -> void*
9074     if (RHSType->getAs<BlockPointerType>()) {
9075       if (LHSPointer->getPointeeType()->isVoidType()) {
9076         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9077         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9078                                 ->getPointeeType()
9079                                 .getAddressSpace();
9080         Kind =
9081             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9082         return Compatible;
9083       }
9084     }
9085 
9086     return Incompatible;
9087   }
9088 
9089   // Conversions to block pointers.
9090   if (isa<BlockPointerType>(LHSType)) {
9091     // U^ -> T^
9092     if (RHSType->isBlockPointerType()) {
9093       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9094                               ->getPointeeType()
9095                               .getAddressSpace();
9096       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9097                               ->getPointeeType()
9098                               .getAddressSpace();
9099       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9100       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9101     }
9102 
9103     // int or null -> T^
9104     if (RHSType->isIntegerType()) {
9105       Kind = CK_IntegralToPointer; // FIXME: null
9106       return IntToBlockPointer;
9107     }
9108 
9109     // id -> T^
9110     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9111       Kind = CK_AnyPointerToBlockPointerCast;
9112       return Compatible;
9113     }
9114 
9115     // void* -> T^
9116     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9117       if (RHSPT->getPointeeType()->isVoidType()) {
9118         Kind = CK_AnyPointerToBlockPointerCast;
9119         return Compatible;
9120       }
9121 
9122     return Incompatible;
9123   }
9124 
9125   // Conversions to Objective-C pointers.
9126   if (isa<ObjCObjectPointerType>(LHSType)) {
9127     // A* -> B*
9128     if (RHSType->isObjCObjectPointerType()) {
9129       Kind = CK_BitCast;
9130       Sema::AssignConvertType result =
9131         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9132       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9133           result == Compatible &&
9134           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9135         result = IncompatibleObjCWeakRef;
9136       return result;
9137     }
9138 
9139     // int or null -> A*
9140     if (RHSType->isIntegerType()) {
9141       Kind = CK_IntegralToPointer; // FIXME: null
9142       return IntToPointer;
9143     }
9144 
9145     // In general, C pointers are not compatible with ObjC object pointers,
9146     // with two exceptions:
9147     if (isa<PointerType>(RHSType)) {
9148       Kind = CK_CPointerToObjCPointerCast;
9149 
9150       //  - conversions from 'void*'
9151       if (RHSType->isVoidPointerType()) {
9152         return Compatible;
9153       }
9154 
9155       //  - conversions to 'Class' from its redefinition type
9156       if (LHSType->isObjCClassType() &&
9157           Context.hasSameType(RHSType,
9158                               Context.getObjCClassRedefinitionType())) {
9159         return Compatible;
9160       }
9161 
9162       return IncompatiblePointer;
9163     }
9164 
9165     // Only under strict condition T^ is compatible with an Objective-C pointer.
9166     if (RHSType->isBlockPointerType() &&
9167         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9168       if (ConvertRHS)
9169         maybeExtendBlockObject(RHS);
9170       Kind = CK_BlockPointerToObjCPointerCast;
9171       return Compatible;
9172     }
9173 
9174     return Incompatible;
9175   }
9176 
9177   // Conversions from pointers that are not covered by the above.
9178   if (isa<PointerType>(RHSType)) {
9179     // T* -> _Bool
9180     if (LHSType == Context.BoolTy) {
9181       Kind = CK_PointerToBoolean;
9182       return Compatible;
9183     }
9184 
9185     // T* -> int
9186     if (LHSType->isIntegerType()) {
9187       Kind = CK_PointerToIntegral;
9188       return PointerToInt;
9189     }
9190 
9191     return Incompatible;
9192   }
9193 
9194   // Conversions from Objective-C pointers that are not covered by the above.
9195   if (isa<ObjCObjectPointerType>(RHSType)) {
9196     // T* -> _Bool
9197     if (LHSType == Context.BoolTy) {
9198       Kind = CK_PointerToBoolean;
9199       return Compatible;
9200     }
9201 
9202     // T* -> int
9203     if (LHSType->isIntegerType()) {
9204       Kind = CK_PointerToIntegral;
9205       return PointerToInt;
9206     }
9207 
9208     return Incompatible;
9209   }
9210 
9211   // struct A -> struct B
9212   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9213     if (Context.typesAreCompatible(LHSType, RHSType)) {
9214       Kind = CK_NoOp;
9215       return Compatible;
9216     }
9217   }
9218 
9219   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9220     Kind = CK_IntToOCLSampler;
9221     return Compatible;
9222   }
9223 
9224   return Incompatible;
9225 }
9226 
9227 /// Constructs a transparent union from an expression that is
9228 /// used to initialize the transparent union.
9229 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9230                                       ExprResult &EResult, QualType UnionType,
9231                                       FieldDecl *Field) {
9232   // Build an initializer list that designates the appropriate member
9233   // of the transparent union.
9234   Expr *E = EResult.get();
9235   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9236                                                    E, SourceLocation());
9237   Initializer->setType(UnionType);
9238   Initializer->setInitializedFieldInUnion(Field);
9239 
9240   // Build a compound literal constructing a value of the transparent
9241   // union type from this initializer list.
9242   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9243   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9244                                         VK_RValue, Initializer, false);
9245 }
9246 
9247 Sema::AssignConvertType
9248 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9249                                                ExprResult &RHS) {
9250   QualType RHSType = RHS.get()->getType();
9251 
9252   // If the ArgType is a Union type, we want to handle a potential
9253   // transparent_union GCC extension.
9254   const RecordType *UT = ArgType->getAsUnionType();
9255   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9256     return Incompatible;
9257 
9258   // The field to initialize within the transparent union.
9259   RecordDecl *UD = UT->getDecl();
9260   FieldDecl *InitField = nullptr;
9261   // It's compatible if the expression matches any of the fields.
9262   for (auto *it : UD->fields()) {
9263     if (it->getType()->isPointerType()) {
9264       // If the transparent union contains a pointer type, we allow:
9265       // 1) void pointer
9266       // 2) null pointer constant
9267       if (RHSType->isPointerType())
9268         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9269           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9270           InitField = it;
9271           break;
9272         }
9273 
9274       if (RHS.get()->isNullPointerConstant(Context,
9275                                            Expr::NPC_ValueDependentIsNull)) {
9276         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9277                                 CK_NullToPointer);
9278         InitField = it;
9279         break;
9280       }
9281     }
9282 
9283     CastKind Kind;
9284     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9285           == Compatible) {
9286       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9287       InitField = it;
9288       break;
9289     }
9290   }
9291 
9292   if (!InitField)
9293     return Incompatible;
9294 
9295   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9296   return Compatible;
9297 }
9298 
9299 Sema::AssignConvertType
9300 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9301                                        bool Diagnose,
9302                                        bool DiagnoseCFAudited,
9303                                        bool ConvertRHS) {
9304   // We need to be able to tell the caller whether we diagnosed a problem, if
9305   // they ask us to issue diagnostics.
9306   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9307 
9308   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9309   // we can't avoid *all* modifications at the moment, so we need some somewhere
9310   // to put the updated value.
9311   ExprResult LocalRHS = CallerRHS;
9312   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9313 
9314   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9315     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9316       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9317           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9318         Diag(RHS.get()->getExprLoc(),
9319              diag::warn_noderef_to_dereferenceable_pointer)
9320             << RHS.get()->getSourceRange();
9321       }
9322     }
9323   }
9324 
9325   if (getLangOpts().CPlusPlus) {
9326     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9327       // C++ 5.17p3: If the left operand is not of class type, the
9328       // expression is implicitly converted (C++ 4) to the
9329       // cv-unqualified type of the left operand.
9330       QualType RHSType = RHS.get()->getType();
9331       if (Diagnose) {
9332         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9333                                         AA_Assigning);
9334       } else {
9335         ImplicitConversionSequence ICS =
9336             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9337                                   /*SuppressUserConversions=*/false,
9338                                   AllowedExplicit::None,
9339                                   /*InOverloadResolution=*/false,
9340                                   /*CStyle=*/false,
9341                                   /*AllowObjCWritebackConversion=*/false);
9342         if (ICS.isFailure())
9343           return Incompatible;
9344         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9345                                         ICS, AA_Assigning);
9346       }
9347       if (RHS.isInvalid())
9348         return Incompatible;
9349       Sema::AssignConvertType result = Compatible;
9350       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9351           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9352         result = IncompatibleObjCWeakRef;
9353       return result;
9354     }
9355 
9356     // FIXME: Currently, we fall through and treat C++ classes like C
9357     // structures.
9358     // FIXME: We also fall through for atomics; not sure what should
9359     // happen there, though.
9360   } else if (RHS.get()->getType() == Context.OverloadTy) {
9361     // As a set of extensions to C, we support overloading on functions. These
9362     // functions need to be resolved here.
9363     DeclAccessPair DAP;
9364     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9365             RHS.get(), LHSType, /*Complain=*/false, DAP))
9366       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9367     else
9368       return Incompatible;
9369   }
9370 
9371   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9372   // a null pointer constant.
9373   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9374        LHSType->isBlockPointerType()) &&
9375       RHS.get()->isNullPointerConstant(Context,
9376                                        Expr::NPC_ValueDependentIsNull)) {
9377     if (Diagnose || ConvertRHS) {
9378       CastKind Kind;
9379       CXXCastPath Path;
9380       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9381                              /*IgnoreBaseAccess=*/false, Diagnose);
9382       if (ConvertRHS)
9383         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9384     }
9385     return Compatible;
9386   }
9387 
9388   // OpenCL queue_t type assignment.
9389   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9390                                  Context, Expr::NPC_ValueDependentIsNull)) {
9391     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9392     return Compatible;
9393   }
9394 
9395   // This check seems unnatural, however it is necessary to ensure the proper
9396   // conversion of functions/arrays. If the conversion were done for all
9397   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9398   // expressions that suppress this implicit conversion (&, sizeof).
9399   //
9400   // Suppress this for references: C++ 8.5.3p5.
9401   if (!LHSType->isReferenceType()) {
9402     // FIXME: We potentially allocate here even if ConvertRHS is false.
9403     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9404     if (RHS.isInvalid())
9405       return Incompatible;
9406   }
9407   CastKind Kind;
9408   Sema::AssignConvertType result =
9409     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9410 
9411   // C99 6.5.16.1p2: The value of the right operand is converted to the
9412   // type of the assignment expression.
9413   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9414   // so that we can use references in built-in functions even in C.
9415   // The getNonReferenceType() call makes sure that the resulting expression
9416   // does not have reference type.
9417   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9418     QualType Ty = LHSType.getNonLValueExprType(Context);
9419     Expr *E = RHS.get();
9420 
9421     // Check for various Objective-C errors. If we are not reporting
9422     // diagnostics and just checking for errors, e.g., during overload
9423     // resolution, return Incompatible to indicate the failure.
9424     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9425         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9426                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9427       if (!Diagnose)
9428         return Incompatible;
9429     }
9430     if (getLangOpts().ObjC &&
9431         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9432                                            E->getType(), E, Diagnose) ||
9433          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9434       if (!Diagnose)
9435         return Incompatible;
9436       // Replace the expression with a corrected version and continue so we
9437       // can find further errors.
9438       RHS = E;
9439       return Compatible;
9440     }
9441 
9442     if (ConvertRHS)
9443       RHS = ImpCastExprToType(E, Ty, Kind);
9444   }
9445 
9446   return result;
9447 }
9448 
9449 namespace {
9450 /// The original operand to an operator, prior to the application of the usual
9451 /// arithmetic conversions and converting the arguments of a builtin operator
9452 /// candidate.
9453 struct OriginalOperand {
9454   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9455     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9456       Op = MTE->getSubExpr();
9457     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9458       Op = BTE->getSubExpr();
9459     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9460       Orig = ICE->getSubExprAsWritten();
9461       Conversion = ICE->getConversionFunction();
9462     }
9463   }
9464 
9465   QualType getType() const { return Orig->getType(); }
9466 
9467   Expr *Orig;
9468   NamedDecl *Conversion;
9469 };
9470 }
9471 
9472 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9473                                ExprResult &RHS) {
9474   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9475 
9476   Diag(Loc, diag::err_typecheck_invalid_operands)
9477     << OrigLHS.getType() << OrigRHS.getType()
9478     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9479 
9480   // If a user-defined conversion was applied to either of the operands prior
9481   // to applying the built-in operator rules, tell the user about it.
9482   if (OrigLHS.Conversion) {
9483     Diag(OrigLHS.Conversion->getLocation(),
9484          diag::note_typecheck_invalid_operands_converted)
9485       << 0 << LHS.get()->getType();
9486   }
9487   if (OrigRHS.Conversion) {
9488     Diag(OrigRHS.Conversion->getLocation(),
9489          diag::note_typecheck_invalid_operands_converted)
9490       << 1 << RHS.get()->getType();
9491   }
9492 
9493   return QualType();
9494 }
9495 
9496 // Diagnose cases where a scalar was implicitly converted to a vector and
9497 // diagnose the underlying types. Otherwise, diagnose the error
9498 // as invalid vector logical operands for non-C++ cases.
9499 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9500                                             ExprResult &RHS) {
9501   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9502   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9503 
9504   bool LHSNatVec = LHSType->isVectorType();
9505   bool RHSNatVec = RHSType->isVectorType();
9506 
9507   if (!(LHSNatVec && RHSNatVec)) {
9508     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9509     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9510     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9511         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9512         << Vector->getSourceRange();
9513     return QualType();
9514   }
9515 
9516   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9517       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9518       << RHS.get()->getSourceRange();
9519 
9520   return QualType();
9521 }
9522 
9523 /// Try to convert a value of non-vector type to a vector type by converting
9524 /// the type to the element type of the vector and then performing a splat.
9525 /// If the language is OpenCL, we only use conversions that promote scalar
9526 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9527 /// for float->int.
9528 ///
9529 /// OpenCL V2.0 6.2.6.p2:
9530 /// An error shall occur if any scalar operand type has greater rank
9531 /// than the type of the vector element.
9532 ///
9533 /// \param scalar - if non-null, actually perform the conversions
9534 /// \return true if the operation fails (but without diagnosing the failure)
9535 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9536                                      QualType scalarTy,
9537                                      QualType vectorEltTy,
9538                                      QualType vectorTy,
9539                                      unsigned &DiagID) {
9540   // The conversion to apply to the scalar before splatting it,
9541   // if necessary.
9542   CastKind scalarCast = CK_NoOp;
9543 
9544   if (vectorEltTy->isIntegralType(S.Context)) {
9545     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9546         (scalarTy->isIntegerType() &&
9547          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9548       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9549       return true;
9550     }
9551     if (!scalarTy->isIntegralType(S.Context))
9552       return true;
9553     scalarCast = CK_IntegralCast;
9554   } else if (vectorEltTy->isRealFloatingType()) {
9555     if (scalarTy->isRealFloatingType()) {
9556       if (S.getLangOpts().OpenCL &&
9557           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9558         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9559         return true;
9560       }
9561       scalarCast = CK_FloatingCast;
9562     }
9563     else if (scalarTy->isIntegralType(S.Context))
9564       scalarCast = CK_IntegralToFloating;
9565     else
9566       return true;
9567   } else {
9568     return true;
9569   }
9570 
9571   // Adjust scalar if desired.
9572   if (scalar) {
9573     if (scalarCast != CK_NoOp)
9574       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9575     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9576   }
9577   return false;
9578 }
9579 
9580 /// Convert vector E to a vector with the same number of elements but different
9581 /// element type.
9582 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9583   const auto *VecTy = E->getType()->getAs<VectorType>();
9584   assert(VecTy && "Expression E must be a vector");
9585   QualType NewVecTy = S.Context.getVectorType(ElementType,
9586                                               VecTy->getNumElements(),
9587                                               VecTy->getVectorKind());
9588 
9589   // Look through the implicit cast. Return the subexpression if its type is
9590   // NewVecTy.
9591   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9592     if (ICE->getSubExpr()->getType() == NewVecTy)
9593       return ICE->getSubExpr();
9594 
9595   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9596   return S.ImpCastExprToType(E, NewVecTy, Cast);
9597 }
9598 
9599 /// Test if a (constant) integer Int can be casted to another integer type
9600 /// IntTy without losing precision.
9601 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9602                                       QualType OtherIntTy) {
9603   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9604 
9605   // Reject cases where the value of the Int is unknown as that would
9606   // possibly cause truncation, but accept cases where the scalar can be
9607   // demoted without loss of precision.
9608   Expr::EvalResult EVResult;
9609   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9610   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9611   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9612   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9613 
9614   if (CstInt) {
9615     // If the scalar is constant and is of a higher order and has more active
9616     // bits that the vector element type, reject it.
9617     llvm::APSInt Result = EVResult.Val.getInt();
9618     unsigned NumBits = IntSigned
9619                            ? (Result.isNegative() ? Result.getMinSignedBits()
9620                                                   : Result.getActiveBits())
9621                            : Result.getActiveBits();
9622     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9623       return true;
9624 
9625     // If the signedness of the scalar type and the vector element type
9626     // differs and the number of bits is greater than that of the vector
9627     // element reject it.
9628     return (IntSigned != OtherIntSigned &&
9629             NumBits > S.Context.getIntWidth(OtherIntTy));
9630   }
9631 
9632   // Reject cases where the value of the scalar is not constant and it's
9633   // order is greater than that of the vector element type.
9634   return (Order < 0);
9635 }
9636 
9637 /// Test if a (constant) integer Int can be casted to floating point type
9638 /// FloatTy without losing precision.
9639 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9640                                      QualType FloatTy) {
9641   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9642 
9643   // Determine if the integer constant can be expressed as a floating point
9644   // number of the appropriate type.
9645   Expr::EvalResult EVResult;
9646   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9647 
9648   uint64_t Bits = 0;
9649   if (CstInt) {
9650     // Reject constants that would be truncated if they were converted to
9651     // the floating point type. Test by simple to/from conversion.
9652     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9653     //        could be avoided if there was a convertFromAPInt method
9654     //        which could signal back if implicit truncation occurred.
9655     llvm::APSInt Result = EVResult.Val.getInt();
9656     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9657     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9658                            llvm::APFloat::rmTowardZero);
9659     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9660                              !IntTy->hasSignedIntegerRepresentation());
9661     bool Ignored = false;
9662     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9663                            &Ignored);
9664     if (Result != ConvertBack)
9665       return true;
9666   } else {
9667     // Reject types that cannot be fully encoded into the mantissa of
9668     // the float.
9669     Bits = S.Context.getTypeSize(IntTy);
9670     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9671         S.Context.getFloatTypeSemantics(FloatTy));
9672     if (Bits > FloatPrec)
9673       return true;
9674   }
9675 
9676   return false;
9677 }
9678 
9679 /// Attempt to convert and splat Scalar into a vector whose types matches
9680 /// Vector following GCC conversion rules. The rule is that implicit
9681 /// conversion can occur when Scalar can be casted to match Vector's element
9682 /// type without causing truncation of Scalar.
9683 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9684                                         ExprResult *Vector) {
9685   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9686   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9687   const VectorType *VT = VectorTy->getAs<VectorType>();
9688 
9689   assert(!isa<ExtVectorType>(VT) &&
9690          "ExtVectorTypes should not be handled here!");
9691 
9692   QualType VectorEltTy = VT->getElementType();
9693 
9694   // Reject cases where the vector element type or the scalar element type are
9695   // not integral or floating point types.
9696   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9697     return true;
9698 
9699   // The conversion to apply to the scalar before splatting it,
9700   // if necessary.
9701   CastKind ScalarCast = CK_NoOp;
9702 
9703   // Accept cases where the vector elements are integers and the scalar is
9704   // an integer.
9705   // FIXME: Notionally if the scalar was a floating point value with a precise
9706   //        integral representation, we could cast it to an appropriate integer
9707   //        type and then perform the rest of the checks here. GCC will perform
9708   //        this conversion in some cases as determined by the input language.
9709   //        We should accept it on a language independent basis.
9710   if (VectorEltTy->isIntegralType(S.Context) &&
9711       ScalarTy->isIntegralType(S.Context) &&
9712       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9713 
9714     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9715       return true;
9716 
9717     ScalarCast = CK_IntegralCast;
9718   } else if (VectorEltTy->isIntegralType(S.Context) &&
9719              ScalarTy->isRealFloatingType()) {
9720     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9721       ScalarCast = CK_FloatingToIntegral;
9722     else
9723       return true;
9724   } else if (VectorEltTy->isRealFloatingType()) {
9725     if (ScalarTy->isRealFloatingType()) {
9726 
9727       // Reject cases where the scalar type is not a constant and has a higher
9728       // Order than the vector element type.
9729       llvm::APFloat Result(0.0);
9730 
9731       // Determine whether this is a constant scalar. In the event that the
9732       // value is dependent (and thus cannot be evaluated by the constant
9733       // evaluator), skip the evaluation. This will then diagnose once the
9734       // expression is instantiated.
9735       bool CstScalar = Scalar->get()->isValueDependent() ||
9736                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9737       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9738       if (!CstScalar && Order < 0)
9739         return true;
9740 
9741       // If the scalar cannot be safely casted to the vector element type,
9742       // reject it.
9743       if (CstScalar) {
9744         bool Truncated = false;
9745         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9746                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9747         if (Truncated)
9748           return true;
9749       }
9750 
9751       ScalarCast = CK_FloatingCast;
9752     } else if (ScalarTy->isIntegralType(S.Context)) {
9753       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9754         return true;
9755 
9756       ScalarCast = CK_IntegralToFloating;
9757     } else
9758       return true;
9759   } else if (ScalarTy->isEnumeralType())
9760     return true;
9761 
9762   // Adjust scalar if desired.
9763   if (Scalar) {
9764     if (ScalarCast != CK_NoOp)
9765       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9766     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9767   }
9768   return false;
9769 }
9770 
9771 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9772                                    SourceLocation Loc, bool IsCompAssign,
9773                                    bool AllowBothBool,
9774                                    bool AllowBoolConversions) {
9775   if (!IsCompAssign) {
9776     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9777     if (LHS.isInvalid())
9778       return QualType();
9779   }
9780   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9781   if (RHS.isInvalid())
9782     return QualType();
9783 
9784   // For conversion purposes, we ignore any qualifiers.
9785   // For example, "const float" and "float" are equivalent.
9786   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9787   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9788 
9789   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9790   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9791   assert(LHSVecType || RHSVecType);
9792 
9793   // AltiVec-style "vector bool op vector bool" combinations are allowed
9794   // for some operators but not others.
9795   if (!AllowBothBool &&
9796       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9797       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9798     return InvalidOperands(Loc, LHS, RHS);
9799 
9800   // If the vector types are identical, return.
9801   if (Context.hasSameType(LHSType, RHSType))
9802     return LHSType;
9803 
9804   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9805   if (LHSVecType && RHSVecType &&
9806       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9807     if (isa<ExtVectorType>(LHSVecType)) {
9808       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9809       return LHSType;
9810     }
9811 
9812     if (!IsCompAssign)
9813       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9814     return RHSType;
9815   }
9816 
9817   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9818   // can be mixed, with the result being the non-bool type.  The non-bool
9819   // operand must have integer element type.
9820   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9821       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9822       (Context.getTypeSize(LHSVecType->getElementType()) ==
9823        Context.getTypeSize(RHSVecType->getElementType()))) {
9824     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9825         LHSVecType->getElementType()->isIntegerType() &&
9826         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9827       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9828       return LHSType;
9829     }
9830     if (!IsCompAssign &&
9831         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9832         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9833         RHSVecType->getElementType()->isIntegerType()) {
9834       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9835       return RHSType;
9836     }
9837   }
9838 
9839   // If there's a vector type and a scalar, try to convert the scalar to
9840   // the vector element type and splat.
9841   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9842   if (!RHSVecType) {
9843     if (isa<ExtVectorType>(LHSVecType)) {
9844       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9845                                     LHSVecType->getElementType(), LHSType,
9846                                     DiagID))
9847         return LHSType;
9848     } else {
9849       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9850         return LHSType;
9851     }
9852   }
9853   if (!LHSVecType) {
9854     if (isa<ExtVectorType>(RHSVecType)) {
9855       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9856                                     LHSType, RHSVecType->getElementType(),
9857                                     RHSType, DiagID))
9858         return RHSType;
9859     } else {
9860       if (LHS.get()->getValueKind() == VK_LValue ||
9861           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9862         return RHSType;
9863     }
9864   }
9865 
9866   // FIXME: The code below also handles conversion between vectors and
9867   // non-scalars, we should break this down into fine grained specific checks
9868   // and emit proper diagnostics.
9869   QualType VecType = LHSVecType ? LHSType : RHSType;
9870   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9871   QualType OtherType = LHSVecType ? RHSType : LHSType;
9872   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9873   if (isLaxVectorConversion(OtherType, VecType)) {
9874     // If we're allowing lax vector conversions, only the total (data) size
9875     // needs to be the same. For non compound assignment, if one of the types is
9876     // scalar, the result is always the vector type.
9877     if (!IsCompAssign) {
9878       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9879       return VecType;
9880     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9881     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9882     // type. Note that this is already done by non-compound assignments in
9883     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9884     // <1 x T> -> T. The result is also a vector type.
9885     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9886                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9887       ExprResult *RHSExpr = &RHS;
9888       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9889       return VecType;
9890     }
9891   }
9892 
9893   // Okay, the expression is invalid.
9894 
9895   // If there's a non-vector, non-real operand, diagnose that.
9896   if ((!RHSVecType && !RHSType->isRealType()) ||
9897       (!LHSVecType && !LHSType->isRealType())) {
9898     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9899       << LHSType << RHSType
9900       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9901     return QualType();
9902   }
9903 
9904   // OpenCL V1.1 6.2.6.p1:
9905   // If the operands are of more than one vector type, then an error shall
9906   // occur. Implicit conversions between vector types are not permitted, per
9907   // section 6.2.1.
9908   if (getLangOpts().OpenCL &&
9909       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9910       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9911     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9912                                                            << RHSType;
9913     return QualType();
9914   }
9915 
9916 
9917   // If there is a vector type that is not a ExtVector and a scalar, we reach
9918   // this point if scalar could not be converted to the vector's element type
9919   // without truncation.
9920   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9921       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9922     QualType Scalar = LHSVecType ? RHSType : LHSType;
9923     QualType Vector = LHSVecType ? LHSType : RHSType;
9924     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9925     Diag(Loc,
9926          diag::err_typecheck_vector_not_convertable_implict_truncation)
9927         << ScalarOrVector << Scalar << Vector;
9928 
9929     return QualType();
9930   }
9931 
9932   // Otherwise, use the generic diagnostic.
9933   Diag(Loc, DiagID)
9934     << LHSType << RHSType
9935     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9936   return QualType();
9937 }
9938 
9939 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9940 // expression.  These are mainly cases where the null pointer is used as an
9941 // integer instead of a pointer.
9942 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9943                                 SourceLocation Loc, bool IsCompare) {
9944   // The canonical way to check for a GNU null is with isNullPointerConstant,
9945   // but we use a bit of a hack here for speed; this is a relatively
9946   // hot path, and isNullPointerConstant is slow.
9947   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9948   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9949 
9950   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9951 
9952   // Avoid analyzing cases where the result will either be invalid (and
9953   // diagnosed as such) or entirely valid and not something to warn about.
9954   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9955       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9956     return;
9957 
9958   // Comparison operations would not make sense with a null pointer no matter
9959   // what the other expression is.
9960   if (!IsCompare) {
9961     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9962         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9963         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9964     return;
9965   }
9966 
9967   // The rest of the operations only make sense with a null pointer
9968   // if the other expression is a pointer.
9969   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9970       NonNullType->canDecayToPointerType())
9971     return;
9972 
9973   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9974       << LHSNull /* LHS is NULL */ << NonNullType
9975       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9976 }
9977 
9978 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9979                                           SourceLocation Loc) {
9980   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9981   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9982   if (!LUE || !RUE)
9983     return;
9984   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9985       RUE->getKind() != UETT_SizeOf)
9986     return;
9987 
9988   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9989   QualType LHSTy = LHSArg->getType();
9990   QualType RHSTy;
9991 
9992   if (RUE->isArgumentType())
9993     RHSTy = RUE->getArgumentType();
9994   else
9995     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9996 
9997   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9998     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9999       return;
10000 
10001     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10002     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10003       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10004         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10005             << LHSArgDecl;
10006     }
10007   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10008     QualType ArrayElemTy = ArrayTy->getElementType();
10009     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10010         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10011         ArrayElemTy->isCharType() ||
10012         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10013       return;
10014     S.Diag(Loc, diag::warn_division_sizeof_array)
10015         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10016     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10017       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10018         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10019             << LHSArgDecl;
10020     }
10021 
10022     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10023   }
10024 }
10025 
10026 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10027                                                ExprResult &RHS,
10028                                                SourceLocation Loc, bool IsDiv) {
10029   // Check for division/remainder by zero.
10030   Expr::EvalResult RHSValue;
10031   if (!RHS.get()->isValueDependent() &&
10032       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10033       RHSValue.Val.getInt() == 0)
10034     S.DiagRuntimeBehavior(Loc, RHS.get(),
10035                           S.PDiag(diag::warn_remainder_division_by_zero)
10036                             << IsDiv << RHS.get()->getSourceRange());
10037 }
10038 
10039 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10040                                            SourceLocation Loc,
10041                                            bool IsCompAssign, bool IsDiv) {
10042   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10043 
10044   if (LHS.get()->getType()->isVectorType() ||
10045       RHS.get()->getType()->isVectorType())
10046     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10047                                /*AllowBothBool*/getLangOpts().AltiVec,
10048                                /*AllowBoolConversions*/false);
10049   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10050                  RHS.get()->getType()->isConstantMatrixType()))
10051     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10052 
10053   QualType compType = UsualArithmeticConversions(
10054       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10055   if (LHS.isInvalid() || RHS.isInvalid())
10056     return QualType();
10057 
10058 
10059   if (compType.isNull() || !compType->isArithmeticType())
10060     return InvalidOperands(Loc, LHS, RHS);
10061   if (IsDiv) {
10062     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10063     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10064   }
10065   return compType;
10066 }
10067 
10068 QualType Sema::CheckRemainderOperands(
10069   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10070   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10071 
10072   if (LHS.get()->getType()->isVectorType() ||
10073       RHS.get()->getType()->isVectorType()) {
10074     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10075         RHS.get()->getType()->hasIntegerRepresentation())
10076       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10077                                  /*AllowBothBool*/getLangOpts().AltiVec,
10078                                  /*AllowBoolConversions*/false);
10079     return InvalidOperands(Loc, LHS, RHS);
10080   }
10081 
10082   QualType compType = UsualArithmeticConversions(
10083       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10084   if (LHS.isInvalid() || RHS.isInvalid())
10085     return QualType();
10086 
10087   if (compType.isNull() || !compType->isIntegerType())
10088     return InvalidOperands(Loc, LHS, RHS);
10089   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10090   return compType;
10091 }
10092 
10093 /// Diagnose invalid arithmetic on two void pointers.
10094 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10095                                                 Expr *LHSExpr, Expr *RHSExpr) {
10096   S.Diag(Loc, S.getLangOpts().CPlusPlus
10097                 ? diag::err_typecheck_pointer_arith_void_type
10098                 : diag::ext_gnu_void_ptr)
10099     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10100                             << RHSExpr->getSourceRange();
10101 }
10102 
10103 /// Diagnose invalid arithmetic on a void pointer.
10104 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10105                                             Expr *Pointer) {
10106   S.Diag(Loc, S.getLangOpts().CPlusPlus
10107                 ? diag::err_typecheck_pointer_arith_void_type
10108                 : diag::ext_gnu_void_ptr)
10109     << 0 /* one pointer */ << Pointer->getSourceRange();
10110 }
10111 
10112 /// Diagnose invalid arithmetic on a null pointer.
10113 ///
10114 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10115 /// idiom, which we recognize as a GNU extension.
10116 ///
10117 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10118                                             Expr *Pointer, bool IsGNUIdiom) {
10119   if (IsGNUIdiom)
10120     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10121       << Pointer->getSourceRange();
10122   else
10123     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10124       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10125 }
10126 
10127 /// Diagnose invalid arithmetic on two function pointers.
10128 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10129                                                     Expr *LHS, Expr *RHS) {
10130   assert(LHS->getType()->isAnyPointerType());
10131   assert(RHS->getType()->isAnyPointerType());
10132   S.Diag(Loc, S.getLangOpts().CPlusPlus
10133                 ? diag::err_typecheck_pointer_arith_function_type
10134                 : diag::ext_gnu_ptr_func_arith)
10135     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10136     // We only show the second type if it differs from the first.
10137     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10138                                                    RHS->getType())
10139     << RHS->getType()->getPointeeType()
10140     << LHS->getSourceRange() << RHS->getSourceRange();
10141 }
10142 
10143 /// Diagnose invalid arithmetic on a function pointer.
10144 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10145                                                 Expr *Pointer) {
10146   assert(Pointer->getType()->isAnyPointerType());
10147   S.Diag(Loc, S.getLangOpts().CPlusPlus
10148                 ? diag::err_typecheck_pointer_arith_function_type
10149                 : diag::ext_gnu_ptr_func_arith)
10150     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10151     << 0 /* one pointer, so only one type */
10152     << Pointer->getSourceRange();
10153 }
10154 
10155 /// Emit error if Operand is incomplete pointer type
10156 ///
10157 /// \returns True if pointer has incomplete type
10158 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10159                                                  Expr *Operand) {
10160   QualType ResType = Operand->getType();
10161   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10162     ResType = ResAtomicType->getValueType();
10163 
10164   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10165   QualType PointeeTy = ResType->getPointeeType();
10166   return S.RequireCompleteSizedType(
10167       Loc, PointeeTy,
10168       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10169       Operand->getSourceRange());
10170 }
10171 
10172 /// Check the validity of an arithmetic pointer operand.
10173 ///
10174 /// If the operand has pointer type, this code will check for pointer types
10175 /// which are invalid in arithmetic operations. These will be diagnosed
10176 /// appropriately, including whether or not the use is supported as an
10177 /// extension.
10178 ///
10179 /// \returns True when the operand is valid to use (even if as an extension).
10180 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10181                                             Expr *Operand) {
10182   QualType ResType = Operand->getType();
10183   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10184     ResType = ResAtomicType->getValueType();
10185 
10186   if (!ResType->isAnyPointerType()) return true;
10187 
10188   QualType PointeeTy = ResType->getPointeeType();
10189   if (PointeeTy->isVoidType()) {
10190     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10191     return !S.getLangOpts().CPlusPlus;
10192   }
10193   if (PointeeTy->isFunctionType()) {
10194     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10195     return !S.getLangOpts().CPlusPlus;
10196   }
10197 
10198   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10199 
10200   return true;
10201 }
10202 
10203 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10204 /// operands.
10205 ///
10206 /// This routine will diagnose any invalid arithmetic on pointer operands much
10207 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10208 /// for emitting a single diagnostic even for operations where both LHS and RHS
10209 /// are (potentially problematic) pointers.
10210 ///
10211 /// \returns True when the operand is valid to use (even if as an extension).
10212 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10213                                                 Expr *LHSExpr, Expr *RHSExpr) {
10214   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10215   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10216   if (!isLHSPointer && !isRHSPointer) return true;
10217 
10218   QualType LHSPointeeTy, RHSPointeeTy;
10219   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10220   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10221 
10222   // if both are pointers check if operation is valid wrt address spaces
10223   if (isLHSPointer && isRHSPointer) {
10224     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10225       S.Diag(Loc,
10226              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10227           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10228           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10229       return false;
10230     }
10231   }
10232 
10233   // Check for arithmetic on pointers to incomplete types.
10234   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10235   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10236   if (isLHSVoidPtr || isRHSVoidPtr) {
10237     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10238     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10239     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10240 
10241     return !S.getLangOpts().CPlusPlus;
10242   }
10243 
10244   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10245   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10246   if (isLHSFuncPtr || isRHSFuncPtr) {
10247     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10248     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10249                                                                 RHSExpr);
10250     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10251 
10252     return !S.getLangOpts().CPlusPlus;
10253   }
10254 
10255   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10256     return false;
10257   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10258     return false;
10259 
10260   return true;
10261 }
10262 
10263 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10264 /// literal.
10265 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10266                                   Expr *LHSExpr, Expr *RHSExpr) {
10267   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10268   Expr* IndexExpr = RHSExpr;
10269   if (!StrExpr) {
10270     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10271     IndexExpr = LHSExpr;
10272   }
10273 
10274   bool IsStringPlusInt = StrExpr &&
10275       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10276   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10277     return;
10278 
10279   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10280   Self.Diag(OpLoc, diag::warn_string_plus_int)
10281       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10282 
10283   // Only print a fixit for "str" + int, not for int + "str".
10284   if (IndexExpr == RHSExpr) {
10285     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10286     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10287         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10288         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10289         << FixItHint::CreateInsertion(EndLoc, "]");
10290   } else
10291     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10292 }
10293 
10294 /// Emit a warning when adding a char literal to a string.
10295 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10296                                    Expr *LHSExpr, Expr *RHSExpr) {
10297   const Expr *StringRefExpr = LHSExpr;
10298   const CharacterLiteral *CharExpr =
10299       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10300 
10301   if (!CharExpr) {
10302     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10303     StringRefExpr = RHSExpr;
10304   }
10305 
10306   if (!CharExpr || !StringRefExpr)
10307     return;
10308 
10309   const QualType StringType = StringRefExpr->getType();
10310 
10311   // Return if not a PointerType.
10312   if (!StringType->isAnyPointerType())
10313     return;
10314 
10315   // Return if not a CharacterType.
10316   if (!StringType->getPointeeType()->isAnyCharacterType())
10317     return;
10318 
10319   ASTContext &Ctx = Self.getASTContext();
10320   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10321 
10322   const QualType CharType = CharExpr->getType();
10323   if (!CharType->isAnyCharacterType() &&
10324       CharType->isIntegerType() &&
10325       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10326     Self.Diag(OpLoc, diag::warn_string_plus_char)
10327         << DiagRange << Ctx.CharTy;
10328   } else {
10329     Self.Diag(OpLoc, diag::warn_string_plus_char)
10330         << DiagRange << CharExpr->getType();
10331   }
10332 
10333   // Only print a fixit for str + char, not for char + str.
10334   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10335     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10336     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10337         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10338         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10339         << FixItHint::CreateInsertion(EndLoc, "]");
10340   } else {
10341     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10342   }
10343 }
10344 
10345 /// Emit error when two pointers are incompatible.
10346 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10347                                            Expr *LHSExpr, Expr *RHSExpr) {
10348   assert(LHSExpr->getType()->isAnyPointerType());
10349   assert(RHSExpr->getType()->isAnyPointerType());
10350   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10351     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10352     << RHSExpr->getSourceRange();
10353 }
10354 
10355 // C99 6.5.6
10356 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10357                                      SourceLocation Loc, BinaryOperatorKind Opc,
10358                                      QualType* CompLHSTy) {
10359   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10360 
10361   if (LHS.get()->getType()->isVectorType() ||
10362       RHS.get()->getType()->isVectorType()) {
10363     QualType compType = CheckVectorOperands(
10364         LHS, RHS, Loc, CompLHSTy,
10365         /*AllowBothBool*/getLangOpts().AltiVec,
10366         /*AllowBoolConversions*/getLangOpts().ZVector);
10367     if (CompLHSTy) *CompLHSTy = compType;
10368     return compType;
10369   }
10370 
10371   if (LHS.get()->getType()->isConstantMatrixType() ||
10372       RHS.get()->getType()->isConstantMatrixType()) {
10373     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10374   }
10375 
10376   QualType compType = UsualArithmeticConversions(
10377       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10378   if (LHS.isInvalid() || RHS.isInvalid())
10379     return QualType();
10380 
10381   // Diagnose "string literal" '+' int and string '+' "char literal".
10382   if (Opc == BO_Add) {
10383     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10384     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10385   }
10386 
10387   // handle the common case first (both operands are arithmetic).
10388   if (!compType.isNull() && compType->isArithmeticType()) {
10389     if (CompLHSTy) *CompLHSTy = compType;
10390     return compType;
10391   }
10392 
10393   // Type-checking.  Ultimately the pointer's going to be in PExp;
10394   // note that we bias towards the LHS being the pointer.
10395   Expr *PExp = LHS.get(), *IExp = RHS.get();
10396 
10397   bool isObjCPointer;
10398   if (PExp->getType()->isPointerType()) {
10399     isObjCPointer = false;
10400   } else if (PExp->getType()->isObjCObjectPointerType()) {
10401     isObjCPointer = true;
10402   } else {
10403     std::swap(PExp, IExp);
10404     if (PExp->getType()->isPointerType()) {
10405       isObjCPointer = false;
10406     } else if (PExp->getType()->isObjCObjectPointerType()) {
10407       isObjCPointer = true;
10408     } else {
10409       return InvalidOperands(Loc, LHS, RHS);
10410     }
10411   }
10412   assert(PExp->getType()->isAnyPointerType());
10413 
10414   if (!IExp->getType()->isIntegerType())
10415     return InvalidOperands(Loc, LHS, RHS);
10416 
10417   // Adding to a null pointer results in undefined behavior.
10418   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10419           Context, Expr::NPC_ValueDependentIsNotNull)) {
10420     // In C++ adding zero to a null pointer is defined.
10421     Expr::EvalResult KnownVal;
10422     if (!getLangOpts().CPlusPlus ||
10423         (!IExp->isValueDependent() &&
10424          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10425           KnownVal.Val.getInt() != 0))) {
10426       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10427       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10428           Context, BO_Add, PExp, IExp);
10429       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10430     }
10431   }
10432 
10433   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10434     return QualType();
10435 
10436   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10437     return QualType();
10438 
10439   // Check array bounds for pointer arithemtic
10440   CheckArrayAccess(PExp, IExp);
10441 
10442   if (CompLHSTy) {
10443     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10444     if (LHSTy.isNull()) {
10445       LHSTy = LHS.get()->getType();
10446       if (LHSTy->isPromotableIntegerType())
10447         LHSTy = Context.getPromotedIntegerType(LHSTy);
10448     }
10449     *CompLHSTy = LHSTy;
10450   }
10451 
10452   return PExp->getType();
10453 }
10454 
10455 // C99 6.5.6
10456 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10457                                         SourceLocation Loc,
10458                                         QualType* CompLHSTy) {
10459   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10460 
10461   if (LHS.get()->getType()->isVectorType() ||
10462       RHS.get()->getType()->isVectorType()) {
10463     QualType compType = CheckVectorOperands(
10464         LHS, RHS, Loc, CompLHSTy,
10465         /*AllowBothBool*/getLangOpts().AltiVec,
10466         /*AllowBoolConversions*/getLangOpts().ZVector);
10467     if (CompLHSTy) *CompLHSTy = compType;
10468     return compType;
10469   }
10470 
10471   if (LHS.get()->getType()->isConstantMatrixType() ||
10472       RHS.get()->getType()->isConstantMatrixType()) {
10473     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10474   }
10475 
10476   QualType compType = UsualArithmeticConversions(
10477       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10478   if (LHS.isInvalid() || RHS.isInvalid())
10479     return QualType();
10480 
10481   // Enforce type constraints: C99 6.5.6p3.
10482 
10483   // Handle the common case first (both operands are arithmetic).
10484   if (!compType.isNull() && compType->isArithmeticType()) {
10485     if (CompLHSTy) *CompLHSTy = compType;
10486     return compType;
10487   }
10488 
10489   // Either ptr - int   or   ptr - ptr.
10490   if (LHS.get()->getType()->isAnyPointerType()) {
10491     QualType lpointee = LHS.get()->getType()->getPointeeType();
10492 
10493     // Diagnose bad cases where we step over interface counts.
10494     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10495         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10496       return QualType();
10497 
10498     // The result type of a pointer-int computation is the pointer type.
10499     if (RHS.get()->getType()->isIntegerType()) {
10500       // Subtracting from a null pointer should produce a warning.
10501       // The last argument to the diagnose call says this doesn't match the
10502       // GNU int-to-pointer idiom.
10503       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10504                                            Expr::NPC_ValueDependentIsNotNull)) {
10505         // In C++ adding zero to a null pointer is defined.
10506         Expr::EvalResult KnownVal;
10507         if (!getLangOpts().CPlusPlus ||
10508             (!RHS.get()->isValueDependent() &&
10509              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10510               KnownVal.Val.getInt() != 0))) {
10511           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10512         }
10513       }
10514 
10515       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10516         return QualType();
10517 
10518       // Check array bounds for pointer arithemtic
10519       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10520                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10521 
10522       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10523       return LHS.get()->getType();
10524     }
10525 
10526     // Handle pointer-pointer subtractions.
10527     if (const PointerType *RHSPTy
10528           = RHS.get()->getType()->getAs<PointerType>()) {
10529       QualType rpointee = RHSPTy->getPointeeType();
10530 
10531       if (getLangOpts().CPlusPlus) {
10532         // Pointee types must be the same: C++ [expr.add]
10533         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10534           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10535         }
10536       } else {
10537         // Pointee types must be compatible C99 6.5.6p3
10538         if (!Context.typesAreCompatible(
10539                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10540                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10541           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10542           return QualType();
10543         }
10544       }
10545 
10546       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10547                                                LHS.get(), RHS.get()))
10548         return QualType();
10549 
10550       // FIXME: Add warnings for nullptr - ptr.
10551 
10552       // The pointee type may have zero size.  As an extension, a structure or
10553       // union may have zero size or an array may have zero length.  In this
10554       // case subtraction does not make sense.
10555       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10556         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10557         if (ElementSize.isZero()) {
10558           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10559             << rpointee.getUnqualifiedType()
10560             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10561         }
10562       }
10563 
10564       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10565       return Context.getPointerDiffType();
10566     }
10567   }
10568 
10569   return InvalidOperands(Loc, LHS, RHS);
10570 }
10571 
10572 static bool isScopedEnumerationType(QualType T) {
10573   if (const EnumType *ET = T->getAs<EnumType>())
10574     return ET->getDecl()->isScoped();
10575   return false;
10576 }
10577 
10578 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10579                                    SourceLocation Loc, BinaryOperatorKind Opc,
10580                                    QualType LHSType) {
10581   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10582   // so skip remaining warnings as we don't want to modify values within Sema.
10583   if (S.getLangOpts().OpenCL)
10584     return;
10585 
10586   // Check right/shifter operand
10587   Expr::EvalResult RHSResult;
10588   if (RHS.get()->isValueDependent() ||
10589       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10590     return;
10591   llvm::APSInt Right = RHSResult.Val.getInt();
10592 
10593   if (Right.isNegative()) {
10594     S.DiagRuntimeBehavior(Loc, RHS.get(),
10595                           S.PDiag(diag::warn_shift_negative)
10596                             << RHS.get()->getSourceRange());
10597     return;
10598   }
10599 
10600   QualType LHSExprType = LHS.get()->getType();
10601   uint64_t LeftSize = LHSExprType->isExtIntType()
10602                           ? S.Context.getIntWidth(LHSExprType)
10603                           : S.Context.getTypeSize(LHSExprType);
10604   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10605   if (Right.uge(LeftBits)) {
10606     S.DiagRuntimeBehavior(Loc, RHS.get(),
10607                           S.PDiag(diag::warn_shift_gt_typewidth)
10608                             << RHS.get()->getSourceRange());
10609     return;
10610   }
10611 
10612   if (Opc != BO_Shl)
10613     return;
10614 
10615   // When left shifting an ICE which is signed, we can check for overflow which
10616   // according to C++ standards prior to C++2a has undefined behavior
10617   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10618   // more than the maximum value representable in the result type, so never
10619   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10620   // expression is still probably a bug.)
10621   Expr::EvalResult LHSResult;
10622   if (LHS.get()->isValueDependent() ||
10623       LHSType->hasUnsignedIntegerRepresentation() ||
10624       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10625     return;
10626   llvm::APSInt Left = LHSResult.Val.getInt();
10627 
10628   // If LHS does not have a signed type and non-negative value
10629   // then, the behavior is undefined before C++2a. Warn about it.
10630   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10631       !S.getLangOpts().CPlusPlus20) {
10632     S.DiagRuntimeBehavior(Loc, LHS.get(),
10633                           S.PDiag(diag::warn_shift_lhs_negative)
10634                             << LHS.get()->getSourceRange());
10635     return;
10636   }
10637 
10638   llvm::APInt ResultBits =
10639       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10640   if (LeftBits.uge(ResultBits))
10641     return;
10642   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10643   Result = Result.shl(Right);
10644 
10645   // Print the bit representation of the signed integer as an unsigned
10646   // hexadecimal number.
10647   SmallString<40> HexResult;
10648   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10649 
10650   // If we are only missing a sign bit, this is less likely to result in actual
10651   // bugs -- if the result is cast back to an unsigned type, it will have the
10652   // expected value. Thus we place this behind a different warning that can be
10653   // turned off separately if needed.
10654   if (LeftBits == ResultBits - 1) {
10655     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10656         << HexResult << LHSType
10657         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10658     return;
10659   }
10660 
10661   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10662     << HexResult.str() << Result.getMinSignedBits() << LHSType
10663     << Left.getBitWidth() << LHS.get()->getSourceRange()
10664     << RHS.get()->getSourceRange();
10665 }
10666 
10667 /// Return the resulting type when a vector is shifted
10668 ///        by a scalar or vector shift amount.
10669 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10670                                  SourceLocation Loc, bool IsCompAssign) {
10671   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10672   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10673       !LHS.get()->getType()->isVectorType()) {
10674     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10675       << RHS.get()->getType() << LHS.get()->getType()
10676       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10677     return QualType();
10678   }
10679 
10680   if (!IsCompAssign) {
10681     LHS = S.UsualUnaryConversions(LHS.get());
10682     if (LHS.isInvalid()) return QualType();
10683   }
10684 
10685   RHS = S.UsualUnaryConversions(RHS.get());
10686   if (RHS.isInvalid()) return QualType();
10687 
10688   QualType LHSType = LHS.get()->getType();
10689   // Note that LHS might be a scalar because the routine calls not only in
10690   // OpenCL case.
10691   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10692   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10693 
10694   // Note that RHS might not be a vector.
10695   QualType RHSType = RHS.get()->getType();
10696   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10697   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10698 
10699   // The operands need to be integers.
10700   if (!LHSEleType->isIntegerType()) {
10701     S.Diag(Loc, diag::err_typecheck_expect_int)
10702       << LHS.get()->getType() << LHS.get()->getSourceRange();
10703     return QualType();
10704   }
10705 
10706   if (!RHSEleType->isIntegerType()) {
10707     S.Diag(Loc, diag::err_typecheck_expect_int)
10708       << RHS.get()->getType() << RHS.get()->getSourceRange();
10709     return QualType();
10710   }
10711 
10712   if (!LHSVecTy) {
10713     assert(RHSVecTy);
10714     if (IsCompAssign)
10715       return RHSType;
10716     if (LHSEleType != RHSEleType) {
10717       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10718       LHSEleType = RHSEleType;
10719     }
10720     QualType VecTy =
10721         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10722     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10723     LHSType = VecTy;
10724   } else if (RHSVecTy) {
10725     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10726     // are applied component-wise. So if RHS is a vector, then ensure
10727     // that the number of elements is the same as LHS...
10728     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10729       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10730         << LHS.get()->getType() << RHS.get()->getType()
10731         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10732       return QualType();
10733     }
10734     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10735       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10736       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10737       if (LHSBT != RHSBT &&
10738           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10739         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10740             << LHS.get()->getType() << RHS.get()->getType()
10741             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10742       }
10743     }
10744   } else {
10745     // ...else expand RHS to match the number of elements in LHS.
10746     QualType VecTy =
10747       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10748     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10749   }
10750 
10751   return LHSType;
10752 }
10753 
10754 // C99 6.5.7
10755 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10756                                   SourceLocation Loc, BinaryOperatorKind Opc,
10757                                   bool IsCompAssign) {
10758   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10759 
10760   // Vector shifts promote their scalar inputs to vector type.
10761   if (LHS.get()->getType()->isVectorType() ||
10762       RHS.get()->getType()->isVectorType()) {
10763     if (LangOpts.ZVector) {
10764       // The shift operators for the z vector extensions work basically
10765       // like general shifts, except that neither the LHS nor the RHS is
10766       // allowed to be a "vector bool".
10767       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10768         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10769           return InvalidOperands(Loc, LHS, RHS);
10770       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10771         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10772           return InvalidOperands(Loc, LHS, RHS);
10773     }
10774     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10775   }
10776 
10777   // Shifts don't perform usual arithmetic conversions, they just do integer
10778   // promotions on each operand. C99 6.5.7p3
10779 
10780   // For the LHS, do usual unary conversions, but then reset them away
10781   // if this is a compound assignment.
10782   ExprResult OldLHS = LHS;
10783   LHS = UsualUnaryConversions(LHS.get());
10784   if (LHS.isInvalid())
10785     return QualType();
10786   QualType LHSType = LHS.get()->getType();
10787   if (IsCompAssign) LHS = OldLHS;
10788 
10789   // The RHS is simpler.
10790   RHS = UsualUnaryConversions(RHS.get());
10791   if (RHS.isInvalid())
10792     return QualType();
10793   QualType RHSType = RHS.get()->getType();
10794 
10795   // C99 6.5.7p2: Each of the operands shall have integer type.
10796   if (!LHSType->hasIntegerRepresentation() ||
10797       !RHSType->hasIntegerRepresentation())
10798     return InvalidOperands(Loc, LHS, RHS);
10799 
10800   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10801   // hasIntegerRepresentation() above instead of this.
10802   if (isScopedEnumerationType(LHSType) ||
10803       isScopedEnumerationType(RHSType)) {
10804     return InvalidOperands(Loc, LHS, RHS);
10805   }
10806   // Sanity-check shift operands
10807   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10808 
10809   // "The type of the result is that of the promoted left operand."
10810   return LHSType;
10811 }
10812 
10813 /// Diagnose bad pointer comparisons.
10814 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10815                                               ExprResult &LHS, ExprResult &RHS,
10816                                               bool IsError) {
10817   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10818                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10819     << LHS.get()->getType() << RHS.get()->getType()
10820     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10821 }
10822 
10823 /// Returns false if the pointers are converted to a composite type,
10824 /// true otherwise.
10825 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10826                                            ExprResult &LHS, ExprResult &RHS) {
10827   // C++ [expr.rel]p2:
10828   //   [...] Pointer conversions (4.10) and qualification
10829   //   conversions (4.4) are performed on pointer operands (or on
10830   //   a pointer operand and a null pointer constant) to bring
10831   //   them to their composite pointer type. [...]
10832   //
10833   // C++ [expr.eq]p1 uses the same notion for (in)equality
10834   // comparisons of pointers.
10835 
10836   QualType LHSType = LHS.get()->getType();
10837   QualType RHSType = RHS.get()->getType();
10838   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10839          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10840 
10841   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10842   if (T.isNull()) {
10843     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10844         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10845       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10846     else
10847       S.InvalidOperands(Loc, LHS, RHS);
10848     return true;
10849   }
10850 
10851   return false;
10852 }
10853 
10854 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10855                                                     ExprResult &LHS,
10856                                                     ExprResult &RHS,
10857                                                     bool IsError) {
10858   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10859                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10860     << LHS.get()->getType() << RHS.get()->getType()
10861     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10862 }
10863 
10864 static bool isObjCObjectLiteral(ExprResult &E) {
10865   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10866   case Stmt::ObjCArrayLiteralClass:
10867   case Stmt::ObjCDictionaryLiteralClass:
10868   case Stmt::ObjCStringLiteralClass:
10869   case Stmt::ObjCBoxedExprClass:
10870     return true;
10871   default:
10872     // Note that ObjCBoolLiteral is NOT an object literal!
10873     return false;
10874   }
10875 }
10876 
10877 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10878   const ObjCObjectPointerType *Type =
10879     LHS->getType()->getAs<ObjCObjectPointerType>();
10880 
10881   // If this is not actually an Objective-C object, bail out.
10882   if (!Type)
10883     return false;
10884 
10885   // Get the LHS object's interface type.
10886   QualType InterfaceType = Type->getPointeeType();
10887 
10888   // If the RHS isn't an Objective-C object, bail out.
10889   if (!RHS->getType()->isObjCObjectPointerType())
10890     return false;
10891 
10892   // Try to find the -isEqual: method.
10893   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10894   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10895                                                       InterfaceType,
10896                                                       /*IsInstance=*/true);
10897   if (!Method) {
10898     if (Type->isObjCIdType()) {
10899       // For 'id', just check the global pool.
10900       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10901                                                   /*receiverId=*/true);
10902     } else {
10903       // Check protocols.
10904       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10905                                              /*IsInstance=*/true);
10906     }
10907   }
10908 
10909   if (!Method)
10910     return false;
10911 
10912   QualType T = Method->parameters()[0]->getType();
10913   if (!T->isObjCObjectPointerType())
10914     return false;
10915 
10916   QualType R = Method->getReturnType();
10917   if (!R->isScalarType())
10918     return false;
10919 
10920   return true;
10921 }
10922 
10923 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10924   FromE = FromE->IgnoreParenImpCasts();
10925   switch (FromE->getStmtClass()) {
10926     default:
10927       break;
10928     case Stmt::ObjCStringLiteralClass:
10929       // "string literal"
10930       return LK_String;
10931     case Stmt::ObjCArrayLiteralClass:
10932       // "array literal"
10933       return LK_Array;
10934     case Stmt::ObjCDictionaryLiteralClass:
10935       // "dictionary literal"
10936       return LK_Dictionary;
10937     case Stmt::BlockExprClass:
10938       return LK_Block;
10939     case Stmt::ObjCBoxedExprClass: {
10940       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10941       switch (Inner->getStmtClass()) {
10942         case Stmt::IntegerLiteralClass:
10943         case Stmt::FloatingLiteralClass:
10944         case Stmt::CharacterLiteralClass:
10945         case Stmt::ObjCBoolLiteralExprClass:
10946         case Stmt::CXXBoolLiteralExprClass:
10947           // "numeric literal"
10948           return LK_Numeric;
10949         case Stmt::ImplicitCastExprClass: {
10950           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10951           // Boolean literals can be represented by implicit casts.
10952           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10953             return LK_Numeric;
10954           break;
10955         }
10956         default:
10957           break;
10958       }
10959       return LK_Boxed;
10960     }
10961   }
10962   return LK_None;
10963 }
10964 
10965 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10966                                           ExprResult &LHS, ExprResult &RHS,
10967                                           BinaryOperator::Opcode Opc){
10968   Expr *Literal;
10969   Expr *Other;
10970   if (isObjCObjectLiteral(LHS)) {
10971     Literal = LHS.get();
10972     Other = RHS.get();
10973   } else {
10974     Literal = RHS.get();
10975     Other = LHS.get();
10976   }
10977 
10978   // Don't warn on comparisons against nil.
10979   Other = Other->IgnoreParenCasts();
10980   if (Other->isNullPointerConstant(S.getASTContext(),
10981                                    Expr::NPC_ValueDependentIsNotNull))
10982     return;
10983 
10984   // This should be kept in sync with warn_objc_literal_comparison.
10985   // LK_String should always be after the other literals, since it has its own
10986   // warning flag.
10987   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10988   assert(LiteralKind != Sema::LK_Block);
10989   if (LiteralKind == Sema::LK_None) {
10990     llvm_unreachable("Unknown Objective-C object literal kind");
10991   }
10992 
10993   if (LiteralKind == Sema::LK_String)
10994     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10995       << Literal->getSourceRange();
10996   else
10997     S.Diag(Loc, diag::warn_objc_literal_comparison)
10998       << LiteralKind << Literal->getSourceRange();
10999 
11000   if (BinaryOperator::isEqualityOp(Opc) &&
11001       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11002     SourceLocation Start = LHS.get()->getBeginLoc();
11003     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11004     CharSourceRange OpRange =
11005       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11006 
11007     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11008       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11009       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11010       << FixItHint::CreateInsertion(End, "]");
11011   }
11012 }
11013 
11014 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11015 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11016                                            ExprResult &RHS, SourceLocation Loc,
11017                                            BinaryOperatorKind Opc) {
11018   // Check that left hand side is !something.
11019   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11020   if (!UO || UO->getOpcode() != UO_LNot) return;
11021 
11022   // Only check if the right hand side is non-bool arithmetic type.
11023   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11024 
11025   // Make sure that the something in !something is not bool.
11026   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11027   if (SubExpr->isKnownToHaveBooleanValue()) return;
11028 
11029   // Emit warning.
11030   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11031   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11032       << Loc << IsBitwiseOp;
11033 
11034   // First note suggest !(x < y)
11035   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11036   SourceLocation FirstClose = RHS.get()->getEndLoc();
11037   FirstClose = S.getLocForEndOfToken(FirstClose);
11038   if (FirstClose.isInvalid())
11039     FirstOpen = SourceLocation();
11040   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11041       << IsBitwiseOp
11042       << FixItHint::CreateInsertion(FirstOpen, "(")
11043       << FixItHint::CreateInsertion(FirstClose, ")");
11044 
11045   // Second note suggests (!x) < y
11046   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11047   SourceLocation SecondClose = LHS.get()->getEndLoc();
11048   SecondClose = S.getLocForEndOfToken(SecondClose);
11049   if (SecondClose.isInvalid())
11050     SecondOpen = SourceLocation();
11051   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11052       << FixItHint::CreateInsertion(SecondOpen, "(")
11053       << FixItHint::CreateInsertion(SecondClose, ")");
11054 }
11055 
11056 // Returns true if E refers to a non-weak array.
11057 static bool checkForArray(const Expr *E) {
11058   const ValueDecl *D = nullptr;
11059   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11060     D = DR->getDecl();
11061   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11062     if (Mem->isImplicitAccess())
11063       D = Mem->getMemberDecl();
11064   }
11065   if (!D)
11066     return false;
11067   return D->getType()->isArrayType() && !D->isWeak();
11068 }
11069 
11070 /// Diagnose some forms of syntactically-obvious tautological comparison.
11071 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11072                                            Expr *LHS, Expr *RHS,
11073                                            BinaryOperatorKind Opc) {
11074   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11075   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11076 
11077   QualType LHSType = LHS->getType();
11078   QualType RHSType = RHS->getType();
11079   if (LHSType->hasFloatingRepresentation() ||
11080       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11081       S.inTemplateInstantiation())
11082     return;
11083 
11084   // Comparisons between two array types are ill-formed for operator<=>, so
11085   // we shouldn't emit any additional warnings about it.
11086   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11087     return;
11088 
11089   // For non-floating point types, check for self-comparisons of the form
11090   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11091   // often indicate logic errors in the program.
11092   //
11093   // NOTE: Don't warn about comparison expressions resulting from macro
11094   // expansion. Also don't warn about comparisons which are only self
11095   // comparisons within a template instantiation. The warnings should catch
11096   // obvious cases in the definition of the template anyways. The idea is to
11097   // warn when the typed comparison operator will always evaluate to the same
11098   // result.
11099 
11100   // Used for indexing into %select in warn_comparison_always
11101   enum {
11102     AlwaysConstant,
11103     AlwaysTrue,
11104     AlwaysFalse,
11105     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11106   };
11107 
11108   // C++2a [depr.array.comp]:
11109   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11110   //   operands of array type are deprecated.
11111   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11112       RHSStripped->getType()->isArrayType()) {
11113     S.Diag(Loc, diag::warn_depr_array_comparison)
11114         << LHS->getSourceRange() << RHS->getSourceRange()
11115         << LHSStripped->getType() << RHSStripped->getType();
11116     // Carry on to produce the tautological comparison warning, if this
11117     // expression is potentially-evaluated, we can resolve the array to a
11118     // non-weak declaration, and so on.
11119   }
11120 
11121   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11122     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11123       unsigned Result;
11124       switch (Opc) {
11125       case BO_EQ:
11126       case BO_LE:
11127       case BO_GE:
11128         Result = AlwaysTrue;
11129         break;
11130       case BO_NE:
11131       case BO_LT:
11132       case BO_GT:
11133         Result = AlwaysFalse;
11134         break;
11135       case BO_Cmp:
11136         Result = AlwaysEqual;
11137         break;
11138       default:
11139         Result = AlwaysConstant;
11140         break;
11141       }
11142       S.DiagRuntimeBehavior(Loc, nullptr,
11143                             S.PDiag(diag::warn_comparison_always)
11144                                 << 0 /*self-comparison*/
11145                                 << Result);
11146     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11147       // What is it always going to evaluate to?
11148       unsigned Result;
11149       switch (Opc) {
11150       case BO_EQ: // e.g. array1 == array2
11151         Result = AlwaysFalse;
11152         break;
11153       case BO_NE: // e.g. array1 != array2
11154         Result = AlwaysTrue;
11155         break;
11156       default: // e.g. array1 <= array2
11157         // The best we can say is 'a constant'
11158         Result = AlwaysConstant;
11159         break;
11160       }
11161       S.DiagRuntimeBehavior(Loc, nullptr,
11162                             S.PDiag(diag::warn_comparison_always)
11163                                 << 1 /*array comparison*/
11164                                 << Result);
11165     }
11166   }
11167 
11168   if (isa<CastExpr>(LHSStripped))
11169     LHSStripped = LHSStripped->IgnoreParenCasts();
11170   if (isa<CastExpr>(RHSStripped))
11171     RHSStripped = RHSStripped->IgnoreParenCasts();
11172 
11173   // Warn about comparisons against a string constant (unless the other
11174   // operand is null); the user probably wants string comparison function.
11175   Expr *LiteralString = nullptr;
11176   Expr *LiteralStringStripped = nullptr;
11177   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11178       !RHSStripped->isNullPointerConstant(S.Context,
11179                                           Expr::NPC_ValueDependentIsNull)) {
11180     LiteralString = LHS;
11181     LiteralStringStripped = LHSStripped;
11182   } else if ((isa<StringLiteral>(RHSStripped) ||
11183               isa<ObjCEncodeExpr>(RHSStripped)) &&
11184              !LHSStripped->isNullPointerConstant(S.Context,
11185                                           Expr::NPC_ValueDependentIsNull)) {
11186     LiteralString = RHS;
11187     LiteralStringStripped = RHSStripped;
11188   }
11189 
11190   if (LiteralString) {
11191     S.DiagRuntimeBehavior(Loc, nullptr,
11192                           S.PDiag(diag::warn_stringcompare)
11193                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11194                               << LiteralString->getSourceRange());
11195   }
11196 }
11197 
11198 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11199   switch (CK) {
11200   default: {
11201 #ifndef NDEBUG
11202     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11203                  << "\n";
11204 #endif
11205     llvm_unreachable("unhandled cast kind");
11206   }
11207   case CK_UserDefinedConversion:
11208     return ICK_Identity;
11209   case CK_LValueToRValue:
11210     return ICK_Lvalue_To_Rvalue;
11211   case CK_ArrayToPointerDecay:
11212     return ICK_Array_To_Pointer;
11213   case CK_FunctionToPointerDecay:
11214     return ICK_Function_To_Pointer;
11215   case CK_IntegralCast:
11216     return ICK_Integral_Conversion;
11217   case CK_FloatingCast:
11218     return ICK_Floating_Conversion;
11219   case CK_IntegralToFloating:
11220   case CK_FloatingToIntegral:
11221     return ICK_Floating_Integral;
11222   case CK_IntegralComplexCast:
11223   case CK_FloatingComplexCast:
11224   case CK_FloatingComplexToIntegralComplex:
11225   case CK_IntegralComplexToFloatingComplex:
11226     return ICK_Complex_Conversion;
11227   case CK_FloatingComplexToReal:
11228   case CK_FloatingRealToComplex:
11229   case CK_IntegralComplexToReal:
11230   case CK_IntegralRealToComplex:
11231     return ICK_Complex_Real;
11232   }
11233 }
11234 
11235 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11236                                              QualType FromType,
11237                                              SourceLocation Loc) {
11238   // Check for a narrowing implicit conversion.
11239   StandardConversionSequence SCS;
11240   SCS.setAsIdentityConversion();
11241   SCS.setToType(0, FromType);
11242   SCS.setToType(1, ToType);
11243   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11244     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11245 
11246   APValue PreNarrowingValue;
11247   QualType PreNarrowingType;
11248   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11249                                PreNarrowingType,
11250                                /*IgnoreFloatToIntegralConversion*/ true)) {
11251   case NK_Dependent_Narrowing:
11252     // Implicit conversion to a narrower type, but the expression is
11253     // value-dependent so we can't tell whether it's actually narrowing.
11254   case NK_Not_Narrowing:
11255     return false;
11256 
11257   case NK_Constant_Narrowing:
11258     // Implicit conversion to a narrower type, and the value is not a constant
11259     // expression.
11260     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11261         << /*Constant*/ 1
11262         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11263     return true;
11264 
11265   case NK_Variable_Narrowing:
11266     // Implicit conversion to a narrower type, and the value is not a constant
11267     // expression.
11268   case NK_Type_Narrowing:
11269     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11270         << /*Constant*/ 0 << FromType << ToType;
11271     // TODO: It's not a constant expression, but what if the user intended it
11272     // to be? Can we produce notes to help them figure out why it isn't?
11273     return true;
11274   }
11275   llvm_unreachable("unhandled case in switch");
11276 }
11277 
11278 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11279                                                          ExprResult &LHS,
11280                                                          ExprResult &RHS,
11281                                                          SourceLocation Loc) {
11282   QualType LHSType = LHS.get()->getType();
11283   QualType RHSType = RHS.get()->getType();
11284   // Dig out the original argument type and expression before implicit casts
11285   // were applied. These are the types/expressions we need to check the
11286   // [expr.spaceship] requirements against.
11287   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11288   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11289   QualType LHSStrippedType = LHSStripped.get()->getType();
11290   QualType RHSStrippedType = RHSStripped.get()->getType();
11291 
11292   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11293   // other is not, the program is ill-formed.
11294   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11295     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11296     return QualType();
11297   }
11298 
11299   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11300   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11301                     RHSStrippedType->isEnumeralType();
11302   if (NumEnumArgs == 1) {
11303     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11304     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11305     if (OtherTy->hasFloatingRepresentation()) {
11306       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11307       return QualType();
11308     }
11309   }
11310   if (NumEnumArgs == 2) {
11311     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11312     // type E, the operator yields the result of converting the operands
11313     // to the underlying type of E and applying <=> to the converted operands.
11314     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11315       S.InvalidOperands(Loc, LHS, RHS);
11316       return QualType();
11317     }
11318     QualType IntType =
11319         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11320     assert(IntType->isArithmeticType());
11321 
11322     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11323     // promote the boolean type, and all other promotable integer types, to
11324     // avoid this.
11325     if (IntType->isPromotableIntegerType())
11326       IntType = S.Context.getPromotedIntegerType(IntType);
11327 
11328     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11329     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11330     LHSType = RHSType = IntType;
11331   }
11332 
11333   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11334   // usual arithmetic conversions are applied to the operands.
11335   QualType Type =
11336       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11337   if (LHS.isInvalid() || RHS.isInvalid())
11338     return QualType();
11339   if (Type.isNull())
11340     return S.InvalidOperands(Loc, LHS, RHS);
11341 
11342   Optional<ComparisonCategoryType> CCT =
11343       getComparisonCategoryForBuiltinCmp(Type);
11344   if (!CCT)
11345     return S.InvalidOperands(Loc, LHS, RHS);
11346 
11347   bool HasNarrowing = checkThreeWayNarrowingConversion(
11348       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11349   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11350                                                    RHS.get()->getBeginLoc());
11351   if (HasNarrowing)
11352     return QualType();
11353 
11354   assert(!Type.isNull() && "composite type for <=> has not been set");
11355 
11356   return S.CheckComparisonCategoryType(
11357       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11358 }
11359 
11360 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11361                                                  ExprResult &RHS,
11362                                                  SourceLocation Loc,
11363                                                  BinaryOperatorKind Opc) {
11364   if (Opc == BO_Cmp)
11365     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11366 
11367   // C99 6.5.8p3 / C99 6.5.9p4
11368   QualType Type =
11369       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11370   if (LHS.isInvalid() || RHS.isInvalid())
11371     return QualType();
11372   if (Type.isNull())
11373     return S.InvalidOperands(Loc, LHS, RHS);
11374   assert(Type->isArithmeticType() || Type->isEnumeralType());
11375 
11376   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11377     return S.InvalidOperands(Loc, LHS, RHS);
11378 
11379   // Check for comparisons of floating point operands using != and ==.
11380   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11381     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11382 
11383   // The result of comparisons is 'bool' in C++, 'int' in C.
11384   return S.Context.getLogicalOperationType();
11385 }
11386 
11387 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11388   if (!NullE.get()->getType()->isAnyPointerType())
11389     return;
11390   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11391   if (!E.get()->getType()->isAnyPointerType() &&
11392       E.get()->isNullPointerConstant(Context,
11393                                      Expr::NPC_ValueDependentIsNotNull) ==
11394         Expr::NPCK_ZeroExpression) {
11395     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11396       if (CL->getValue() == 0)
11397         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11398             << NullValue
11399             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11400                                             NullValue ? "NULL" : "(void *)0");
11401     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11402         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11403         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11404         if (T == Context.CharTy)
11405           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11406               << NullValue
11407               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11408                                               NullValue ? "NULL" : "(void *)0");
11409       }
11410   }
11411 }
11412 
11413 // C99 6.5.8, C++ [expr.rel]
11414 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11415                                     SourceLocation Loc,
11416                                     BinaryOperatorKind Opc) {
11417   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11418   bool IsThreeWay = Opc == BO_Cmp;
11419   bool IsOrdered = IsRelational || IsThreeWay;
11420   auto IsAnyPointerType = [](ExprResult E) {
11421     QualType Ty = E.get()->getType();
11422     return Ty->isPointerType() || Ty->isMemberPointerType();
11423   };
11424 
11425   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11426   // type, array-to-pointer, ..., conversions are performed on both operands to
11427   // bring them to their composite type.
11428   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11429   // any type-related checks.
11430   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11431     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11432     if (LHS.isInvalid())
11433       return QualType();
11434     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11435     if (RHS.isInvalid())
11436       return QualType();
11437   } else {
11438     LHS = DefaultLvalueConversion(LHS.get());
11439     if (LHS.isInvalid())
11440       return QualType();
11441     RHS = DefaultLvalueConversion(RHS.get());
11442     if (RHS.isInvalid())
11443       return QualType();
11444   }
11445 
11446   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11447   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11448     CheckPtrComparisonWithNullChar(LHS, RHS);
11449     CheckPtrComparisonWithNullChar(RHS, LHS);
11450   }
11451 
11452   // Handle vector comparisons separately.
11453   if (LHS.get()->getType()->isVectorType() ||
11454       RHS.get()->getType()->isVectorType())
11455     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11456 
11457   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11458   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11459 
11460   QualType LHSType = LHS.get()->getType();
11461   QualType RHSType = RHS.get()->getType();
11462   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11463       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11464     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11465 
11466   const Expr::NullPointerConstantKind LHSNullKind =
11467       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11468   const Expr::NullPointerConstantKind RHSNullKind =
11469       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11470   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11471   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11472 
11473   auto computeResultTy = [&]() {
11474     if (Opc != BO_Cmp)
11475       return Context.getLogicalOperationType();
11476     assert(getLangOpts().CPlusPlus);
11477     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11478 
11479     QualType CompositeTy = LHS.get()->getType();
11480     assert(!CompositeTy->isReferenceType());
11481 
11482     Optional<ComparisonCategoryType> CCT =
11483         getComparisonCategoryForBuiltinCmp(CompositeTy);
11484     if (!CCT)
11485       return InvalidOperands(Loc, LHS, RHS);
11486 
11487     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11488       // P0946R0: Comparisons between a null pointer constant and an object
11489       // pointer result in std::strong_equality, which is ill-formed under
11490       // P1959R0.
11491       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11492           << (LHSIsNull ? LHS.get()->getSourceRange()
11493                         : RHS.get()->getSourceRange());
11494       return QualType();
11495     }
11496 
11497     return CheckComparisonCategoryType(
11498         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11499   };
11500 
11501   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11502     bool IsEquality = Opc == BO_EQ;
11503     if (RHSIsNull)
11504       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11505                                    RHS.get()->getSourceRange());
11506     else
11507       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11508                                    LHS.get()->getSourceRange());
11509   }
11510 
11511   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11512       (RHSType->isIntegerType() && !RHSIsNull)) {
11513     // Skip normal pointer conversion checks in this case; we have better
11514     // diagnostics for this below.
11515   } else if (getLangOpts().CPlusPlus) {
11516     // Equality comparison of a function pointer to a void pointer is invalid,
11517     // but we allow it as an extension.
11518     // FIXME: If we really want to allow this, should it be part of composite
11519     // pointer type computation so it works in conditionals too?
11520     if (!IsOrdered &&
11521         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11522          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11523       // This is a gcc extension compatibility comparison.
11524       // In a SFINAE context, we treat this as a hard error to maintain
11525       // conformance with the C++ standard.
11526       diagnoseFunctionPointerToVoidComparison(
11527           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11528 
11529       if (isSFINAEContext())
11530         return QualType();
11531 
11532       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11533       return computeResultTy();
11534     }
11535 
11536     // C++ [expr.eq]p2:
11537     //   If at least one operand is a pointer [...] bring them to their
11538     //   composite pointer type.
11539     // C++ [expr.spaceship]p6
11540     //  If at least one of the operands is of pointer type, [...] bring them
11541     //  to their composite pointer type.
11542     // C++ [expr.rel]p2:
11543     //   If both operands are pointers, [...] bring them to their composite
11544     //   pointer type.
11545     // For <=>, the only valid non-pointer types are arrays and functions, and
11546     // we already decayed those, so this is really the same as the relational
11547     // comparison rule.
11548     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11549             (IsOrdered ? 2 : 1) &&
11550         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11551                                          RHSType->isObjCObjectPointerType()))) {
11552       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11553         return QualType();
11554       return computeResultTy();
11555     }
11556   } else if (LHSType->isPointerType() &&
11557              RHSType->isPointerType()) { // C99 6.5.8p2
11558     // All of the following pointer-related warnings are GCC extensions, except
11559     // when handling null pointer constants.
11560     QualType LCanPointeeTy =
11561       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11562     QualType RCanPointeeTy =
11563       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11564 
11565     // C99 6.5.9p2 and C99 6.5.8p2
11566     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11567                                    RCanPointeeTy.getUnqualifiedType())) {
11568       if (IsRelational) {
11569         // Pointers both need to point to complete or incomplete types
11570         if ((LCanPointeeTy->isIncompleteType() !=
11571              RCanPointeeTy->isIncompleteType()) &&
11572             !getLangOpts().C11) {
11573           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11574               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11575               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11576               << RCanPointeeTy->isIncompleteType();
11577         }
11578         if (LCanPointeeTy->isFunctionType()) {
11579           // Valid unless a relational comparison of function pointers
11580           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11581               << LHSType << RHSType << LHS.get()->getSourceRange()
11582               << RHS.get()->getSourceRange();
11583         }
11584       }
11585     } else if (!IsRelational &&
11586                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11587       // Valid unless comparison between non-null pointer and function pointer
11588       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11589           && !LHSIsNull && !RHSIsNull)
11590         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11591                                                 /*isError*/false);
11592     } else {
11593       // Invalid
11594       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11595     }
11596     if (LCanPointeeTy != RCanPointeeTy) {
11597       // Treat NULL constant as a special case in OpenCL.
11598       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11599         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11600           Diag(Loc,
11601                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11602               << LHSType << RHSType << 0 /* comparison */
11603               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11604         }
11605       }
11606       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11607       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11608       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11609                                                : CK_BitCast;
11610       if (LHSIsNull && !RHSIsNull)
11611         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11612       else
11613         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11614     }
11615     return computeResultTy();
11616   }
11617 
11618   if (getLangOpts().CPlusPlus) {
11619     // C++ [expr.eq]p4:
11620     //   Two operands of type std::nullptr_t or one operand of type
11621     //   std::nullptr_t and the other a null pointer constant compare equal.
11622     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11623       if (LHSType->isNullPtrType()) {
11624         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11625         return computeResultTy();
11626       }
11627       if (RHSType->isNullPtrType()) {
11628         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11629         return computeResultTy();
11630       }
11631     }
11632 
11633     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11634     // These aren't covered by the composite pointer type rules.
11635     if (!IsOrdered && RHSType->isNullPtrType() &&
11636         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11637       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11638       return computeResultTy();
11639     }
11640     if (!IsOrdered && LHSType->isNullPtrType() &&
11641         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11642       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11643       return computeResultTy();
11644     }
11645 
11646     if (IsRelational &&
11647         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11648          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11649       // HACK: Relational comparison of nullptr_t against a pointer type is
11650       // invalid per DR583, but we allow it within std::less<> and friends,
11651       // since otherwise common uses of it break.
11652       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11653       // friends to have std::nullptr_t overload candidates.
11654       DeclContext *DC = CurContext;
11655       if (isa<FunctionDecl>(DC))
11656         DC = DC->getParent();
11657       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11658         if (CTSD->isInStdNamespace() &&
11659             llvm::StringSwitch<bool>(CTSD->getName())
11660                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11661                 .Default(false)) {
11662           if (RHSType->isNullPtrType())
11663             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11664           else
11665             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11666           return computeResultTy();
11667         }
11668       }
11669     }
11670 
11671     // C++ [expr.eq]p2:
11672     //   If at least one operand is a pointer to member, [...] bring them to
11673     //   their composite pointer type.
11674     if (!IsOrdered &&
11675         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11676       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11677         return QualType();
11678       else
11679         return computeResultTy();
11680     }
11681   }
11682 
11683   // Handle block pointer types.
11684   if (!IsOrdered && LHSType->isBlockPointerType() &&
11685       RHSType->isBlockPointerType()) {
11686     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11687     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11688 
11689     if (!LHSIsNull && !RHSIsNull &&
11690         !Context.typesAreCompatible(lpointee, rpointee)) {
11691       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11692         << LHSType << RHSType << LHS.get()->getSourceRange()
11693         << RHS.get()->getSourceRange();
11694     }
11695     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11696     return computeResultTy();
11697   }
11698 
11699   // Allow block pointers to be compared with null pointer constants.
11700   if (!IsOrdered
11701       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11702           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11703     if (!LHSIsNull && !RHSIsNull) {
11704       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11705              ->getPointeeType()->isVoidType())
11706             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11707                 ->getPointeeType()->isVoidType())))
11708         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11709           << LHSType << RHSType << LHS.get()->getSourceRange()
11710           << RHS.get()->getSourceRange();
11711     }
11712     if (LHSIsNull && !RHSIsNull)
11713       LHS = ImpCastExprToType(LHS.get(), RHSType,
11714                               RHSType->isPointerType() ? CK_BitCast
11715                                 : CK_AnyPointerToBlockPointerCast);
11716     else
11717       RHS = ImpCastExprToType(RHS.get(), LHSType,
11718                               LHSType->isPointerType() ? CK_BitCast
11719                                 : CK_AnyPointerToBlockPointerCast);
11720     return computeResultTy();
11721   }
11722 
11723   if (LHSType->isObjCObjectPointerType() ||
11724       RHSType->isObjCObjectPointerType()) {
11725     const PointerType *LPT = LHSType->getAs<PointerType>();
11726     const PointerType *RPT = RHSType->getAs<PointerType>();
11727     if (LPT || RPT) {
11728       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11729       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11730 
11731       if (!LPtrToVoid && !RPtrToVoid &&
11732           !Context.typesAreCompatible(LHSType, RHSType)) {
11733         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11734                                           /*isError*/false);
11735       }
11736       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11737       // the RHS, but we have test coverage for this behavior.
11738       // FIXME: Consider using convertPointersToCompositeType in C++.
11739       if (LHSIsNull && !RHSIsNull) {
11740         Expr *E = LHS.get();
11741         if (getLangOpts().ObjCAutoRefCount)
11742           CheckObjCConversion(SourceRange(), RHSType, E,
11743                               CCK_ImplicitConversion);
11744         LHS = ImpCastExprToType(E, RHSType,
11745                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11746       }
11747       else {
11748         Expr *E = RHS.get();
11749         if (getLangOpts().ObjCAutoRefCount)
11750           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11751                               /*Diagnose=*/true,
11752                               /*DiagnoseCFAudited=*/false, Opc);
11753         RHS = ImpCastExprToType(E, LHSType,
11754                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11755       }
11756       return computeResultTy();
11757     }
11758     if (LHSType->isObjCObjectPointerType() &&
11759         RHSType->isObjCObjectPointerType()) {
11760       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11761         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11762                                           /*isError*/false);
11763       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11764         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11765 
11766       if (LHSIsNull && !RHSIsNull)
11767         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11768       else
11769         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11770       return computeResultTy();
11771     }
11772 
11773     if (!IsOrdered && LHSType->isBlockPointerType() &&
11774         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11775       LHS = ImpCastExprToType(LHS.get(), RHSType,
11776                               CK_BlockPointerToObjCPointerCast);
11777       return computeResultTy();
11778     } else if (!IsOrdered &&
11779                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11780                RHSType->isBlockPointerType()) {
11781       RHS = ImpCastExprToType(RHS.get(), LHSType,
11782                               CK_BlockPointerToObjCPointerCast);
11783       return computeResultTy();
11784     }
11785   }
11786   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11787       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11788     unsigned DiagID = 0;
11789     bool isError = false;
11790     if (LangOpts.DebuggerSupport) {
11791       // Under a debugger, allow the comparison of pointers to integers,
11792       // since users tend to want to compare addresses.
11793     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11794                (RHSIsNull && RHSType->isIntegerType())) {
11795       if (IsOrdered) {
11796         isError = getLangOpts().CPlusPlus;
11797         DiagID =
11798           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11799                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11800       }
11801     } else if (getLangOpts().CPlusPlus) {
11802       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11803       isError = true;
11804     } else if (IsOrdered)
11805       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11806     else
11807       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11808 
11809     if (DiagID) {
11810       Diag(Loc, DiagID)
11811         << LHSType << RHSType << LHS.get()->getSourceRange()
11812         << RHS.get()->getSourceRange();
11813       if (isError)
11814         return QualType();
11815     }
11816 
11817     if (LHSType->isIntegerType())
11818       LHS = ImpCastExprToType(LHS.get(), RHSType,
11819                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11820     else
11821       RHS = ImpCastExprToType(RHS.get(), LHSType,
11822                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11823     return computeResultTy();
11824   }
11825 
11826   // Handle block pointers.
11827   if (!IsOrdered && RHSIsNull
11828       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11829     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11830     return computeResultTy();
11831   }
11832   if (!IsOrdered && LHSIsNull
11833       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11834     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11835     return computeResultTy();
11836   }
11837 
11838   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11839     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11840       return computeResultTy();
11841     }
11842 
11843     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11844       return computeResultTy();
11845     }
11846 
11847     if (LHSIsNull && RHSType->isQueueT()) {
11848       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11849       return computeResultTy();
11850     }
11851 
11852     if (LHSType->isQueueT() && RHSIsNull) {
11853       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11854       return computeResultTy();
11855     }
11856   }
11857 
11858   return InvalidOperands(Loc, LHS, RHS);
11859 }
11860 
11861 // Return a signed ext_vector_type that is of identical size and number of
11862 // elements. For floating point vectors, return an integer type of identical
11863 // size and number of elements. In the non ext_vector_type case, search from
11864 // the largest type to the smallest type to avoid cases where long long == long,
11865 // where long gets picked over long long.
11866 QualType Sema::GetSignedVectorType(QualType V) {
11867   const VectorType *VTy = V->castAs<VectorType>();
11868   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11869 
11870   if (isa<ExtVectorType>(VTy)) {
11871     if (TypeSize == Context.getTypeSize(Context.CharTy))
11872       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11873     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11874       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11875     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11876       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11877     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11878       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11879     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11880            "Unhandled vector element size in vector compare");
11881     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11882   }
11883 
11884   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11885     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11886                                  VectorType::GenericVector);
11887   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11888     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11889                                  VectorType::GenericVector);
11890   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11891     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11892                                  VectorType::GenericVector);
11893   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11894     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11895                                  VectorType::GenericVector);
11896   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11897          "Unhandled vector element size in vector compare");
11898   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11899                                VectorType::GenericVector);
11900 }
11901 
11902 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11903 /// operates on extended vector types.  Instead of producing an IntTy result,
11904 /// like a scalar comparison, a vector comparison produces a vector of integer
11905 /// types.
11906 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11907                                           SourceLocation Loc,
11908                                           BinaryOperatorKind Opc) {
11909   if (Opc == BO_Cmp) {
11910     Diag(Loc, diag::err_three_way_vector_comparison);
11911     return QualType();
11912   }
11913 
11914   // Check to make sure we're operating on vectors of the same type and width,
11915   // Allowing one side to be a scalar of element type.
11916   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11917                               /*AllowBothBool*/true,
11918                               /*AllowBoolConversions*/getLangOpts().ZVector);
11919   if (vType.isNull())
11920     return vType;
11921 
11922   QualType LHSType = LHS.get()->getType();
11923 
11924   // If AltiVec, the comparison results in a numeric type, i.e.
11925   // bool for C++, int for C
11926   if (getLangOpts().AltiVec &&
11927       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11928     return Context.getLogicalOperationType();
11929 
11930   // For non-floating point types, check for self-comparisons of the form
11931   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11932   // often indicate logic errors in the program.
11933   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11934 
11935   // Check for comparisons of floating point operands using != and ==.
11936   if (BinaryOperator::isEqualityOp(Opc) &&
11937       LHSType->hasFloatingRepresentation()) {
11938     assert(RHS.get()->getType()->hasFloatingRepresentation());
11939     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11940   }
11941 
11942   // Return a signed type for the vector.
11943   return GetSignedVectorType(vType);
11944 }
11945 
11946 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11947                                     const ExprResult &XorRHS,
11948                                     const SourceLocation Loc) {
11949   // Do not diagnose macros.
11950   if (Loc.isMacroID())
11951     return;
11952 
11953   bool Negative = false;
11954   bool ExplicitPlus = false;
11955   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11956   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11957 
11958   if (!LHSInt)
11959     return;
11960   if (!RHSInt) {
11961     // Check negative literals.
11962     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11963       UnaryOperatorKind Opc = UO->getOpcode();
11964       if (Opc != UO_Minus && Opc != UO_Plus)
11965         return;
11966       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11967       if (!RHSInt)
11968         return;
11969       Negative = (Opc == UO_Minus);
11970       ExplicitPlus = !Negative;
11971     } else {
11972       return;
11973     }
11974   }
11975 
11976   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11977   llvm::APInt RightSideValue = RHSInt->getValue();
11978   if (LeftSideValue != 2 && LeftSideValue != 10)
11979     return;
11980 
11981   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11982     return;
11983 
11984   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11985       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11986   llvm::StringRef ExprStr =
11987       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11988 
11989   CharSourceRange XorRange =
11990       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11991   llvm::StringRef XorStr =
11992       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11993   // Do not diagnose if xor keyword/macro is used.
11994   if (XorStr == "xor")
11995     return;
11996 
11997   std::string LHSStr = std::string(Lexer::getSourceText(
11998       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11999       S.getSourceManager(), S.getLangOpts()));
12000   std::string RHSStr = std::string(Lexer::getSourceText(
12001       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12002       S.getSourceManager(), S.getLangOpts()));
12003 
12004   if (Negative) {
12005     RightSideValue = -RightSideValue;
12006     RHSStr = "-" + RHSStr;
12007   } else if (ExplicitPlus) {
12008     RHSStr = "+" + RHSStr;
12009   }
12010 
12011   StringRef LHSStrRef = LHSStr;
12012   StringRef RHSStrRef = RHSStr;
12013   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12014   // literals.
12015   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12016       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12017       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12018       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12019       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12020       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12021       LHSStrRef.find('\'') != StringRef::npos ||
12022       RHSStrRef.find('\'') != StringRef::npos)
12023     return;
12024 
12025   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12026   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12027   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12028   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12029     std::string SuggestedExpr = "1 << " + RHSStr;
12030     bool Overflow = false;
12031     llvm::APInt One = (LeftSideValue - 1);
12032     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12033     if (Overflow) {
12034       if (RightSideIntValue < 64)
12035         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12036             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12037             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12038       else if (RightSideIntValue == 64)
12039         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12040       else
12041         return;
12042     } else {
12043       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12044           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12045           << PowValue.toString(10, true)
12046           << FixItHint::CreateReplacement(
12047                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12048     }
12049 
12050     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12051   } else if (LeftSideValue == 10) {
12052     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12053     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12054         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12055         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12056     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12057   }
12058 }
12059 
12060 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12061                                           SourceLocation Loc) {
12062   // Ensure that either both operands are of the same vector type, or
12063   // one operand is of a vector type and the other is of its element type.
12064   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12065                                        /*AllowBothBool*/true,
12066                                        /*AllowBoolConversions*/false);
12067   if (vType.isNull())
12068     return InvalidOperands(Loc, LHS, RHS);
12069   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12070       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12071     return InvalidOperands(Loc, LHS, RHS);
12072   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12073   //        usage of the logical operators && and || with vectors in C. This
12074   //        check could be notionally dropped.
12075   if (!getLangOpts().CPlusPlus &&
12076       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12077     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12078 
12079   return GetSignedVectorType(LHS.get()->getType());
12080 }
12081 
12082 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12083                                               SourceLocation Loc,
12084                                               bool IsCompAssign) {
12085   if (!IsCompAssign) {
12086     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12087     if (LHS.isInvalid())
12088       return QualType();
12089   }
12090   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12091   if (RHS.isInvalid())
12092     return QualType();
12093 
12094   // For conversion purposes, we ignore any qualifiers.
12095   // For example, "const float" and "float" are equivalent.
12096   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12097   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12098 
12099   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12100   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12101   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12102 
12103   if (Context.hasSameType(LHSType, RHSType))
12104     return LHSType;
12105 
12106   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12107   // case we have to return InvalidOperands.
12108   ExprResult OriginalLHS = LHS;
12109   ExprResult OriginalRHS = RHS;
12110   if (LHSMatType && !RHSMatType) {
12111     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12112     if (!RHS.isInvalid())
12113       return LHSType;
12114 
12115     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12116   }
12117 
12118   if (!LHSMatType && RHSMatType) {
12119     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12120     if (!LHS.isInvalid())
12121       return RHSType;
12122     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12123   }
12124 
12125   return InvalidOperands(Loc, LHS, RHS);
12126 }
12127 
12128 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12129                                            SourceLocation Loc,
12130                                            bool IsCompAssign) {
12131   if (!IsCompAssign) {
12132     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12133     if (LHS.isInvalid())
12134       return QualType();
12135   }
12136   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12137   if (RHS.isInvalid())
12138     return QualType();
12139 
12140   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12141   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12142   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12143 
12144   if (LHSMatType && RHSMatType) {
12145     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12146       return InvalidOperands(Loc, LHS, RHS);
12147 
12148     if (!Context.hasSameType(LHSMatType->getElementType(),
12149                              RHSMatType->getElementType()))
12150       return InvalidOperands(Loc, LHS, RHS);
12151 
12152     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12153                                          LHSMatType->getNumRows(),
12154                                          RHSMatType->getNumColumns());
12155   }
12156   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12157 }
12158 
12159 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12160                                            SourceLocation Loc,
12161                                            BinaryOperatorKind Opc) {
12162   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12163 
12164   bool IsCompAssign =
12165       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12166 
12167   if (LHS.get()->getType()->isVectorType() ||
12168       RHS.get()->getType()->isVectorType()) {
12169     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12170         RHS.get()->getType()->hasIntegerRepresentation())
12171       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12172                         /*AllowBothBool*/true,
12173                         /*AllowBoolConversions*/getLangOpts().ZVector);
12174     return InvalidOperands(Loc, LHS, RHS);
12175   }
12176 
12177   if (Opc == BO_And)
12178     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12179 
12180   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12181       RHS.get()->getType()->hasFloatingRepresentation())
12182     return InvalidOperands(Loc, LHS, RHS);
12183 
12184   ExprResult LHSResult = LHS, RHSResult = RHS;
12185   QualType compType = UsualArithmeticConversions(
12186       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12187   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12188     return QualType();
12189   LHS = LHSResult.get();
12190   RHS = RHSResult.get();
12191 
12192   if (Opc == BO_Xor)
12193     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12194 
12195   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12196     return compType;
12197   return InvalidOperands(Loc, LHS, RHS);
12198 }
12199 
12200 // C99 6.5.[13,14]
12201 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12202                                            SourceLocation Loc,
12203                                            BinaryOperatorKind Opc) {
12204   // Check vector operands differently.
12205   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12206     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12207 
12208   bool EnumConstantInBoolContext = false;
12209   for (const ExprResult &HS : {LHS, RHS}) {
12210     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12211       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12212       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12213         EnumConstantInBoolContext = true;
12214     }
12215   }
12216 
12217   if (EnumConstantInBoolContext)
12218     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12219 
12220   // Diagnose cases where the user write a logical and/or but probably meant a
12221   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12222   // is a constant.
12223   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12224       !LHS.get()->getType()->isBooleanType() &&
12225       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12226       // Don't warn in macros or template instantiations.
12227       !Loc.isMacroID() && !inTemplateInstantiation()) {
12228     // If the RHS can be constant folded, and if it constant folds to something
12229     // that isn't 0 or 1 (which indicate a potential logical operation that
12230     // happened to fold to true/false) then warn.
12231     // Parens on the RHS are ignored.
12232     Expr::EvalResult EVResult;
12233     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12234       llvm::APSInt Result = EVResult.Val.getInt();
12235       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12236            !RHS.get()->getExprLoc().isMacroID()) ||
12237           (Result != 0 && Result != 1)) {
12238         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12239           << RHS.get()->getSourceRange()
12240           << (Opc == BO_LAnd ? "&&" : "||");
12241         // Suggest replacing the logical operator with the bitwise version
12242         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12243             << (Opc == BO_LAnd ? "&" : "|")
12244             << FixItHint::CreateReplacement(SourceRange(
12245                                                  Loc, getLocForEndOfToken(Loc)),
12246                                             Opc == BO_LAnd ? "&" : "|");
12247         if (Opc == BO_LAnd)
12248           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12249           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12250               << FixItHint::CreateRemoval(
12251                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12252                                  RHS.get()->getEndLoc()));
12253       }
12254     }
12255   }
12256 
12257   if (!Context.getLangOpts().CPlusPlus) {
12258     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12259     // not operate on the built-in scalar and vector float types.
12260     if (Context.getLangOpts().OpenCL &&
12261         Context.getLangOpts().OpenCLVersion < 120) {
12262       if (LHS.get()->getType()->isFloatingType() ||
12263           RHS.get()->getType()->isFloatingType())
12264         return InvalidOperands(Loc, LHS, RHS);
12265     }
12266 
12267     LHS = UsualUnaryConversions(LHS.get());
12268     if (LHS.isInvalid())
12269       return QualType();
12270 
12271     RHS = UsualUnaryConversions(RHS.get());
12272     if (RHS.isInvalid())
12273       return QualType();
12274 
12275     if (!LHS.get()->getType()->isScalarType() ||
12276         !RHS.get()->getType()->isScalarType())
12277       return InvalidOperands(Loc, LHS, RHS);
12278 
12279     return Context.IntTy;
12280   }
12281 
12282   // The following is safe because we only use this method for
12283   // non-overloadable operands.
12284 
12285   // C++ [expr.log.and]p1
12286   // C++ [expr.log.or]p1
12287   // The operands are both contextually converted to type bool.
12288   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12289   if (LHSRes.isInvalid())
12290     return InvalidOperands(Loc, LHS, RHS);
12291   LHS = LHSRes;
12292 
12293   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12294   if (RHSRes.isInvalid())
12295     return InvalidOperands(Loc, LHS, RHS);
12296   RHS = RHSRes;
12297 
12298   // C++ [expr.log.and]p2
12299   // C++ [expr.log.or]p2
12300   // The result is a bool.
12301   return Context.BoolTy;
12302 }
12303 
12304 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12305   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12306   if (!ME) return false;
12307   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12308   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12309       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12310   if (!Base) return false;
12311   return Base->getMethodDecl() != nullptr;
12312 }
12313 
12314 /// Is the given expression (which must be 'const') a reference to a
12315 /// variable which was originally non-const, but which has become
12316 /// 'const' due to being captured within a block?
12317 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12318 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12319   assert(E->isLValue() && E->getType().isConstQualified());
12320   E = E->IgnoreParens();
12321 
12322   // Must be a reference to a declaration from an enclosing scope.
12323   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12324   if (!DRE) return NCCK_None;
12325   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12326 
12327   // The declaration must be a variable which is not declared 'const'.
12328   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12329   if (!var) return NCCK_None;
12330   if (var->getType().isConstQualified()) return NCCK_None;
12331   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12332 
12333   // Decide whether the first capture was for a block or a lambda.
12334   DeclContext *DC = S.CurContext, *Prev = nullptr;
12335   // Decide whether the first capture was for a block or a lambda.
12336   while (DC) {
12337     // For init-capture, it is possible that the variable belongs to the
12338     // template pattern of the current context.
12339     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12340       if (var->isInitCapture() &&
12341           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12342         break;
12343     if (DC == var->getDeclContext())
12344       break;
12345     Prev = DC;
12346     DC = DC->getParent();
12347   }
12348   // Unless we have an init-capture, we've gone one step too far.
12349   if (!var->isInitCapture())
12350     DC = Prev;
12351   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12352 }
12353 
12354 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12355   Ty = Ty.getNonReferenceType();
12356   if (IsDereference && Ty->isPointerType())
12357     Ty = Ty->getPointeeType();
12358   return !Ty.isConstQualified();
12359 }
12360 
12361 // Update err_typecheck_assign_const and note_typecheck_assign_const
12362 // when this enum is changed.
12363 enum {
12364   ConstFunction,
12365   ConstVariable,
12366   ConstMember,
12367   ConstMethod,
12368   NestedConstMember,
12369   ConstUnknown,  // Keep as last element
12370 };
12371 
12372 /// Emit the "read-only variable not assignable" error and print notes to give
12373 /// more information about why the variable is not assignable, such as pointing
12374 /// to the declaration of a const variable, showing that a method is const, or
12375 /// that the function is returning a const reference.
12376 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12377                                     SourceLocation Loc) {
12378   SourceRange ExprRange = E->getSourceRange();
12379 
12380   // Only emit one error on the first const found.  All other consts will emit
12381   // a note to the error.
12382   bool DiagnosticEmitted = false;
12383 
12384   // Track if the current expression is the result of a dereference, and if the
12385   // next checked expression is the result of a dereference.
12386   bool IsDereference = false;
12387   bool NextIsDereference = false;
12388 
12389   // Loop to process MemberExpr chains.
12390   while (true) {
12391     IsDereference = NextIsDereference;
12392 
12393     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12394     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12395       NextIsDereference = ME->isArrow();
12396       const ValueDecl *VD = ME->getMemberDecl();
12397       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12398         // Mutable fields can be modified even if the class is const.
12399         if (Field->isMutable()) {
12400           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12401           break;
12402         }
12403 
12404         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12405           if (!DiagnosticEmitted) {
12406             S.Diag(Loc, diag::err_typecheck_assign_const)
12407                 << ExprRange << ConstMember << false /*static*/ << Field
12408                 << Field->getType();
12409             DiagnosticEmitted = true;
12410           }
12411           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12412               << ConstMember << false /*static*/ << Field << Field->getType()
12413               << Field->getSourceRange();
12414         }
12415         E = ME->getBase();
12416         continue;
12417       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12418         if (VDecl->getType().isConstQualified()) {
12419           if (!DiagnosticEmitted) {
12420             S.Diag(Loc, diag::err_typecheck_assign_const)
12421                 << ExprRange << ConstMember << true /*static*/ << VDecl
12422                 << VDecl->getType();
12423             DiagnosticEmitted = true;
12424           }
12425           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12426               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12427               << VDecl->getSourceRange();
12428         }
12429         // Static fields do not inherit constness from parents.
12430         break;
12431       }
12432       break; // End MemberExpr
12433     } else if (const ArraySubscriptExpr *ASE =
12434                    dyn_cast<ArraySubscriptExpr>(E)) {
12435       E = ASE->getBase()->IgnoreParenImpCasts();
12436       continue;
12437     } else if (const ExtVectorElementExpr *EVE =
12438                    dyn_cast<ExtVectorElementExpr>(E)) {
12439       E = EVE->getBase()->IgnoreParenImpCasts();
12440       continue;
12441     }
12442     break;
12443   }
12444 
12445   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12446     // Function calls
12447     const FunctionDecl *FD = CE->getDirectCallee();
12448     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12449       if (!DiagnosticEmitted) {
12450         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12451                                                       << ConstFunction << FD;
12452         DiagnosticEmitted = true;
12453       }
12454       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12455              diag::note_typecheck_assign_const)
12456           << ConstFunction << FD << FD->getReturnType()
12457           << FD->getReturnTypeSourceRange();
12458     }
12459   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12460     // Point to variable declaration.
12461     if (const ValueDecl *VD = DRE->getDecl()) {
12462       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12463         if (!DiagnosticEmitted) {
12464           S.Diag(Loc, diag::err_typecheck_assign_const)
12465               << ExprRange << ConstVariable << VD << VD->getType();
12466           DiagnosticEmitted = true;
12467         }
12468         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12469             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12470       }
12471     }
12472   } else if (isa<CXXThisExpr>(E)) {
12473     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12474       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12475         if (MD->isConst()) {
12476           if (!DiagnosticEmitted) {
12477             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12478                                                           << ConstMethod << MD;
12479             DiagnosticEmitted = true;
12480           }
12481           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12482               << ConstMethod << MD << MD->getSourceRange();
12483         }
12484       }
12485     }
12486   }
12487 
12488   if (DiagnosticEmitted)
12489     return;
12490 
12491   // Can't determine a more specific message, so display the generic error.
12492   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12493 }
12494 
12495 enum OriginalExprKind {
12496   OEK_Variable,
12497   OEK_Member,
12498   OEK_LValue
12499 };
12500 
12501 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12502                                          const RecordType *Ty,
12503                                          SourceLocation Loc, SourceRange Range,
12504                                          OriginalExprKind OEK,
12505                                          bool &DiagnosticEmitted) {
12506   std::vector<const RecordType *> RecordTypeList;
12507   RecordTypeList.push_back(Ty);
12508   unsigned NextToCheckIndex = 0;
12509   // We walk the record hierarchy breadth-first to ensure that we print
12510   // diagnostics in field nesting order.
12511   while (RecordTypeList.size() > NextToCheckIndex) {
12512     bool IsNested = NextToCheckIndex > 0;
12513     for (const FieldDecl *Field :
12514          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12515       // First, check every field for constness.
12516       QualType FieldTy = Field->getType();
12517       if (FieldTy.isConstQualified()) {
12518         if (!DiagnosticEmitted) {
12519           S.Diag(Loc, diag::err_typecheck_assign_const)
12520               << Range << NestedConstMember << OEK << VD
12521               << IsNested << Field;
12522           DiagnosticEmitted = true;
12523         }
12524         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12525             << NestedConstMember << IsNested << Field
12526             << FieldTy << Field->getSourceRange();
12527       }
12528 
12529       // Then we append it to the list to check next in order.
12530       FieldTy = FieldTy.getCanonicalType();
12531       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12532         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12533           RecordTypeList.push_back(FieldRecTy);
12534       }
12535     }
12536     ++NextToCheckIndex;
12537   }
12538 }
12539 
12540 /// Emit an error for the case where a record we are trying to assign to has a
12541 /// const-qualified field somewhere in its hierarchy.
12542 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12543                                          SourceLocation Loc) {
12544   QualType Ty = E->getType();
12545   assert(Ty->isRecordType() && "lvalue was not record?");
12546   SourceRange Range = E->getSourceRange();
12547   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12548   bool DiagEmitted = false;
12549 
12550   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12551     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12552             Range, OEK_Member, DiagEmitted);
12553   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12554     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12555             Range, OEK_Variable, DiagEmitted);
12556   else
12557     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12558             Range, OEK_LValue, DiagEmitted);
12559   if (!DiagEmitted)
12560     DiagnoseConstAssignment(S, E, Loc);
12561 }
12562 
12563 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12564 /// emit an error and return true.  If so, return false.
12565 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12566   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12567 
12568   S.CheckShadowingDeclModification(E, Loc);
12569 
12570   SourceLocation OrigLoc = Loc;
12571   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12572                                                               &Loc);
12573   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12574     IsLV = Expr::MLV_InvalidMessageExpression;
12575   if (IsLV == Expr::MLV_Valid)
12576     return false;
12577 
12578   unsigned DiagID = 0;
12579   bool NeedType = false;
12580   switch (IsLV) { // C99 6.5.16p2
12581   case Expr::MLV_ConstQualified:
12582     // Use a specialized diagnostic when we're assigning to an object
12583     // from an enclosing function or block.
12584     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12585       if (NCCK == NCCK_Block)
12586         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12587       else
12588         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12589       break;
12590     }
12591 
12592     // In ARC, use some specialized diagnostics for occasions where we
12593     // infer 'const'.  These are always pseudo-strong variables.
12594     if (S.getLangOpts().ObjCAutoRefCount) {
12595       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12596       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12597         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12598 
12599         // Use the normal diagnostic if it's pseudo-__strong but the
12600         // user actually wrote 'const'.
12601         if (var->isARCPseudoStrong() &&
12602             (!var->getTypeSourceInfo() ||
12603              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12604           // There are three pseudo-strong cases:
12605           //  - self
12606           ObjCMethodDecl *method = S.getCurMethodDecl();
12607           if (method && var == method->getSelfDecl()) {
12608             DiagID = method->isClassMethod()
12609               ? diag::err_typecheck_arc_assign_self_class_method
12610               : diag::err_typecheck_arc_assign_self;
12611 
12612           //  - Objective-C externally_retained attribute.
12613           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12614                      isa<ParmVarDecl>(var)) {
12615             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12616 
12617           //  - fast enumeration variables
12618           } else {
12619             DiagID = diag::err_typecheck_arr_assign_enumeration;
12620           }
12621 
12622           SourceRange Assign;
12623           if (Loc != OrigLoc)
12624             Assign = SourceRange(OrigLoc, OrigLoc);
12625           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12626           // We need to preserve the AST regardless, so migration tool
12627           // can do its job.
12628           return false;
12629         }
12630       }
12631     }
12632 
12633     // If none of the special cases above are triggered, then this is a
12634     // simple const assignment.
12635     if (DiagID == 0) {
12636       DiagnoseConstAssignment(S, E, Loc);
12637       return true;
12638     }
12639 
12640     break;
12641   case Expr::MLV_ConstAddrSpace:
12642     DiagnoseConstAssignment(S, E, Loc);
12643     return true;
12644   case Expr::MLV_ConstQualifiedField:
12645     DiagnoseRecursiveConstFields(S, E, Loc);
12646     return true;
12647   case Expr::MLV_ArrayType:
12648   case Expr::MLV_ArrayTemporary:
12649     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12650     NeedType = true;
12651     break;
12652   case Expr::MLV_NotObjectType:
12653     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12654     NeedType = true;
12655     break;
12656   case Expr::MLV_LValueCast:
12657     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12658     break;
12659   case Expr::MLV_Valid:
12660     llvm_unreachable("did not take early return for MLV_Valid");
12661   case Expr::MLV_InvalidExpression:
12662   case Expr::MLV_MemberFunction:
12663   case Expr::MLV_ClassTemporary:
12664     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12665     break;
12666   case Expr::MLV_IncompleteType:
12667   case Expr::MLV_IncompleteVoidType:
12668     return S.RequireCompleteType(Loc, E->getType(),
12669              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12670   case Expr::MLV_DuplicateVectorComponents:
12671     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12672     break;
12673   case Expr::MLV_NoSetterProperty:
12674     llvm_unreachable("readonly properties should be processed differently");
12675   case Expr::MLV_InvalidMessageExpression:
12676     DiagID = diag::err_readonly_message_assignment;
12677     break;
12678   case Expr::MLV_SubObjCPropertySetting:
12679     DiagID = diag::err_no_subobject_property_setting;
12680     break;
12681   }
12682 
12683   SourceRange Assign;
12684   if (Loc != OrigLoc)
12685     Assign = SourceRange(OrigLoc, OrigLoc);
12686   if (NeedType)
12687     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12688   else
12689     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12690   return true;
12691 }
12692 
12693 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12694                                          SourceLocation Loc,
12695                                          Sema &Sema) {
12696   if (Sema.inTemplateInstantiation())
12697     return;
12698   if (Sema.isUnevaluatedContext())
12699     return;
12700   if (Loc.isInvalid() || Loc.isMacroID())
12701     return;
12702   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12703     return;
12704 
12705   // C / C++ fields
12706   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12707   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12708   if (ML && MR) {
12709     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12710       return;
12711     const ValueDecl *LHSDecl =
12712         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12713     const ValueDecl *RHSDecl =
12714         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12715     if (LHSDecl != RHSDecl)
12716       return;
12717     if (LHSDecl->getType().isVolatileQualified())
12718       return;
12719     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12720       if (RefTy->getPointeeType().isVolatileQualified())
12721         return;
12722 
12723     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12724   }
12725 
12726   // Objective-C instance variables
12727   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12728   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12729   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12730     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12731     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12732     if (RL && RR && RL->getDecl() == RR->getDecl())
12733       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12734   }
12735 }
12736 
12737 // C99 6.5.16.1
12738 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12739                                        SourceLocation Loc,
12740                                        QualType CompoundType) {
12741   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12742 
12743   // Verify that LHS is a modifiable lvalue, and emit error if not.
12744   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12745     return QualType();
12746 
12747   QualType LHSType = LHSExpr->getType();
12748   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12749                                              CompoundType;
12750   // OpenCL v1.2 s6.1.1.1 p2:
12751   // The half data type can only be used to declare a pointer to a buffer that
12752   // contains half values
12753   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12754     LHSType->isHalfType()) {
12755     Diag(Loc, diag::err_opencl_half_load_store) << 1
12756         << LHSType.getUnqualifiedType();
12757     return QualType();
12758   }
12759 
12760   AssignConvertType ConvTy;
12761   if (CompoundType.isNull()) {
12762     Expr *RHSCheck = RHS.get();
12763 
12764     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12765 
12766     QualType LHSTy(LHSType);
12767     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12768     if (RHS.isInvalid())
12769       return QualType();
12770     // Special case of NSObject attributes on c-style pointer types.
12771     if (ConvTy == IncompatiblePointer &&
12772         ((Context.isObjCNSObjectType(LHSType) &&
12773           RHSType->isObjCObjectPointerType()) ||
12774          (Context.isObjCNSObjectType(RHSType) &&
12775           LHSType->isObjCObjectPointerType())))
12776       ConvTy = Compatible;
12777 
12778     if (ConvTy == Compatible &&
12779         LHSType->isObjCObjectType())
12780         Diag(Loc, diag::err_objc_object_assignment)
12781           << LHSType;
12782 
12783     // If the RHS is a unary plus or minus, check to see if they = and + are
12784     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12785     // instead of "x += 4".
12786     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12787       RHSCheck = ICE->getSubExpr();
12788     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12789       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12790           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12791           // Only if the two operators are exactly adjacent.
12792           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12793           // And there is a space or other character before the subexpr of the
12794           // unary +/-.  We don't want to warn on "x=-1".
12795           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12796           UO->getSubExpr()->getBeginLoc().isFileID()) {
12797         Diag(Loc, diag::warn_not_compound_assign)
12798           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12799           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12800       }
12801     }
12802 
12803     if (ConvTy == Compatible) {
12804       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12805         // Warn about retain cycles where a block captures the LHS, but
12806         // not if the LHS is a simple variable into which the block is
12807         // being stored...unless that variable can be captured by reference!
12808         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12809         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12810         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12811           checkRetainCycles(LHSExpr, RHS.get());
12812       }
12813 
12814       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12815           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12816         // It is safe to assign a weak reference into a strong variable.
12817         // Although this code can still have problems:
12818         //   id x = self.weakProp;
12819         //   id y = self.weakProp;
12820         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12821         // paths through the function. This should be revisited if
12822         // -Wrepeated-use-of-weak is made flow-sensitive.
12823         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12824         // variable, which will be valid for the current autorelease scope.
12825         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12826                              RHS.get()->getBeginLoc()))
12827           getCurFunction()->markSafeWeakUse(RHS.get());
12828 
12829       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12830         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12831       }
12832     }
12833   } else {
12834     // Compound assignment "x += y"
12835     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12836   }
12837 
12838   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12839                                RHS.get(), AA_Assigning))
12840     return QualType();
12841 
12842   CheckForNullPointerDereference(*this, LHSExpr);
12843 
12844   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12845     if (CompoundType.isNull()) {
12846       // C++2a [expr.ass]p5:
12847       //   A simple-assignment whose left operand is of a volatile-qualified
12848       //   type is deprecated unless the assignment is either a discarded-value
12849       //   expression or an unevaluated operand
12850       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12851     } else {
12852       // C++2a [expr.ass]p6:
12853       //   [Compound-assignment] expressions are deprecated if E1 has
12854       //   volatile-qualified type
12855       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12856     }
12857   }
12858 
12859   // C99 6.5.16p3: The type of an assignment expression is the type of the
12860   // left operand unless the left operand has qualified type, in which case
12861   // it is the unqualified version of the type of the left operand.
12862   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12863   // is converted to the type of the assignment expression (above).
12864   // C++ 5.17p1: the type of the assignment expression is that of its left
12865   // operand.
12866   return (getLangOpts().CPlusPlus
12867           ? LHSType : LHSType.getUnqualifiedType());
12868 }
12869 
12870 // Only ignore explicit casts to void.
12871 static bool IgnoreCommaOperand(const Expr *E) {
12872   E = E->IgnoreParens();
12873 
12874   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12875     if (CE->getCastKind() == CK_ToVoid) {
12876       return true;
12877     }
12878 
12879     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12880     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12881         CE->getSubExpr()->getType()->isDependentType()) {
12882       return true;
12883     }
12884   }
12885 
12886   return false;
12887 }
12888 
12889 // Look for instances where it is likely the comma operator is confused with
12890 // another operator.  There is an explicit list of acceptable expressions for
12891 // the left hand side of the comma operator, otherwise emit a warning.
12892 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12893   // No warnings in macros
12894   if (Loc.isMacroID())
12895     return;
12896 
12897   // Don't warn in template instantiations.
12898   if (inTemplateInstantiation())
12899     return;
12900 
12901   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12902   // instead, skip more than needed, then call back into here with the
12903   // CommaVisitor in SemaStmt.cpp.
12904   // The listed locations are the initialization and increment portions
12905   // of a for loop.  The additional checks are on the condition of
12906   // if statements, do/while loops, and for loops.
12907   // Differences in scope flags for C89 mode requires the extra logic.
12908   const unsigned ForIncrementFlags =
12909       getLangOpts().C99 || getLangOpts().CPlusPlus
12910           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12911           : Scope::ContinueScope | Scope::BreakScope;
12912   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12913   const unsigned ScopeFlags = getCurScope()->getFlags();
12914   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12915       (ScopeFlags & ForInitFlags) == ForInitFlags)
12916     return;
12917 
12918   // If there are multiple comma operators used together, get the RHS of the
12919   // of the comma operator as the LHS.
12920   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12921     if (BO->getOpcode() != BO_Comma)
12922       break;
12923     LHS = BO->getRHS();
12924   }
12925 
12926   // Only allow some expressions on LHS to not warn.
12927   if (IgnoreCommaOperand(LHS))
12928     return;
12929 
12930   Diag(Loc, diag::warn_comma_operator);
12931   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12932       << LHS->getSourceRange()
12933       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12934                                     LangOpts.CPlusPlus ? "static_cast<void>("
12935                                                        : "(void)(")
12936       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12937                                     ")");
12938 }
12939 
12940 // C99 6.5.17
12941 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12942                                    SourceLocation Loc) {
12943   LHS = S.CheckPlaceholderExpr(LHS.get());
12944   RHS = S.CheckPlaceholderExpr(RHS.get());
12945   if (LHS.isInvalid() || RHS.isInvalid())
12946     return QualType();
12947 
12948   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12949   // operands, but not unary promotions.
12950   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12951 
12952   // So we treat the LHS as a ignored value, and in C++ we allow the
12953   // containing site to determine what should be done with the RHS.
12954   LHS = S.IgnoredValueConversions(LHS.get());
12955   if (LHS.isInvalid())
12956     return QualType();
12957 
12958   S.DiagnoseUnusedExprResult(LHS.get());
12959 
12960   if (!S.getLangOpts().CPlusPlus) {
12961     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12962     if (RHS.isInvalid())
12963       return QualType();
12964     if (!RHS.get()->getType()->isVoidType())
12965       S.RequireCompleteType(Loc, RHS.get()->getType(),
12966                             diag::err_incomplete_type);
12967   }
12968 
12969   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12970     S.DiagnoseCommaOperator(LHS.get(), Loc);
12971 
12972   return RHS.get()->getType();
12973 }
12974 
12975 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12976 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12977 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12978                                                ExprValueKind &VK,
12979                                                ExprObjectKind &OK,
12980                                                SourceLocation OpLoc,
12981                                                bool IsInc, bool IsPrefix) {
12982   if (Op->isTypeDependent())
12983     return S.Context.DependentTy;
12984 
12985   QualType ResType = Op->getType();
12986   // Atomic types can be used for increment / decrement where the non-atomic
12987   // versions can, so ignore the _Atomic() specifier for the purpose of
12988   // checking.
12989   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12990     ResType = ResAtomicType->getValueType();
12991 
12992   assert(!ResType.isNull() && "no type for increment/decrement expression");
12993 
12994   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12995     // Decrement of bool is not allowed.
12996     if (!IsInc) {
12997       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12998       return QualType();
12999     }
13000     // Increment of bool sets it to true, but is deprecated.
13001     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13002                                               : diag::warn_increment_bool)
13003       << Op->getSourceRange();
13004   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13005     // Error on enum increments and decrements in C++ mode
13006     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13007     return QualType();
13008   } else if (ResType->isRealType()) {
13009     // OK!
13010   } else if (ResType->isPointerType()) {
13011     // C99 6.5.2.4p2, 6.5.6p2
13012     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13013       return QualType();
13014   } else if (ResType->isObjCObjectPointerType()) {
13015     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13016     // Otherwise, we just need a complete type.
13017     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13018         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13019       return QualType();
13020   } else if (ResType->isAnyComplexType()) {
13021     // C99 does not support ++/-- on complex types, we allow as an extension.
13022     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13023       << ResType << Op->getSourceRange();
13024   } else if (ResType->isPlaceholderType()) {
13025     ExprResult PR = S.CheckPlaceholderExpr(Op);
13026     if (PR.isInvalid()) return QualType();
13027     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13028                                           IsInc, IsPrefix);
13029   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13030     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13031   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13032              (ResType->castAs<VectorType>()->getVectorKind() !=
13033               VectorType::AltiVecBool)) {
13034     // The z vector extensions allow ++ and -- for non-bool vectors.
13035   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13036             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13037     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13038   } else {
13039     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13040       << ResType << int(IsInc) << Op->getSourceRange();
13041     return QualType();
13042   }
13043   // At this point, we know we have a real, complex or pointer type.
13044   // Now make sure the operand is a modifiable lvalue.
13045   if (CheckForModifiableLvalue(Op, OpLoc, S))
13046     return QualType();
13047   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13048     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13049     //   An operand with volatile-qualified type is deprecated
13050     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13051         << IsInc << ResType;
13052   }
13053   // In C++, a prefix increment is the same type as the operand. Otherwise
13054   // (in C or with postfix), the increment is the unqualified type of the
13055   // operand.
13056   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13057     VK = VK_LValue;
13058     OK = Op->getObjectKind();
13059     return ResType;
13060   } else {
13061     VK = VK_RValue;
13062     return ResType.getUnqualifiedType();
13063   }
13064 }
13065 
13066 
13067 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13068 /// This routine allows us to typecheck complex/recursive expressions
13069 /// where the declaration is needed for type checking. We only need to
13070 /// handle cases when the expression references a function designator
13071 /// or is an lvalue. Here are some examples:
13072 ///  - &(x) => x
13073 ///  - &*****f => f for f a function designator.
13074 ///  - &s.xx => s
13075 ///  - &s.zz[1].yy -> s, if zz is an array
13076 ///  - *(x + 1) -> x, if x is an array
13077 ///  - &"123"[2] -> 0
13078 ///  - & __real__ x -> x
13079 ///
13080 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13081 /// members.
13082 static ValueDecl *getPrimaryDecl(Expr *E) {
13083   switch (E->getStmtClass()) {
13084   case Stmt::DeclRefExprClass:
13085     return cast<DeclRefExpr>(E)->getDecl();
13086   case Stmt::MemberExprClass:
13087     // If this is an arrow operator, the address is an offset from
13088     // the base's value, so the object the base refers to is
13089     // irrelevant.
13090     if (cast<MemberExpr>(E)->isArrow())
13091       return nullptr;
13092     // Otherwise, the expression refers to a part of the base
13093     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13094   case Stmt::ArraySubscriptExprClass: {
13095     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13096     // promotion of register arrays earlier.
13097     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13098     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13099       if (ICE->getSubExpr()->getType()->isArrayType())
13100         return getPrimaryDecl(ICE->getSubExpr());
13101     }
13102     return nullptr;
13103   }
13104   case Stmt::UnaryOperatorClass: {
13105     UnaryOperator *UO = cast<UnaryOperator>(E);
13106 
13107     switch(UO->getOpcode()) {
13108     case UO_Real:
13109     case UO_Imag:
13110     case UO_Extension:
13111       return getPrimaryDecl(UO->getSubExpr());
13112     default:
13113       return nullptr;
13114     }
13115   }
13116   case Stmt::ParenExprClass:
13117     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13118   case Stmt::ImplicitCastExprClass:
13119     // If the result of an implicit cast is an l-value, we care about
13120     // the sub-expression; otherwise, the result here doesn't matter.
13121     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13122   case Stmt::CXXUuidofExprClass:
13123     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13124   default:
13125     return nullptr;
13126   }
13127 }
13128 
13129 namespace {
13130 enum {
13131   AO_Bit_Field = 0,
13132   AO_Vector_Element = 1,
13133   AO_Property_Expansion = 2,
13134   AO_Register_Variable = 3,
13135   AO_Matrix_Element = 4,
13136   AO_No_Error = 5
13137 };
13138 }
13139 /// Diagnose invalid operand for address of operations.
13140 ///
13141 /// \param Type The type of operand which cannot have its address taken.
13142 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13143                                          Expr *E, unsigned Type) {
13144   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13145 }
13146 
13147 /// CheckAddressOfOperand - The operand of & must be either a function
13148 /// designator or an lvalue designating an object. If it is an lvalue, the
13149 /// object cannot be declared with storage class register or be a bit field.
13150 /// Note: The usual conversions are *not* applied to the operand of the &
13151 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13152 /// In C++, the operand might be an overloaded function name, in which case
13153 /// we allow the '&' but retain the overloaded-function type.
13154 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13155   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13156     if (PTy->getKind() == BuiltinType::Overload) {
13157       Expr *E = OrigOp.get()->IgnoreParens();
13158       if (!isa<OverloadExpr>(E)) {
13159         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13160         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13161           << OrigOp.get()->getSourceRange();
13162         return QualType();
13163       }
13164 
13165       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13166       if (isa<UnresolvedMemberExpr>(Ovl))
13167         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13168           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13169             << OrigOp.get()->getSourceRange();
13170           return QualType();
13171         }
13172 
13173       return Context.OverloadTy;
13174     }
13175 
13176     if (PTy->getKind() == BuiltinType::UnknownAny)
13177       return Context.UnknownAnyTy;
13178 
13179     if (PTy->getKind() == BuiltinType::BoundMember) {
13180       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13181         << OrigOp.get()->getSourceRange();
13182       return QualType();
13183     }
13184 
13185     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13186     if (OrigOp.isInvalid()) return QualType();
13187   }
13188 
13189   if (OrigOp.get()->isTypeDependent())
13190     return Context.DependentTy;
13191 
13192   assert(!OrigOp.get()->getType()->isPlaceholderType());
13193 
13194   // Make sure to ignore parentheses in subsequent checks
13195   Expr *op = OrigOp.get()->IgnoreParens();
13196 
13197   // In OpenCL captures for blocks called as lambda functions
13198   // are located in the private address space. Blocks used in
13199   // enqueue_kernel can be located in a different address space
13200   // depending on a vendor implementation. Thus preventing
13201   // taking an address of the capture to avoid invalid AS casts.
13202   if (LangOpts.OpenCL) {
13203     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13204     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13205       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13206       return QualType();
13207     }
13208   }
13209 
13210   if (getLangOpts().C99) {
13211     // Implement C99-only parts of addressof rules.
13212     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13213       if (uOp->getOpcode() == UO_Deref)
13214         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13215         // (assuming the deref expression is valid).
13216         return uOp->getSubExpr()->getType();
13217     }
13218     // Technically, there should be a check for array subscript
13219     // expressions here, but the result of one is always an lvalue anyway.
13220   }
13221   ValueDecl *dcl = getPrimaryDecl(op);
13222 
13223   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13224     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13225                                            op->getBeginLoc()))
13226       return QualType();
13227 
13228   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13229   unsigned AddressOfError = AO_No_Error;
13230 
13231   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13232     bool sfinae = (bool)isSFINAEContext();
13233     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13234                                   : diag::ext_typecheck_addrof_temporary)
13235       << op->getType() << op->getSourceRange();
13236     if (sfinae)
13237       return QualType();
13238     // Materialize the temporary as an lvalue so that we can take its address.
13239     OrigOp = op =
13240         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13241   } else if (isa<ObjCSelectorExpr>(op)) {
13242     return Context.getPointerType(op->getType());
13243   } else if (lval == Expr::LV_MemberFunction) {
13244     // If it's an instance method, make a member pointer.
13245     // The expression must have exactly the form &A::foo.
13246 
13247     // If the underlying expression isn't a decl ref, give up.
13248     if (!isa<DeclRefExpr>(op)) {
13249       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13250         << OrigOp.get()->getSourceRange();
13251       return QualType();
13252     }
13253     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13254     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13255 
13256     // The id-expression was parenthesized.
13257     if (OrigOp.get() != DRE) {
13258       Diag(OpLoc, diag::err_parens_pointer_member_function)
13259         << OrigOp.get()->getSourceRange();
13260 
13261     // The method was named without a qualifier.
13262     } else if (!DRE->getQualifier()) {
13263       if (MD->getParent()->getName().empty())
13264         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13265           << op->getSourceRange();
13266       else {
13267         SmallString<32> Str;
13268         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13269         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13270           << op->getSourceRange()
13271           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13272       }
13273     }
13274 
13275     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13276     if (isa<CXXDestructorDecl>(MD))
13277       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13278 
13279     QualType MPTy = Context.getMemberPointerType(
13280         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13281     // Under the MS ABI, lock down the inheritance model now.
13282     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13283       (void)isCompleteType(OpLoc, MPTy);
13284     return MPTy;
13285   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13286     // C99 6.5.3.2p1
13287     // The operand must be either an l-value or a function designator
13288     if (!op->getType()->isFunctionType()) {
13289       // Use a special diagnostic for loads from property references.
13290       if (isa<PseudoObjectExpr>(op)) {
13291         AddressOfError = AO_Property_Expansion;
13292       } else {
13293         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13294           << op->getType() << op->getSourceRange();
13295         return QualType();
13296       }
13297     }
13298   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13299     // The operand cannot be a bit-field
13300     AddressOfError = AO_Bit_Field;
13301   } else if (op->getObjectKind() == OK_VectorComponent) {
13302     // The operand cannot be an element of a vector
13303     AddressOfError = AO_Vector_Element;
13304   } else if (op->getObjectKind() == OK_MatrixComponent) {
13305     // The operand cannot be an element of a matrix.
13306     AddressOfError = AO_Matrix_Element;
13307   } else if (dcl) { // C99 6.5.3.2p1
13308     // We have an lvalue with a decl. Make sure the decl is not declared
13309     // with the register storage-class specifier.
13310     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13311       // in C++ it is not error to take address of a register
13312       // variable (c++03 7.1.1P3)
13313       if (vd->getStorageClass() == SC_Register &&
13314           !getLangOpts().CPlusPlus) {
13315         AddressOfError = AO_Register_Variable;
13316       }
13317     } else if (isa<MSPropertyDecl>(dcl)) {
13318       AddressOfError = AO_Property_Expansion;
13319     } else if (isa<FunctionTemplateDecl>(dcl)) {
13320       return Context.OverloadTy;
13321     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13322       // Okay: we can take the address of a field.
13323       // Could be a pointer to member, though, if there is an explicit
13324       // scope qualifier for the class.
13325       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13326         DeclContext *Ctx = dcl->getDeclContext();
13327         if (Ctx && Ctx->isRecord()) {
13328           if (dcl->getType()->isReferenceType()) {
13329             Diag(OpLoc,
13330                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13331               << dcl->getDeclName() << dcl->getType();
13332             return QualType();
13333           }
13334 
13335           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13336             Ctx = Ctx->getParent();
13337 
13338           QualType MPTy = Context.getMemberPointerType(
13339               op->getType(),
13340               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13341           // Under the MS ABI, lock down the inheritance model now.
13342           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13343             (void)isCompleteType(OpLoc, MPTy);
13344           return MPTy;
13345         }
13346       }
13347     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13348                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13349       llvm_unreachable("Unknown/unexpected decl type");
13350   }
13351 
13352   if (AddressOfError != AO_No_Error) {
13353     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13354     return QualType();
13355   }
13356 
13357   if (lval == Expr::LV_IncompleteVoidType) {
13358     // Taking the address of a void variable is technically illegal, but we
13359     // allow it in cases which are otherwise valid.
13360     // Example: "extern void x; void* y = &x;".
13361     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13362   }
13363 
13364   // If the operand has type "type", the result has type "pointer to type".
13365   if (op->getType()->isObjCObjectType())
13366     return Context.getObjCObjectPointerType(op->getType());
13367 
13368   CheckAddressOfPackedMember(op);
13369 
13370   return Context.getPointerType(op->getType());
13371 }
13372 
13373 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13374   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13375   if (!DRE)
13376     return;
13377   const Decl *D = DRE->getDecl();
13378   if (!D)
13379     return;
13380   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13381   if (!Param)
13382     return;
13383   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13384     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13385       return;
13386   if (FunctionScopeInfo *FD = S.getCurFunction())
13387     if (!FD->ModifiedNonNullParams.count(Param))
13388       FD->ModifiedNonNullParams.insert(Param);
13389 }
13390 
13391 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13392 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13393                                         SourceLocation OpLoc) {
13394   if (Op->isTypeDependent())
13395     return S.Context.DependentTy;
13396 
13397   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13398   if (ConvResult.isInvalid())
13399     return QualType();
13400   Op = ConvResult.get();
13401   QualType OpTy = Op->getType();
13402   QualType Result;
13403 
13404   if (isa<CXXReinterpretCastExpr>(Op)) {
13405     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13406     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13407                                      Op->getSourceRange());
13408   }
13409 
13410   if (const PointerType *PT = OpTy->getAs<PointerType>())
13411   {
13412     Result = PT->getPointeeType();
13413   }
13414   else if (const ObjCObjectPointerType *OPT =
13415              OpTy->getAs<ObjCObjectPointerType>())
13416     Result = OPT->getPointeeType();
13417   else {
13418     ExprResult PR = S.CheckPlaceholderExpr(Op);
13419     if (PR.isInvalid()) return QualType();
13420     if (PR.get() != Op)
13421       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13422   }
13423 
13424   if (Result.isNull()) {
13425     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13426       << OpTy << Op->getSourceRange();
13427     return QualType();
13428   }
13429 
13430   // Note that per both C89 and C99, indirection is always legal, even if Result
13431   // is an incomplete type or void.  It would be possible to warn about
13432   // dereferencing a void pointer, but it's completely well-defined, and such a
13433   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13434   // for pointers to 'void' but is fine for any other pointer type:
13435   //
13436   // C++ [expr.unary.op]p1:
13437   //   [...] the expression to which [the unary * operator] is applied shall
13438   //   be a pointer to an object type, or a pointer to a function type
13439   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13440     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13441       << OpTy << Op->getSourceRange();
13442 
13443   // Dereferences are usually l-values...
13444   VK = VK_LValue;
13445 
13446   // ...except that certain expressions are never l-values in C.
13447   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13448     VK = VK_RValue;
13449 
13450   return Result;
13451 }
13452 
13453 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13454   BinaryOperatorKind Opc;
13455   switch (Kind) {
13456   default: llvm_unreachable("Unknown binop!");
13457   case tok::periodstar:           Opc = BO_PtrMemD; break;
13458   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13459   case tok::star:                 Opc = BO_Mul; break;
13460   case tok::slash:                Opc = BO_Div; break;
13461   case tok::percent:              Opc = BO_Rem; break;
13462   case tok::plus:                 Opc = BO_Add; break;
13463   case tok::minus:                Opc = BO_Sub; break;
13464   case tok::lessless:             Opc = BO_Shl; break;
13465   case tok::greatergreater:       Opc = BO_Shr; break;
13466   case tok::lessequal:            Opc = BO_LE; break;
13467   case tok::less:                 Opc = BO_LT; break;
13468   case tok::greaterequal:         Opc = BO_GE; break;
13469   case tok::greater:              Opc = BO_GT; break;
13470   case tok::exclaimequal:         Opc = BO_NE; break;
13471   case tok::equalequal:           Opc = BO_EQ; break;
13472   case tok::spaceship:            Opc = BO_Cmp; break;
13473   case tok::amp:                  Opc = BO_And; break;
13474   case tok::caret:                Opc = BO_Xor; break;
13475   case tok::pipe:                 Opc = BO_Or; break;
13476   case tok::ampamp:               Opc = BO_LAnd; break;
13477   case tok::pipepipe:             Opc = BO_LOr; break;
13478   case tok::equal:                Opc = BO_Assign; break;
13479   case tok::starequal:            Opc = BO_MulAssign; break;
13480   case tok::slashequal:           Opc = BO_DivAssign; break;
13481   case tok::percentequal:         Opc = BO_RemAssign; break;
13482   case tok::plusequal:            Opc = BO_AddAssign; break;
13483   case tok::minusequal:           Opc = BO_SubAssign; break;
13484   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13485   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13486   case tok::ampequal:             Opc = BO_AndAssign; break;
13487   case tok::caretequal:           Opc = BO_XorAssign; break;
13488   case tok::pipeequal:            Opc = BO_OrAssign; break;
13489   case tok::comma:                Opc = BO_Comma; break;
13490   }
13491   return Opc;
13492 }
13493 
13494 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13495   tok::TokenKind Kind) {
13496   UnaryOperatorKind Opc;
13497   switch (Kind) {
13498   default: llvm_unreachable("Unknown unary op!");
13499   case tok::plusplus:     Opc = UO_PreInc; break;
13500   case tok::minusminus:   Opc = UO_PreDec; break;
13501   case tok::amp:          Opc = UO_AddrOf; break;
13502   case tok::star:         Opc = UO_Deref; break;
13503   case tok::plus:         Opc = UO_Plus; break;
13504   case tok::minus:        Opc = UO_Minus; break;
13505   case tok::tilde:        Opc = UO_Not; break;
13506   case tok::exclaim:      Opc = UO_LNot; break;
13507   case tok::kw___real:    Opc = UO_Real; break;
13508   case tok::kw___imag:    Opc = UO_Imag; break;
13509   case tok::kw___extension__: Opc = UO_Extension; break;
13510   }
13511   return Opc;
13512 }
13513 
13514 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13515 /// This warning suppressed in the event of macro expansions.
13516 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13517                                    SourceLocation OpLoc, bool IsBuiltin) {
13518   if (S.inTemplateInstantiation())
13519     return;
13520   if (S.isUnevaluatedContext())
13521     return;
13522   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13523     return;
13524   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13525   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13526   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13527   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13528   if (!LHSDeclRef || !RHSDeclRef ||
13529       LHSDeclRef->getLocation().isMacroID() ||
13530       RHSDeclRef->getLocation().isMacroID())
13531     return;
13532   const ValueDecl *LHSDecl =
13533     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13534   const ValueDecl *RHSDecl =
13535     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13536   if (LHSDecl != RHSDecl)
13537     return;
13538   if (LHSDecl->getType().isVolatileQualified())
13539     return;
13540   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13541     if (RefTy->getPointeeType().isVolatileQualified())
13542       return;
13543 
13544   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13545                           : diag::warn_self_assignment_overloaded)
13546       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13547       << RHSExpr->getSourceRange();
13548 }
13549 
13550 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13551 /// is usually indicative of introspection within the Objective-C pointer.
13552 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13553                                           SourceLocation OpLoc) {
13554   if (!S.getLangOpts().ObjC)
13555     return;
13556 
13557   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13558   const Expr *LHS = L.get();
13559   const Expr *RHS = R.get();
13560 
13561   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13562     ObjCPointerExpr = LHS;
13563     OtherExpr = RHS;
13564   }
13565   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13566     ObjCPointerExpr = RHS;
13567     OtherExpr = LHS;
13568   }
13569 
13570   // This warning is deliberately made very specific to reduce false
13571   // positives with logic that uses '&' for hashing.  This logic mainly
13572   // looks for code trying to introspect into tagged pointers, which
13573   // code should generally never do.
13574   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13575     unsigned Diag = diag::warn_objc_pointer_masking;
13576     // Determine if we are introspecting the result of performSelectorXXX.
13577     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13578     // Special case messages to -performSelector and friends, which
13579     // can return non-pointer values boxed in a pointer value.
13580     // Some clients may wish to silence warnings in this subcase.
13581     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13582       Selector S = ME->getSelector();
13583       StringRef SelArg0 = S.getNameForSlot(0);
13584       if (SelArg0.startswith("performSelector"))
13585         Diag = diag::warn_objc_pointer_masking_performSelector;
13586     }
13587 
13588     S.Diag(OpLoc, Diag)
13589       << ObjCPointerExpr->getSourceRange();
13590   }
13591 }
13592 
13593 static NamedDecl *getDeclFromExpr(Expr *E) {
13594   if (!E)
13595     return nullptr;
13596   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13597     return DRE->getDecl();
13598   if (auto *ME = dyn_cast<MemberExpr>(E))
13599     return ME->getMemberDecl();
13600   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13601     return IRE->getDecl();
13602   return nullptr;
13603 }
13604 
13605 // This helper function promotes a binary operator's operands (which are of a
13606 // half vector type) to a vector of floats and then truncates the result to
13607 // a vector of either half or short.
13608 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13609                                       BinaryOperatorKind Opc, QualType ResultTy,
13610                                       ExprValueKind VK, ExprObjectKind OK,
13611                                       bool IsCompAssign, SourceLocation OpLoc,
13612                                       FPOptionsOverride FPFeatures) {
13613   auto &Context = S.getASTContext();
13614   assert((isVector(ResultTy, Context.HalfTy) ||
13615           isVector(ResultTy, Context.ShortTy)) &&
13616          "Result must be a vector of half or short");
13617   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13618          isVector(RHS.get()->getType(), Context.HalfTy) &&
13619          "both operands expected to be a half vector");
13620 
13621   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13622   QualType BinOpResTy = RHS.get()->getType();
13623 
13624   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13625   // change BinOpResTy to a vector of ints.
13626   if (isVector(ResultTy, Context.ShortTy))
13627     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13628 
13629   if (IsCompAssign)
13630     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13631                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13632                                           BinOpResTy, BinOpResTy);
13633 
13634   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13635   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13636                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13637   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13638 }
13639 
13640 static std::pair<ExprResult, ExprResult>
13641 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13642                            Expr *RHSExpr) {
13643   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13644   if (!S.getLangOpts().CPlusPlus) {
13645     // C cannot handle TypoExpr nodes on either side of a binop because it
13646     // doesn't handle dependent types properly, so make sure any TypoExprs have
13647     // been dealt with before checking the operands.
13648     LHS = S.CorrectDelayedTyposInExpr(LHS);
13649     RHS = S.CorrectDelayedTyposInExpr(
13650         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13651         [Opc, LHS](Expr *E) {
13652           if (Opc != BO_Assign)
13653             return ExprResult(E);
13654           // Avoid correcting the RHS to the same Expr as the LHS.
13655           Decl *D = getDeclFromExpr(E);
13656           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13657         });
13658   }
13659   return std::make_pair(LHS, RHS);
13660 }
13661 
13662 /// Returns true if conversion between vectors of halfs and vectors of floats
13663 /// is needed.
13664 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13665                                      Expr *E0, Expr *E1 = nullptr) {
13666   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13667       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13668     return false;
13669 
13670   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13671     QualType Ty = E->IgnoreImplicit()->getType();
13672 
13673     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13674     // to vectors of floats. Although the element type of the vectors is __fp16,
13675     // the vectors shouldn't be treated as storage-only types. See the
13676     // discussion here: https://reviews.llvm.org/rG825235c140e7
13677     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13678       if (VT->getVectorKind() == VectorType::NeonVector)
13679         return false;
13680       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13681     }
13682     return false;
13683   };
13684 
13685   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13686 }
13687 
13688 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13689 /// operator @p Opc at location @c TokLoc. This routine only supports
13690 /// built-in operations; ActOnBinOp handles overloaded operators.
13691 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13692                                     BinaryOperatorKind Opc,
13693                                     Expr *LHSExpr, Expr *RHSExpr) {
13694   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13695     // The syntax only allows initializer lists on the RHS of assignment,
13696     // so we don't need to worry about accepting invalid code for
13697     // non-assignment operators.
13698     // C++11 5.17p9:
13699     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13700     //   of x = {} is x = T().
13701     InitializationKind Kind = InitializationKind::CreateDirectList(
13702         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13703     InitializedEntity Entity =
13704         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13705     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13706     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13707     if (Init.isInvalid())
13708       return Init;
13709     RHSExpr = Init.get();
13710   }
13711 
13712   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13713   QualType ResultTy;     // Result type of the binary operator.
13714   // The following two variables are used for compound assignment operators
13715   QualType CompLHSTy;    // Type of LHS after promotions for computation
13716   QualType CompResultTy; // Type of computation result
13717   ExprValueKind VK = VK_RValue;
13718   ExprObjectKind OK = OK_Ordinary;
13719   bool ConvertHalfVec = false;
13720 
13721   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13722   if (!LHS.isUsable() || !RHS.isUsable())
13723     return ExprError();
13724 
13725   if (getLangOpts().OpenCL) {
13726     QualType LHSTy = LHSExpr->getType();
13727     QualType RHSTy = RHSExpr->getType();
13728     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13729     // the ATOMIC_VAR_INIT macro.
13730     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13731       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13732       if (BO_Assign == Opc)
13733         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13734       else
13735         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13736       return ExprError();
13737     }
13738 
13739     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13740     // only with a builtin functions and therefore should be disallowed here.
13741     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13742         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13743         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13744         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13745       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13746       return ExprError();
13747     }
13748   }
13749 
13750   switch (Opc) {
13751   case BO_Assign:
13752     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13753     if (getLangOpts().CPlusPlus &&
13754         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13755       VK = LHS.get()->getValueKind();
13756       OK = LHS.get()->getObjectKind();
13757     }
13758     if (!ResultTy.isNull()) {
13759       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13760       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13761 
13762       // Avoid copying a block to the heap if the block is assigned to a local
13763       // auto variable that is declared in the same scope as the block. This
13764       // optimization is unsafe if the local variable is declared in an outer
13765       // scope. For example:
13766       //
13767       // BlockTy b;
13768       // {
13769       //   b = ^{...};
13770       // }
13771       // // It is unsafe to invoke the block here if it wasn't copied to the
13772       // // heap.
13773       // b();
13774 
13775       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13776         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13777           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13778             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13779               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13780 
13781       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13782         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13783                               NTCUC_Assignment, NTCUK_Copy);
13784     }
13785     RecordModifiableNonNullParam(*this, LHS.get());
13786     break;
13787   case BO_PtrMemD:
13788   case BO_PtrMemI:
13789     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13790                                             Opc == BO_PtrMemI);
13791     break;
13792   case BO_Mul:
13793   case BO_Div:
13794     ConvertHalfVec = true;
13795     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13796                                            Opc == BO_Div);
13797     break;
13798   case BO_Rem:
13799     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13800     break;
13801   case BO_Add:
13802     ConvertHalfVec = true;
13803     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13804     break;
13805   case BO_Sub:
13806     ConvertHalfVec = true;
13807     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13808     break;
13809   case BO_Shl:
13810   case BO_Shr:
13811     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13812     break;
13813   case BO_LE:
13814   case BO_LT:
13815   case BO_GE:
13816   case BO_GT:
13817     ConvertHalfVec = true;
13818     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13819     break;
13820   case BO_EQ:
13821   case BO_NE:
13822     ConvertHalfVec = true;
13823     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13824     break;
13825   case BO_Cmp:
13826     ConvertHalfVec = true;
13827     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13828     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13829     break;
13830   case BO_And:
13831     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13832     LLVM_FALLTHROUGH;
13833   case BO_Xor:
13834   case BO_Or:
13835     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13836     break;
13837   case BO_LAnd:
13838   case BO_LOr:
13839     ConvertHalfVec = true;
13840     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13841     break;
13842   case BO_MulAssign:
13843   case BO_DivAssign:
13844     ConvertHalfVec = true;
13845     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13846                                                Opc == BO_DivAssign);
13847     CompLHSTy = CompResultTy;
13848     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13849       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13850     break;
13851   case BO_RemAssign:
13852     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13853     CompLHSTy = CompResultTy;
13854     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13855       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13856     break;
13857   case BO_AddAssign:
13858     ConvertHalfVec = true;
13859     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13860     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13861       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13862     break;
13863   case BO_SubAssign:
13864     ConvertHalfVec = true;
13865     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13866     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13867       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13868     break;
13869   case BO_ShlAssign:
13870   case BO_ShrAssign:
13871     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13872     CompLHSTy = CompResultTy;
13873     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13874       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13875     break;
13876   case BO_AndAssign:
13877   case BO_OrAssign: // fallthrough
13878     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13879     LLVM_FALLTHROUGH;
13880   case BO_XorAssign:
13881     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13882     CompLHSTy = CompResultTy;
13883     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13884       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13885     break;
13886   case BO_Comma:
13887     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13888     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13889       VK = RHS.get()->getValueKind();
13890       OK = RHS.get()->getObjectKind();
13891     }
13892     break;
13893   }
13894   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13895     return ExprError();
13896 
13897   // Some of the binary operations require promoting operands of half vector to
13898   // float vectors and truncating the result back to half vector. For now, we do
13899   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13900   // arm64).
13901   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13902          isVector(LHS.get()->getType(), Context.HalfTy) &&
13903          "both sides are half vectors or neither sides are");
13904   ConvertHalfVec =
13905       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13906 
13907   // Check for array bounds violations for both sides of the BinaryOperator
13908   CheckArrayAccess(LHS.get());
13909   CheckArrayAccess(RHS.get());
13910 
13911   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13912     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13913                                                  &Context.Idents.get("object_setClass"),
13914                                                  SourceLocation(), LookupOrdinaryName);
13915     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13916       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13917       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13918           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13919                                         "object_setClass(")
13920           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13921                                           ",")
13922           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13923     }
13924     else
13925       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13926   }
13927   else if (const ObjCIvarRefExpr *OIRE =
13928            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13929     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13930 
13931   // Opc is not a compound assignment if CompResultTy is null.
13932   if (CompResultTy.isNull()) {
13933     if (ConvertHalfVec)
13934       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13935                                  OpLoc, CurFPFeatureOverrides());
13936     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13937                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13938   }
13939 
13940   // Handle compound assignments.
13941   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13942       OK_ObjCProperty) {
13943     VK = VK_LValue;
13944     OK = LHS.get()->getObjectKind();
13945   }
13946 
13947   // The LHS is not converted to the result type for fixed-point compound
13948   // assignment as the common type is computed on demand. Reset the CompLHSTy
13949   // to the LHS type we would have gotten after unary conversions.
13950   if (CompResultTy->isFixedPointType())
13951     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13952 
13953   if (ConvertHalfVec)
13954     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13955                                OpLoc, CurFPFeatureOverrides());
13956 
13957   return CompoundAssignOperator::Create(
13958       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13959       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13960 }
13961 
13962 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13963 /// operators are mixed in a way that suggests that the programmer forgot that
13964 /// comparison operators have higher precedence. The most typical example of
13965 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13966 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13967                                       SourceLocation OpLoc, Expr *LHSExpr,
13968                                       Expr *RHSExpr) {
13969   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13970   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13971 
13972   // Check that one of the sides is a comparison operator and the other isn't.
13973   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13974   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13975   if (isLeftComp == isRightComp)
13976     return;
13977 
13978   // Bitwise operations are sometimes used as eager logical ops.
13979   // Don't diagnose this.
13980   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13981   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13982   if (isLeftBitwise || isRightBitwise)
13983     return;
13984 
13985   SourceRange DiagRange = isLeftComp
13986                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13987                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13988   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13989   SourceRange ParensRange =
13990       isLeftComp
13991           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13992           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13993 
13994   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13995     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13996   SuggestParentheses(Self, OpLoc,
13997     Self.PDiag(diag::note_precedence_silence) << OpStr,
13998     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13999   SuggestParentheses(Self, OpLoc,
14000     Self.PDiag(diag::note_precedence_bitwise_first)
14001       << BinaryOperator::getOpcodeStr(Opc),
14002     ParensRange);
14003 }
14004 
14005 /// It accepts a '&&' expr that is inside a '||' one.
14006 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14007 /// in parentheses.
14008 static void
14009 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14010                                        BinaryOperator *Bop) {
14011   assert(Bop->getOpcode() == BO_LAnd);
14012   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14013       << Bop->getSourceRange() << OpLoc;
14014   SuggestParentheses(Self, Bop->getOperatorLoc(),
14015     Self.PDiag(diag::note_precedence_silence)
14016       << Bop->getOpcodeStr(),
14017     Bop->getSourceRange());
14018 }
14019 
14020 /// Returns true if the given expression can be evaluated as a constant
14021 /// 'true'.
14022 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14023   bool Res;
14024   return !E->isValueDependent() &&
14025          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14026 }
14027 
14028 /// Returns true if the given expression can be evaluated as a constant
14029 /// 'false'.
14030 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14031   bool Res;
14032   return !E->isValueDependent() &&
14033          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14034 }
14035 
14036 /// Look for '&&' in the left hand of a '||' expr.
14037 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14038                                              Expr *LHSExpr, Expr *RHSExpr) {
14039   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14040     if (Bop->getOpcode() == BO_LAnd) {
14041       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14042       if (EvaluatesAsFalse(S, RHSExpr))
14043         return;
14044       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14045       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14046         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14047     } else if (Bop->getOpcode() == BO_LOr) {
14048       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14049         // If it's "a || b && 1 || c" we didn't warn earlier for
14050         // "a || b && 1", but warn now.
14051         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14052           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14053       }
14054     }
14055   }
14056 }
14057 
14058 /// Look for '&&' in the right hand of a '||' expr.
14059 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14060                                              Expr *LHSExpr, Expr *RHSExpr) {
14061   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14062     if (Bop->getOpcode() == BO_LAnd) {
14063       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14064       if (EvaluatesAsFalse(S, LHSExpr))
14065         return;
14066       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14067       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14068         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14069     }
14070   }
14071 }
14072 
14073 /// Look for bitwise op in the left or right hand of a bitwise op with
14074 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14075 /// the '&' expression in parentheses.
14076 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14077                                          SourceLocation OpLoc, Expr *SubExpr) {
14078   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14079     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14080       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14081         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14082         << Bop->getSourceRange() << OpLoc;
14083       SuggestParentheses(S, Bop->getOperatorLoc(),
14084         S.PDiag(diag::note_precedence_silence)
14085           << Bop->getOpcodeStr(),
14086         Bop->getSourceRange());
14087     }
14088   }
14089 }
14090 
14091 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14092                                     Expr *SubExpr, StringRef Shift) {
14093   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14094     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14095       StringRef Op = Bop->getOpcodeStr();
14096       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14097           << Bop->getSourceRange() << OpLoc << Shift << Op;
14098       SuggestParentheses(S, Bop->getOperatorLoc(),
14099           S.PDiag(diag::note_precedence_silence) << Op,
14100           Bop->getSourceRange());
14101     }
14102   }
14103 }
14104 
14105 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14106                                  Expr *LHSExpr, Expr *RHSExpr) {
14107   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14108   if (!OCE)
14109     return;
14110 
14111   FunctionDecl *FD = OCE->getDirectCallee();
14112   if (!FD || !FD->isOverloadedOperator())
14113     return;
14114 
14115   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14116   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14117     return;
14118 
14119   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14120       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14121       << (Kind == OO_LessLess);
14122   SuggestParentheses(S, OCE->getOperatorLoc(),
14123                      S.PDiag(diag::note_precedence_silence)
14124                          << (Kind == OO_LessLess ? "<<" : ">>"),
14125                      OCE->getSourceRange());
14126   SuggestParentheses(
14127       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14128       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14129 }
14130 
14131 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14132 /// precedence.
14133 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14134                                     SourceLocation OpLoc, Expr *LHSExpr,
14135                                     Expr *RHSExpr){
14136   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14137   if (BinaryOperator::isBitwiseOp(Opc))
14138     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14139 
14140   // Diagnose "arg1 & arg2 | arg3"
14141   if ((Opc == BO_Or || Opc == BO_Xor) &&
14142       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14143     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14144     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14145   }
14146 
14147   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14148   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14149   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14150     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14151     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14152   }
14153 
14154   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14155       || Opc == BO_Shr) {
14156     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14157     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14158     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14159   }
14160 
14161   // Warn on overloaded shift operators and comparisons, such as:
14162   // cout << 5 == 4;
14163   if (BinaryOperator::isComparisonOp(Opc))
14164     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14165 }
14166 
14167 // Binary Operators.  'Tok' is the token for the operator.
14168 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14169                             tok::TokenKind Kind,
14170                             Expr *LHSExpr, Expr *RHSExpr) {
14171   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14172   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14173   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14174 
14175   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14176   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14177 
14178   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14179 }
14180 
14181 /// Build an overloaded binary operator expression in the given scope.
14182 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14183                                        BinaryOperatorKind Opc,
14184                                        Expr *LHS, Expr *RHS) {
14185   switch (Opc) {
14186   case BO_Assign:
14187   case BO_DivAssign:
14188   case BO_RemAssign:
14189   case BO_SubAssign:
14190   case BO_AndAssign:
14191   case BO_OrAssign:
14192   case BO_XorAssign:
14193     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14194     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14195     break;
14196   default:
14197     break;
14198   }
14199 
14200   // Find all of the overloaded operators visible from this
14201   // point. We perform both an operator-name lookup from the local
14202   // scope and an argument-dependent lookup based on the types of
14203   // the arguments.
14204   UnresolvedSet<16> Functions;
14205   OverloadedOperatorKind OverOp
14206     = BinaryOperator::getOverloadedOperator(Opc);
14207   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14208     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14209                                    RHS->getType(), Functions);
14210 
14211   // In C++20 onwards, we may have a second operator to look up.
14212   if (S.getLangOpts().CPlusPlus20) {
14213     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14214       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14215                                      RHS->getType(), Functions);
14216   }
14217 
14218   // Build the (potentially-overloaded, potentially-dependent)
14219   // binary operation.
14220   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14221 }
14222 
14223 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14224                             BinaryOperatorKind Opc,
14225                             Expr *LHSExpr, Expr *RHSExpr) {
14226   ExprResult LHS, RHS;
14227   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14228   if (!LHS.isUsable() || !RHS.isUsable())
14229     return ExprError();
14230   LHSExpr = LHS.get();
14231   RHSExpr = RHS.get();
14232 
14233   // We want to end up calling one of checkPseudoObjectAssignment
14234   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14235   // both expressions are overloadable or either is type-dependent),
14236   // or CreateBuiltinBinOp (in any other case).  We also want to get
14237   // any placeholder types out of the way.
14238 
14239   // Handle pseudo-objects in the LHS.
14240   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14241     // Assignments with a pseudo-object l-value need special analysis.
14242     if (pty->getKind() == BuiltinType::PseudoObject &&
14243         BinaryOperator::isAssignmentOp(Opc))
14244       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14245 
14246     // Don't resolve overloads if the other type is overloadable.
14247     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14248       // We can't actually test that if we still have a placeholder,
14249       // though.  Fortunately, none of the exceptions we see in that
14250       // code below are valid when the LHS is an overload set.  Note
14251       // that an overload set can be dependently-typed, but it never
14252       // instantiates to having an overloadable type.
14253       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14254       if (resolvedRHS.isInvalid()) return ExprError();
14255       RHSExpr = resolvedRHS.get();
14256 
14257       if (RHSExpr->isTypeDependent() ||
14258           RHSExpr->getType()->isOverloadableType())
14259         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14260     }
14261 
14262     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14263     // template, diagnose the missing 'template' keyword instead of diagnosing
14264     // an invalid use of a bound member function.
14265     //
14266     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14267     // to C++1z [over.over]/1.4, but we already checked for that case above.
14268     if (Opc == BO_LT && inTemplateInstantiation() &&
14269         (pty->getKind() == BuiltinType::BoundMember ||
14270          pty->getKind() == BuiltinType::Overload)) {
14271       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14272       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14273           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14274             return isa<FunctionTemplateDecl>(ND);
14275           })) {
14276         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14277                                 : OE->getNameLoc(),
14278              diag::err_template_kw_missing)
14279           << OE->getName().getAsString() << "";
14280         return ExprError();
14281       }
14282     }
14283 
14284     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14285     if (LHS.isInvalid()) return ExprError();
14286     LHSExpr = LHS.get();
14287   }
14288 
14289   // Handle pseudo-objects in the RHS.
14290   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14291     // An overload in the RHS can potentially be resolved by the type
14292     // being assigned to.
14293     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14294       if (getLangOpts().CPlusPlus &&
14295           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14296            LHSExpr->getType()->isOverloadableType()))
14297         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14298 
14299       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14300     }
14301 
14302     // Don't resolve overloads if the other type is overloadable.
14303     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14304         LHSExpr->getType()->isOverloadableType())
14305       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14306 
14307     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14308     if (!resolvedRHS.isUsable()) return ExprError();
14309     RHSExpr = resolvedRHS.get();
14310   }
14311 
14312   if (getLangOpts().CPlusPlus) {
14313     // If either expression is type-dependent, always build an
14314     // overloaded op.
14315     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14316       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14317 
14318     // Otherwise, build an overloaded op if either expression has an
14319     // overloadable type.
14320     if (LHSExpr->getType()->isOverloadableType() ||
14321         RHSExpr->getType()->isOverloadableType())
14322       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14323   }
14324 
14325   // Build a built-in binary operation.
14326   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14327 }
14328 
14329 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14330   if (T.isNull() || T->isDependentType())
14331     return false;
14332 
14333   if (!T->isPromotableIntegerType())
14334     return true;
14335 
14336   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14337 }
14338 
14339 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14340                                       UnaryOperatorKind Opc,
14341                                       Expr *InputExpr) {
14342   ExprResult Input = InputExpr;
14343   ExprValueKind VK = VK_RValue;
14344   ExprObjectKind OK = OK_Ordinary;
14345   QualType resultType;
14346   bool CanOverflow = false;
14347 
14348   bool ConvertHalfVec = false;
14349   if (getLangOpts().OpenCL) {
14350     QualType Ty = InputExpr->getType();
14351     // The only legal unary operation for atomics is '&'.
14352     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14353     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14354     // only with a builtin functions and therefore should be disallowed here.
14355         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14356         || Ty->isBlockPointerType())) {
14357       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14358                        << InputExpr->getType()
14359                        << Input.get()->getSourceRange());
14360     }
14361   }
14362 
14363   switch (Opc) {
14364   case UO_PreInc:
14365   case UO_PreDec:
14366   case UO_PostInc:
14367   case UO_PostDec:
14368     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14369                                                 OpLoc,
14370                                                 Opc == UO_PreInc ||
14371                                                 Opc == UO_PostInc,
14372                                                 Opc == UO_PreInc ||
14373                                                 Opc == UO_PreDec);
14374     CanOverflow = isOverflowingIntegerType(Context, resultType);
14375     break;
14376   case UO_AddrOf:
14377     resultType = CheckAddressOfOperand(Input, OpLoc);
14378     CheckAddressOfNoDeref(InputExpr);
14379     RecordModifiableNonNullParam(*this, InputExpr);
14380     break;
14381   case UO_Deref: {
14382     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14383     if (Input.isInvalid()) return ExprError();
14384     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14385     break;
14386   }
14387   case UO_Plus:
14388   case UO_Minus:
14389     CanOverflow = Opc == UO_Minus &&
14390                   isOverflowingIntegerType(Context, Input.get()->getType());
14391     Input = UsualUnaryConversions(Input.get());
14392     if (Input.isInvalid()) return ExprError();
14393     // Unary plus and minus require promoting an operand of half vector to a
14394     // float vector and truncating the result back to a half vector. For now, we
14395     // do this only when HalfArgsAndReturns is set (that is, when the target is
14396     // arm or arm64).
14397     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14398 
14399     // If the operand is a half vector, promote it to a float vector.
14400     if (ConvertHalfVec)
14401       Input = convertVector(Input.get(), Context.FloatTy, *this);
14402     resultType = Input.get()->getType();
14403     if (resultType->isDependentType())
14404       break;
14405     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14406       break;
14407     else if (resultType->isVectorType() &&
14408              // The z vector extensions don't allow + or - with bool vectors.
14409              (!Context.getLangOpts().ZVector ||
14410               resultType->castAs<VectorType>()->getVectorKind() !=
14411               VectorType::AltiVecBool))
14412       break;
14413     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14414              Opc == UO_Plus &&
14415              resultType->isPointerType())
14416       break;
14417 
14418     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14419       << resultType << Input.get()->getSourceRange());
14420 
14421   case UO_Not: // bitwise complement
14422     Input = UsualUnaryConversions(Input.get());
14423     if (Input.isInvalid())
14424       return ExprError();
14425     resultType = Input.get()->getType();
14426     if (resultType->isDependentType())
14427       break;
14428     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14429     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14430       // C99 does not support '~' for complex conjugation.
14431       Diag(OpLoc, diag::ext_integer_complement_complex)
14432           << resultType << Input.get()->getSourceRange();
14433     else if (resultType->hasIntegerRepresentation())
14434       break;
14435     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14436       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14437       // on vector float types.
14438       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14439       if (!T->isIntegerType())
14440         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14441                           << resultType << Input.get()->getSourceRange());
14442     } else {
14443       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14444                        << resultType << Input.get()->getSourceRange());
14445     }
14446     break;
14447 
14448   case UO_LNot: // logical negation
14449     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14450     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14451     if (Input.isInvalid()) return ExprError();
14452     resultType = Input.get()->getType();
14453 
14454     // Though we still have to promote half FP to float...
14455     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14456       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14457       resultType = Context.FloatTy;
14458     }
14459 
14460     if (resultType->isDependentType())
14461       break;
14462     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14463       // C99 6.5.3.3p1: ok, fallthrough;
14464       if (Context.getLangOpts().CPlusPlus) {
14465         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14466         // operand contextually converted to bool.
14467         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14468                                   ScalarTypeToBooleanCastKind(resultType));
14469       } else if (Context.getLangOpts().OpenCL &&
14470                  Context.getLangOpts().OpenCLVersion < 120) {
14471         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14472         // operate on scalar float types.
14473         if (!resultType->isIntegerType() && !resultType->isPointerType())
14474           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14475                            << resultType << Input.get()->getSourceRange());
14476       }
14477     } else if (resultType->isExtVectorType()) {
14478       if (Context.getLangOpts().OpenCL &&
14479           Context.getLangOpts().OpenCLVersion < 120 &&
14480           !Context.getLangOpts().OpenCLCPlusPlus) {
14481         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14482         // operate on vector float types.
14483         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14484         if (!T->isIntegerType())
14485           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14486                            << resultType << Input.get()->getSourceRange());
14487       }
14488       // Vector logical not returns the signed variant of the operand type.
14489       resultType = GetSignedVectorType(resultType);
14490       break;
14491     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14492       const VectorType *VTy = resultType->castAs<VectorType>();
14493       if (VTy->getVectorKind() != VectorType::GenericVector)
14494         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14495                          << resultType << Input.get()->getSourceRange());
14496 
14497       // Vector logical not returns the signed variant of the operand type.
14498       resultType = GetSignedVectorType(resultType);
14499       break;
14500     } else {
14501       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14502         << resultType << Input.get()->getSourceRange());
14503     }
14504 
14505     // LNot always has type int. C99 6.5.3.3p5.
14506     // In C++, it's bool. C++ 5.3.1p8
14507     resultType = Context.getLogicalOperationType();
14508     break;
14509   case UO_Real:
14510   case UO_Imag:
14511     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14512     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14513     // complex l-values to ordinary l-values and all other values to r-values.
14514     if (Input.isInvalid()) return ExprError();
14515     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14516       if (Input.get()->getValueKind() != VK_RValue &&
14517           Input.get()->getObjectKind() == OK_Ordinary)
14518         VK = Input.get()->getValueKind();
14519     } else if (!getLangOpts().CPlusPlus) {
14520       // In C, a volatile scalar is read by __imag. In C++, it is not.
14521       Input = DefaultLvalueConversion(Input.get());
14522     }
14523     break;
14524   case UO_Extension:
14525     resultType = Input.get()->getType();
14526     VK = Input.get()->getValueKind();
14527     OK = Input.get()->getObjectKind();
14528     break;
14529   case UO_Coawait:
14530     // It's unnecessary to represent the pass-through operator co_await in the
14531     // AST; just return the input expression instead.
14532     assert(!Input.get()->getType()->isDependentType() &&
14533                    "the co_await expression must be non-dependant before "
14534                    "building operator co_await");
14535     return Input;
14536   }
14537   if (resultType.isNull() || Input.isInvalid())
14538     return ExprError();
14539 
14540   // Check for array bounds violations in the operand of the UnaryOperator,
14541   // except for the '*' and '&' operators that have to be handled specially
14542   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14543   // that are explicitly defined as valid by the standard).
14544   if (Opc != UO_AddrOf && Opc != UO_Deref)
14545     CheckArrayAccess(Input.get());
14546 
14547   auto *UO =
14548       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14549                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14550 
14551   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14552       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14553     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14554 
14555   // Convert the result back to a half vector.
14556   if (ConvertHalfVec)
14557     return convertVector(UO, Context.HalfTy, *this);
14558   return UO;
14559 }
14560 
14561 /// Determine whether the given expression is a qualified member
14562 /// access expression, of a form that could be turned into a pointer to member
14563 /// with the address-of operator.
14564 bool Sema::isQualifiedMemberAccess(Expr *E) {
14565   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14566     if (!DRE->getQualifier())
14567       return false;
14568 
14569     ValueDecl *VD = DRE->getDecl();
14570     if (!VD->isCXXClassMember())
14571       return false;
14572 
14573     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14574       return true;
14575     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14576       return Method->isInstance();
14577 
14578     return false;
14579   }
14580 
14581   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14582     if (!ULE->getQualifier())
14583       return false;
14584 
14585     for (NamedDecl *D : ULE->decls()) {
14586       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14587         if (Method->isInstance())
14588           return true;
14589       } else {
14590         // Overload set does not contain methods.
14591         break;
14592       }
14593     }
14594 
14595     return false;
14596   }
14597 
14598   return false;
14599 }
14600 
14601 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14602                               UnaryOperatorKind Opc, Expr *Input) {
14603   // First things first: handle placeholders so that the
14604   // overloaded-operator check considers the right type.
14605   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14606     // Increment and decrement of pseudo-object references.
14607     if (pty->getKind() == BuiltinType::PseudoObject &&
14608         UnaryOperator::isIncrementDecrementOp(Opc))
14609       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14610 
14611     // extension is always a builtin operator.
14612     if (Opc == UO_Extension)
14613       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14614 
14615     // & gets special logic for several kinds of placeholder.
14616     // The builtin code knows what to do.
14617     if (Opc == UO_AddrOf &&
14618         (pty->getKind() == BuiltinType::Overload ||
14619          pty->getKind() == BuiltinType::UnknownAny ||
14620          pty->getKind() == BuiltinType::BoundMember))
14621       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14622 
14623     // Anything else needs to be handled now.
14624     ExprResult Result = CheckPlaceholderExpr(Input);
14625     if (Result.isInvalid()) return ExprError();
14626     Input = Result.get();
14627   }
14628 
14629   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14630       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14631       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14632     // Find all of the overloaded operators visible from this
14633     // point. We perform both an operator-name lookup from the local
14634     // scope and an argument-dependent lookup based on the types of
14635     // the arguments.
14636     UnresolvedSet<16> Functions;
14637     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14638     if (S && OverOp != OO_None)
14639       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14640                                    Functions);
14641 
14642     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14643   }
14644 
14645   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14646 }
14647 
14648 // Unary Operators.  'Tok' is the token for the operator.
14649 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14650                               tok::TokenKind Op, Expr *Input) {
14651   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14652 }
14653 
14654 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14655 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14656                                 LabelDecl *TheDecl) {
14657   TheDecl->markUsed(Context);
14658   // Create the AST node.  The address of a label always has type 'void*'.
14659   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14660                                      Context.getPointerType(Context.VoidTy));
14661 }
14662 
14663 void Sema::ActOnStartStmtExpr() {
14664   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14665 }
14666 
14667 void Sema::ActOnStmtExprError() {
14668   // Note that function is also called by TreeTransform when leaving a
14669   // StmtExpr scope without rebuilding anything.
14670 
14671   DiscardCleanupsInEvaluationContext();
14672   PopExpressionEvaluationContext();
14673 }
14674 
14675 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14676                                SourceLocation RPLoc) {
14677   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14678 }
14679 
14680 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14681                                SourceLocation RPLoc, unsigned TemplateDepth) {
14682   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14683   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14684 
14685   if (hasAnyUnrecoverableErrorsInThisFunction())
14686     DiscardCleanupsInEvaluationContext();
14687   assert(!Cleanup.exprNeedsCleanups() &&
14688          "cleanups within StmtExpr not correctly bound!");
14689   PopExpressionEvaluationContext();
14690 
14691   // FIXME: there are a variety of strange constraints to enforce here, for
14692   // example, it is not possible to goto into a stmt expression apparently.
14693   // More semantic analysis is needed.
14694 
14695   // If there are sub-stmts in the compound stmt, take the type of the last one
14696   // as the type of the stmtexpr.
14697   QualType Ty = Context.VoidTy;
14698   bool StmtExprMayBindToTemp = false;
14699   if (!Compound->body_empty()) {
14700     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14701     if (const auto *LastStmt =
14702             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14703       if (const Expr *Value = LastStmt->getExprStmt()) {
14704         StmtExprMayBindToTemp = true;
14705         Ty = Value->getType();
14706       }
14707     }
14708   }
14709 
14710   // FIXME: Check that expression type is complete/non-abstract; statement
14711   // expressions are not lvalues.
14712   Expr *ResStmtExpr =
14713       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14714   if (StmtExprMayBindToTemp)
14715     return MaybeBindToTemporary(ResStmtExpr);
14716   return ResStmtExpr;
14717 }
14718 
14719 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14720   if (ER.isInvalid())
14721     return ExprError();
14722 
14723   // Do function/array conversion on the last expression, but not
14724   // lvalue-to-rvalue.  However, initialize an unqualified type.
14725   ER = DefaultFunctionArrayConversion(ER.get());
14726   if (ER.isInvalid())
14727     return ExprError();
14728   Expr *E = ER.get();
14729 
14730   if (E->isTypeDependent())
14731     return E;
14732 
14733   // In ARC, if the final expression ends in a consume, splice
14734   // the consume out and bind it later.  In the alternate case
14735   // (when dealing with a retainable type), the result
14736   // initialization will create a produce.  In both cases the
14737   // result will be +1, and we'll need to balance that out with
14738   // a bind.
14739   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14740   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14741     return Cast->getSubExpr();
14742 
14743   // FIXME: Provide a better location for the initialization.
14744   return PerformCopyInitialization(
14745       InitializedEntity::InitializeStmtExprResult(
14746           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14747       SourceLocation(), E);
14748 }
14749 
14750 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14751                                       TypeSourceInfo *TInfo,
14752                                       ArrayRef<OffsetOfComponent> Components,
14753                                       SourceLocation RParenLoc) {
14754   QualType ArgTy = TInfo->getType();
14755   bool Dependent = ArgTy->isDependentType();
14756   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14757 
14758   // We must have at least one component that refers to the type, and the first
14759   // one is known to be a field designator.  Verify that the ArgTy represents
14760   // a struct/union/class.
14761   if (!Dependent && !ArgTy->isRecordType())
14762     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14763                        << ArgTy << TypeRange);
14764 
14765   // Type must be complete per C99 7.17p3 because a declaring a variable
14766   // with an incomplete type would be ill-formed.
14767   if (!Dependent
14768       && RequireCompleteType(BuiltinLoc, ArgTy,
14769                              diag::err_offsetof_incomplete_type, TypeRange))
14770     return ExprError();
14771 
14772   bool DidWarnAboutNonPOD = false;
14773   QualType CurrentType = ArgTy;
14774   SmallVector<OffsetOfNode, 4> Comps;
14775   SmallVector<Expr*, 4> Exprs;
14776   for (const OffsetOfComponent &OC : Components) {
14777     if (OC.isBrackets) {
14778       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14779       if (!CurrentType->isDependentType()) {
14780         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14781         if(!AT)
14782           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14783                            << CurrentType);
14784         CurrentType = AT->getElementType();
14785       } else
14786         CurrentType = Context.DependentTy;
14787 
14788       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14789       if (IdxRval.isInvalid())
14790         return ExprError();
14791       Expr *Idx = IdxRval.get();
14792 
14793       // The expression must be an integral expression.
14794       // FIXME: An integral constant expression?
14795       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14796           !Idx->getType()->isIntegerType())
14797         return ExprError(
14798             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14799             << Idx->getSourceRange());
14800 
14801       // Record this array index.
14802       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14803       Exprs.push_back(Idx);
14804       continue;
14805     }
14806 
14807     // Offset of a field.
14808     if (CurrentType->isDependentType()) {
14809       // We have the offset of a field, but we can't look into the dependent
14810       // type. Just record the identifier of the field.
14811       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14812       CurrentType = Context.DependentTy;
14813       continue;
14814     }
14815 
14816     // We need to have a complete type to look into.
14817     if (RequireCompleteType(OC.LocStart, CurrentType,
14818                             diag::err_offsetof_incomplete_type))
14819       return ExprError();
14820 
14821     // Look for the designated field.
14822     const RecordType *RC = CurrentType->getAs<RecordType>();
14823     if (!RC)
14824       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14825                        << CurrentType);
14826     RecordDecl *RD = RC->getDecl();
14827 
14828     // C++ [lib.support.types]p5:
14829     //   The macro offsetof accepts a restricted set of type arguments in this
14830     //   International Standard. type shall be a POD structure or a POD union
14831     //   (clause 9).
14832     // C++11 [support.types]p4:
14833     //   If type is not a standard-layout class (Clause 9), the results are
14834     //   undefined.
14835     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14836       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14837       unsigned DiagID =
14838         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14839                             : diag::ext_offsetof_non_pod_type;
14840 
14841       if (!IsSafe && !DidWarnAboutNonPOD &&
14842           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14843                               PDiag(DiagID)
14844                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14845                               << CurrentType))
14846         DidWarnAboutNonPOD = true;
14847     }
14848 
14849     // Look for the field.
14850     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14851     LookupQualifiedName(R, RD);
14852     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14853     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14854     if (!MemberDecl) {
14855       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14856         MemberDecl = IndirectMemberDecl->getAnonField();
14857     }
14858 
14859     if (!MemberDecl)
14860       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14861                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14862                                                               OC.LocEnd));
14863 
14864     // C99 7.17p3:
14865     //   (If the specified member is a bit-field, the behavior is undefined.)
14866     //
14867     // We diagnose this as an error.
14868     if (MemberDecl->isBitField()) {
14869       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14870         << MemberDecl->getDeclName()
14871         << SourceRange(BuiltinLoc, RParenLoc);
14872       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14873       return ExprError();
14874     }
14875 
14876     RecordDecl *Parent = MemberDecl->getParent();
14877     if (IndirectMemberDecl)
14878       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14879 
14880     // If the member was found in a base class, introduce OffsetOfNodes for
14881     // the base class indirections.
14882     CXXBasePaths Paths;
14883     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14884                       Paths)) {
14885       if (Paths.getDetectedVirtual()) {
14886         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14887           << MemberDecl->getDeclName()
14888           << SourceRange(BuiltinLoc, RParenLoc);
14889         return ExprError();
14890       }
14891 
14892       CXXBasePath &Path = Paths.front();
14893       for (const CXXBasePathElement &B : Path)
14894         Comps.push_back(OffsetOfNode(B.Base));
14895     }
14896 
14897     if (IndirectMemberDecl) {
14898       for (auto *FI : IndirectMemberDecl->chain()) {
14899         assert(isa<FieldDecl>(FI));
14900         Comps.push_back(OffsetOfNode(OC.LocStart,
14901                                      cast<FieldDecl>(FI), OC.LocEnd));
14902       }
14903     } else
14904       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14905 
14906     CurrentType = MemberDecl->getType().getNonReferenceType();
14907   }
14908 
14909   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14910                               Comps, Exprs, RParenLoc);
14911 }
14912 
14913 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14914                                       SourceLocation BuiltinLoc,
14915                                       SourceLocation TypeLoc,
14916                                       ParsedType ParsedArgTy,
14917                                       ArrayRef<OffsetOfComponent> Components,
14918                                       SourceLocation RParenLoc) {
14919 
14920   TypeSourceInfo *ArgTInfo;
14921   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14922   if (ArgTy.isNull())
14923     return ExprError();
14924 
14925   if (!ArgTInfo)
14926     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14927 
14928   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14929 }
14930 
14931 
14932 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14933                                  Expr *CondExpr,
14934                                  Expr *LHSExpr, Expr *RHSExpr,
14935                                  SourceLocation RPLoc) {
14936   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14937 
14938   ExprValueKind VK = VK_RValue;
14939   ExprObjectKind OK = OK_Ordinary;
14940   QualType resType;
14941   bool CondIsTrue = false;
14942   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14943     resType = Context.DependentTy;
14944   } else {
14945     // The conditional expression is required to be a constant expression.
14946     llvm::APSInt condEval(32);
14947     ExprResult CondICE
14948       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14949           diag::err_typecheck_choose_expr_requires_constant, false);
14950     if (CondICE.isInvalid())
14951       return ExprError();
14952     CondExpr = CondICE.get();
14953     CondIsTrue = condEval.getZExtValue();
14954 
14955     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14956     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14957 
14958     resType = ActiveExpr->getType();
14959     VK = ActiveExpr->getValueKind();
14960     OK = ActiveExpr->getObjectKind();
14961   }
14962 
14963   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14964                                   resType, VK, OK, RPLoc, CondIsTrue);
14965 }
14966 
14967 //===----------------------------------------------------------------------===//
14968 // Clang Extensions.
14969 //===----------------------------------------------------------------------===//
14970 
14971 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14972 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14973   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14974 
14975   if (LangOpts.CPlusPlus) {
14976     MangleNumberingContext *MCtx;
14977     Decl *ManglingContextDecl;
14978     std::tie(MCtx, ManglingContextDecl) =
14979         getCurrentMangleNumberContext(Block->getDeclContext());
14980     if (MCtx) {
14981       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14982       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14983     }
14984   }
14985 
14986   PushBlockScope(CurScope, Block);
14987   CurContext->addDecl(Block);
14988   if (CurScope)
14989     PushDeclContext(CurScope, Block);
14990   else
14991     CurContext = Block;
14992 
14993   getCurBlock()->HasImplicitReturnType = true;
14994 
14995   // Enter a new evaluation context to insulate the block from any
14996   // cleanups from the enclosing full-expression.
14997   PushExpressionEvaluationContext(
14998       ExpressionEvaluationContext::PotentiallyEvaluated);
14999 }
15000 
15001 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15002                                Scope *CurScope) {
15003   assert(ParamInfo.getIdentifier() == nullptr &&
15004          "block-id should have no identifier!");
15005   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15006   BlockScopeInfo *CurBlock = getCurBlock();
15007 
15008   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15009   QualType T = Sig->getType();
15010 
15011   // FIXME: We should allow unexpanded parameter packs here, but that would,
15012   // in turn, make the block expression contain unexpanded parameter packs.
15013   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15014     // Drop the parameters.
15015     FunctionProtoType::ExtProtoInfo EPI;
15016     EPI.HasTrailingReturn = false;
15017     EPI.TypeQuals.addConst();
15018     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15019     Sig = Context.getTrivialTypeSourceInfo(T);
15020   }
15021 
15022   // GetTypeForDeclarator always produces a function type for a block
15023   // literal signature.  Furthermore, it is always a FunctionProtoType
15024   // unless the function was written with a typedef.
15025   assert(T->isFunctionType() &&
15026          "GetTypeForDeclarator made a non-function block signature");
15027 
15028   // Look for an explicit signature in that function type.
15029   FunctionProtoTypeLoc ExplicitSignature;
15030 
15031   if ((ExplicitSignature = Sig->getTypeLoc()
15032                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15033 
15034     // Check whether that explicit signature was synthesized by
15035     // GetTypeForDeclarator.  If so, don't save that as part of the
15036     // written signature.
15037     if (ExplicitSignature.getLocalRangeBegin() ==
15038         ExplicitSignature.getLocalRangeEnd()) {
15039       // This would be much cheaper if we stored TypeLocs instead of
15040       // TypeSourceInfos.
15041       TypeLoc Result = ExplicitSignature.getReturnLoc();
15042       unsigned Size = Result.getFullDataSize();
15043       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15044       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15045 
15046       ExplicitSignature = FunctionProtoTypeLoc();
15047     }
15048   }
15049 
15050   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15051   CurBlock->FunctionType = T;
15052 
15053   const FunctionType *Fn = T->getAs<FunctionType>();
15054   QualType RetTy = Fn->getReturnType();
15055   bool isVariadic =
15056     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15057 
15058   CurBlock->TheDecl->setIsVariadic(isVariadic);
15059 
15060   // Context.DependentTy is used as a placeholder for a missing block
15061   // return type.  TODO:  what should we do with declarators like:
15062   //   ^ * { ... }
15063   // If the answer is "apply template argument deduction"....
15064   if (RetTy != Context.DependentTy) {
15065     CurBlock->ReturnType = RetTy;
15066     CurBlock->TheDecl->setBlockMissingReturnType(false);
15067     CurBlock->HasImplicitReturnType = false;
15068   }
15069 
15070   // Push block parameters from the declarator if we had them.
15071   SmallVector<ParmVarDecl*, 8> Params;
15072   if (ExplicitSignature) {
15073     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15074       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15075       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15076           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15077         // Diagnose this as an extension in C17 and earlier.
15078         if (!getLangOpts().C2x)
15079           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15080       }
15081       Params.push_back(Param);
15082     }
15083 
15084   // Fake up parameter variables if we have a typedef, like
15085   //   ^ fntype { ... }
15086   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15087     for (const auto &I : Fn->param_types()) {
15088       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15089           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15090       Params.push_back(Param);
15091     }
15092   }
15093 
15094   // Set the parameters on the block decl.
15095   if (!Params.empty()) {
15096     CurBlock->TheDecl->setParams(Params);
15097     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15098                              /*CheckParameterNames=*/false);
15099   }
15100 
15101   // Finally we can process decl attributes.
15102   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15103 
15104   // Put the parameter variables in scope.
15105   for (auto AI : CurBlock->TheDecl->parameters()) {
15106     AI->setOwningFunction(CurBlock->TheDecl);
15107 
15108     // If this has an identifier, add it to the scope stack.
15109     if (AI->getIdentifier()) {
15110       CheckShadow(CurBlock->TheScope, AI);
15111 
15112       PushOnScopeChains(AI, CurBlock->TheScope);
15113     }
15114   }
15115 }
15116 
15117 /// ActOnBlockError - If there is an error parsing a block, this callback
15118 /// is invoked to pop the information about the block from the action impl.
15119 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15120   // Leave the expression-evaluation context.
15121   DiscardCleanupsInEvaluationContext();
15122   PopExpressionEvaluationContext();
15123 
15124   // Pop off CurBlock, handle nested blocks.
15125   PopDeclContext();
15126   PopFunctionScopeInfo();
15127 }
15128 
15129 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15130 /// literal was successfully completed.  ^(int x){...}
15131 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15132                                     Stmt *Body, Scope *CurScope) {
15133   // If blocks are disabled, emit an error.
15134   if (!LangOpts.Blocks)
15135     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15136 
15137   // Leave the expression-evaluation context.
15138   if (hasAnyUnrecoverableErrorsInThisFunction())
15139     DiscardCleanupsInEvaluationContext();
15140   assert(!Cleanup.exprNeedsCleanups() &&
15141          "cleanups within block not correctly bound!");
15142   PopExpressionEvaluationContext();
15143 
15144   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15145   BlockDecl *BD = BSI->TheDecl;
15146 
15147   if (BSI->HasImplicitReturnType)
15148     deduceClosureReturnType(*BSI);
15149 
15150   QualType RetTy = Context.VoidTy;
15151   if (!BSI->ReturnType.isNull())
15152     RetTy = BSI->ReturnType;
15153 
15154   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15155   QualType BlockTy;
15156 
15157   // If the user wrote a function type in some form, try to use that.
15158   if (!BSI->FunctionType.isNull()) {
15159     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15160 
15161     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15162     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15163 
15164     // Turn protoless block types into nullary block types.
15165     if (isa<FunctionNoProtoType>(FTy)) {
15166       FunctionProtoType::ExtProtoInfo EPI;
15167       EPI.ExtInfo = Ext;
15168       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15169 
15170     // Otherwise, if we don't need to change anything about the function type,
15171     // preserve its sugar structure.
15172     } else if (FTy->getReturnType() == RetTy &&
15173                (!NoReturn || FTy->getNoReturnAttr())) {
15174       BlockTy = BSI->FunctionType;
15175 
15176     // Otherwise, make the minimal modifications to the function type.
15177     } else {
15178       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15179       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15180       EPI.TypeQuals = Qualifiers();
15181       EPI.ExtInfo = Ext;
15182       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15183     }
15184 
15185   // If we don't have a function type, just build one from nothing.
15186   } else {
15187     FunctionProtoType::ExtProtoInfo EPI;
15188     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15189     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15190   }
15191 
15192   DiagnoseUnusedParameters(BD->parameters());
15193   BlockTy = Context.getBlockPointerType(BlockTy);
15194 
15195   // If needed, diagnose invalid gotos and switches in the block.
15196   if (getCurFunction()->NeedsScopeChecking() &&
15197       !PP.isCodeCompletionEnabled())
15198     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15199 
15200   BD->setBody(cast<CompoundStmt>(Body));
15201 
15202   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15203     DiagnoseUnguardedAvailabilityViolations(BD);
15204 
15205   // Try to apply the named return value optimization. We have to check again
15206   // if we can do this, though, because blocks keep return statements around
15207   // to deduce an implicit return type.
15208   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15209       !BD->isDependentContext())
15210     computeNRVO(Body, BSI);
15211 
15212   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15213       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15214     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15215                           NTCUK_Destruct|NTCUK_Copy);
15216 
15217   PopDeclContext();
15218 
15219   // Pop the block scope now but keep it alive to the end of this function.
15220   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15221   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15222 
15223   // Set the captured variables on the block.
15224   SmallVector<BlockDecl::Capture, 4> Captures;
15225   for (Capture &Cap : BSI->Captures) {
15226     if (Cap.isInvalid() || Cap.isThisCapture())
15227       continue;
15228 
15229     VarDecl *Var = Cap.getVariable();
15230     Expr *CopyExpr = nullptr;
15231     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15232       if (const RecordType *Record =
15233               Cap.getCaptureType()->getAs<RecordType>()) {
15234         // The capture logic needs the destructor, so make sure we mark it.
15235         // Usually this is unnecessary because most local variables have
15236         // their destructors marked at declaration time, but parameters are
15237         // an exception because it's technically only the call site that
15238         // actually requires the destructor.
15239         if (isa<ParmVarDecl>(Var))
15240           FinalizeVarWithDestructor(Var, Record);
15241 
15242         // Enter a separate potentially-evaluated context while building block
15243         // initializers to isolate their cleanups from those of the block
15244         // itself.
15245         // FIXME: Is this appropriate even when the block itself occurs in an
15246         // unevaluated operand?
15247         EnterExpressionEvaluationContext EvalContext(
15248             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15249 
15250         SourceLocation Loc = Cap.getLocation();
15251 
15252         ExprResult Result = BuildDeclarationNameExpr(
15253             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15254 
15255         // According to the blocks spec, the capture of a variable from
15256         // the stack requires a const copy constructor.  This is not true
15257         // of the copy/move done to move a __block variable to the heap.
15258         if (!Result.isInvalid() &&
15259             !Result.get()->getType().isConstQualified()) {
15260           Result = ImpCastExprToType(Result.get(),
15261                                      Result.get()->getType().withConst(),
15262                                      CK_NoOp, VK_LValue);
15263         }
15264 
15265         if (!Result.isInvalid()) {
15266           Result = PerformCopyInitialization(
15267               InitializedEntity::InitializeBlock(Var->getLocation(),
15268                                                  Cap.getCaptureType(), false),
15269               Loc, Result.get());
15270         }
15271 
15272         // Build a full-expression copy expression if initialization
15273         // succeeded and used a non-trivial constructor.  Recover from
15274         // errors by pretending that the copy isn't necessary.
15275         if (!Result.isInvalid() &&
15276             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15277                 ->isTrivial()) {
15278           Result = MaybeCreateExprWithCleanups(Result);
15279           CopyExpr = Result.get();
15280         }
15281       }
15282     }
15283 
15284     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15285                               CopyExpr);
15286     Captures.push_back(NewCap);
15287   }
15288   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15289 
15290   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15291 
15292   // If the block isn't obviously global, i.e. it captures anything at
15293   // all, then we need to do a few things in the surrounding context:
15294   if (Result->getBlockDecl()->hasCaptures()) {
15295     // First, this expression has a new cleanup object.
15296     ExprCleanupObjects.push_back(Result->getBlockDecl());
15297     Cleanup.setExprNeedsCleanups(true);
15298 
15299     // It also gets a branch-protected scope if any of the captured
15300     // variables needs destruction.
15301     for (const auto &CI : Result->getBlockDecl()->captures()) {
15302       const VarDecl *var = CI.getVariable();
15303       if (var->getType().isDestructedType() != QualType::DK_none) {
15304         setFunctionHasBranchProtectedScope();
15305         break;
15306       }
15307     }
15308   }
15309 
15310   if (getCurFunction())
15311     getCurFunction()->addBlock(BD);
15312 
15313   return Result;
15314 }
15315 
15316 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15317                             SourceLocation RPLoc) {
15318   TypeSourceInfo *TInfo;
15319   GetTypeFromParser(Ty, &TInfo);
15320   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15321 }
15322 
15323 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15324                                 Expr *E, TypeSourceInfo *TInfo,
15325                                 SourceLocation RPLoc) {
15326   Expr *OrigExpr = E;
15327   bool IsMS = false;
15328 
15329   // CUDA device code does not support varargs.
15330   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15331     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15332       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15333       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15334         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15335     }
15336   }
15337 
15338   // NVPTX does not support va_arg expression.
15339   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15340       Context.getTargetInfo().getTriple().isNVPTX())
15341     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15342 
15343   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15344   // as Microsoft ABI on an actual Microsoft platform, where
15345   // __builtin_ms_va_list and __builtin_va_list are the same.)
15346   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15347       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15348     QualType MSVaListType = Context.getBuiltinMSVaListType();
15349     if (Context.hasSameType(MSVaListType, E->getType())) {
15350       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15351         return ExprError();
15352       IsMS = true;
15353     }
15354   }
15355 
15356   // Get the va_list type
15357   QualType VaListType = Context.getBuiltinVaListType();
15358   if (!IsMS) {
15359     if (VaListType->isArrayType()) {
15360       // Deal with implicit array decay; for example, on x86-64,
15361       // va_list is an array, but it's supposed to decay to
15362       // a pointer for va_arg.
15363       VaListType = Context.getArrayDecayedType(VaListType);
15364       // Make sure the input expression also decays appropriately.
15365       ExprResult Result = UsualUnaryConversions(E);
15366       if (Result.isInvalid())
15367         return ExprError();
15368       E = Result.get();
15369     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15370       // If va_list is a record type and we are compiling in C++ mode,
15371       // check the argument using reference binding.
15372       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15373           Context, Context.getLValueReferenceType(VaListType), false);
15374       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15375       if (Init.isInvalid())
15376         return ExprError();
15377       E = Init.getAs<Expr>();
15378     } else {
15379       // Otherwise, the va_list argument must be an l-value because
15380       // it is modified by va_arg.
15381       if (!E->isTypeDependent() &&
15382           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15383         return ExprError();
15384     }
15385   }
15386 
15387   if (!IsMS && !E->isTypeDependent() &&
15388       !Context.hasSameType(VaListType, E->getType()))
15389     return ExprError(
15390         Diag(E->getBeginLoc(),
15391              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15392         << OrigExpr->getType() << E->getSourceRange());
15393 
15394   if (!TInfo->getType()->isDependentType()) {
15395     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15396                             diag::err_second_parameter_to_va_arg_incomplete,
15397                             TInfo->getTypeLoc()))
15398       return ExprError();
15399 
15400     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15401                                TInfo->getType(),
15402                                diag::err_second_parameter_to_va_arg_abstract,
15403                                TInfo->getTypeLoc()))
15404       return ExprError();
15405 
15406     if (!TInfo->getType().isPODType(Context)) {
15407       Diag(TInfo->getTypeLoc().getBeginLoc(),
15408            TInfo->getType()->isObjCLifetimeType()
15409              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15410              : diag::warn_second_parameter_to_va_arg_not_pod)
15411         << TInfo->getType()
15412         << TInfo->getTypeLoc().getSourceRange();
15413     }
15414 
15415     // Check for va_arg where arguments of the given type will be promoted
15416     // (i.e. this va_arg is guaranteed to have undefined behavior).
15417     QualType PromoteType;
15418     if (TInfo->getType()->isPromotableIntegerType()) {
15419       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15420       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15421         PromoteType = QualType();
15422     }
15423     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15424       PromoteType = Context.DoubleTy;
15425     if (!PromoteType.isNull())
15426       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15427                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15428                           << TInfo->getType()
15429                           << PromoteType
15430                           << TInfo->getTypeLoc().getSourceRange());
15431   }
15432 
15433   QualType T = TInfo->getType().getNonLValueExprType(Context);
15434   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15435 }
15436 
15437 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15438   // The type of __null will be int or long, depending on the size of
15439   // pointers on the target.
15440   QualType Ty;
15441   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15442   if (pw == Context.getTargetInfo().getIntWidth())
15443     Ty = Context.IntTy;
15444   else if (pw == Context.getTargetInfo().getLongWidth())
15445     Ty = Context.LongTy;
15446   else if (pw == Context.getTargetInfo().getLongLongWidth())
15447     Ty = Context.LongLongTy;
15448   else {
15449     llvm_unreachable("I don't know size of pointer!");
15450   }
15451 
15452   return new (Context) GNUNullExpr(Ty, TokenLoc);
15453 }
15454 
15455 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15456                                     SourceLocation BuiltinLoc,
15457                                     SourceLocation RPLoc) {
15458   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15459 }
15460 
15461 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15462                                     SourceLocation BuiltinLoc,
15463                                     SourceLocation RPLoc,
15464                                     DeclContext *ParentContext) {
15465   return new (Context)
15466       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15467 }
15468 
15469 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15470                                         bool Diagnose) {
15471   if (!getLangOpts().ObjC)
15472     return false;
15473 
15474   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15475   if (!PT)
15476     return false;
15477   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15478 
15479   // Ignore any parens, implicit casts (should only be
15480   // array-to-pointer decays), and not-so-opaque values.  The last is
15481   // important for making this trigger for property assignments.
15482   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15483   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15484     if (OV->getSourceExpr())
15485       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15486 
15487   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15488     if (!PT->isObjCIdType() &&
15489         !(ID && ID->getIdentifier()->isStr("NSString")))
15490       return false;
15491     if (!SL->isAscii())
15492       return false;
15493 
15494     if (Diagnose) {
15495       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15496           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15497       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15498     }
15499     return true;
15500   }
15501 
15502   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15503       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15504       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15505       !SrcExpr->isNullPointerConstant(
15506           getASTContext(), Expr::NPC_NeverValueDependent)) {
15507     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15508       return false;
15509     if (Diagnose) {
15510       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15511           << /*number*/1
15512           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15513       Expr *NumLit =
15514           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15515       if (NumLit)
15516         Exp = NumLit;
15517     }
15518     return true;
15519   }
15520 
15521   return false;
15522 }
15523 
15524 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15525                                               const Expr *SrcExpr) {
15526   if (!DstType->isFunctionPointerType() ||
15527       !SrcExpr->getType()->isFunctionType())
15528     return false;
15529 
15530   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15531   if (!DRE)
15532     return false;
15533 
15534   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15535   if (!FD)
15536     return false;
15537 
15538   return !S.checkAddressOfFunctionIsAvailable(FD,
15539                                               /*Complain=*/true,
15540                                               SrcExpr->getBeginLoc());
15541 }
15542 
15543 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15544                                     SourceLocation Loc,
15545                                     QualType DstType, QualType SrcType,
15546                                     Expr *SrcExpr, AssignmentAction Action,
15547                                     bool *Complained) {
15548   if (Complained)
15549     *Complained = false;
15550 
15551   // Decode the result (notice that AST's are still created for extensions).
15552   bool CheckInferredResultType = false;
15553   bool isInvalid = false;
15554   unsigned DiagKind = 0;
15555   ConversionFixItGenerator ConvHints;
15556   bool MayHaveConvFixit = false;
15557   bool MayHaveFunctionDiff = false;
15558   const ObjCInterfaceDecl *IFace = nullptr;
15559   const ObjCProtocolDecl *PDecl = nullptr;
15560 
15561   switch (ConvTy) {
15562   case Compatible:
15563       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15564       return false;
15565 
15566   case PointerToInt:
15567     if (getLangOpts().CPlusPlus) {
15568       DiagKind = diag::err_typecheck_convert_pointer_int;
15569       isInvalid = true;
15570     } else {
15571       DiagKind = diag::ext_typecheck_convert_pointer_int;
15572     }
15573     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15574     MayHaveConvFixit = true;
15575     break;
15576   case IntToPointer:
15577     if (getLangOpts().CPlusPlus) {
15578       DiagKind = diag::err_typecheck_convert_int_pointer;
15579       isInvalid = true;
15580     } else {
15581       DiagKind = diag::ext_typecheck_convert_int_pointer;
15582     }
15583     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15584     MayHaveConvFixit = true;
15585     break;
15586   case IncompatibleFunctionPointer:
15587     if (getLangOpts().CPlusPlus) {
15588       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15589       isInvalid = true;
15590     } else {
15591       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15592     }
15593     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15594     MayHaveConvFixit = true;
15595     break;
15596   case IncompatiblePointer:
15597     if (Action == AA_Passing_CFAudited) {
15598       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15599     } else if (getLangOpts().CPlusPlus) {
15600       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15601       isInvalid = true;
15602     } else {
15603       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15604     }
15605     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15606       SrcType->isObjCObjectPointerType();
15607     if (!CheckInferredResultType) {
15608       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15609     } else if (CheckInferredResultType) {
15610       SrcType = SrcType.getUnqualifiedType();
15611       DstType = DstType.getUnqualifiedType();
15612     }
15613     MayHaveConvFixit = true;
15614     break;
15615   case IncompatiblePointerSign:
15616     if (getLangOpts().CPlusPlus) {
15617       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15618       isInvalid = true;
15619     } else {
15620       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15621     }
15622     break;
15623   case FunctionVoidPointer:
15624     if (getLangOpts().CPlusPlus) {
15625       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15626       isInvalid = true;
15627     } else {
15628       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15629     }
15630     break;
15631   case IncompatiblePointerDiscardsQualifiers: {
15632     // Perform array-to-pointer decay if necessary.
15633     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15634 
15635     isInvalid = true;
15636 
15637     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15638     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15639     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15640       DiagKind = diag::err_typecheck_incompatible_address_space;
15641       break;
15642 
15643     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15644       DiagKind = diag::err_typecheck_incompatible_ownership;
15645       break;
15646     }
15647 
15648     llvm_unreachable("unknown error case for discarding qualifiers!");
15649     // fallthrough
15650   }
15651   case CompatiblePointerDiscardsQualifiers:
15652     // If the qualifiers lost were because we were applying the
15653     // (deprecated) C++ conversion from a string literal to a char*
15654     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15655     // Ideally, this check would be performed in
15656     // checkPointerTypesForAssignment. However, that would require a
15657     // bit of refactoring (so that the second argument is an
15658     // expression, rather than a type), which should be done as part
15659     // of a larger effort to fix checkPointerTypesForAssignment for
15660     // C++ semantics.
15661     if (getLangOpts().CPlusPlus &&
15662         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15663       return false;
15664     if (getLangOpts().CPlusPlus) {
15665       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15666       isInvalid = true;
15667     } else {
15668       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15669     }
15670 
15671     break;
15672   case IncompatibleNestedPointerQualifiers:
15673     if (getLangOpts().CPlusPlus) {
15674       isInvalid = true;
15675       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15676     } else {
15677       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15678     }
15679     break;
15680   case IncompatibleNestedPointerAddressSpaceMismatch:
15681     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15682     isInvalid = true;
15683     break;
15684   case IntToBlockPointer:
15685     DiagKind = diag::err_int_to_block_pointer;
15686     isInvalid = true;
15687     break;
15688   case IncompatibleBlockPointer:
15689     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15690     isInvalid = true;
15691     break;
15692   case IncompatibleObjCQualifiedId: {
15693     if (SrcType->isObjCQualifiedIdType()) {
15694       const ObjCObjectPointerType *srcOPT =
15695                 SrcType->castAs<ObjCObjectPointerType>();
15696       for (auto *srcProto : srcOPT->quals()) {
15697         PDecl = srcProto;
15698         break;
15699       }
15700       if (const ObjCInterfaceType *IFaceT =
15701             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15702         IFace = IFaceT->getDecl();
15703     }
15704     else if (DstType->isObjCQualifiedIdType()) {
15705       const ObjCObjectPointerType *dstOPT =
15706         DstType->castAs<ObjCObjectPointerType>();
15707       for (auto *dstProto : dstOPT->quals()) {
15708         PDecl = dstProto;
15709         break;
15710       }
15711       if (const ObjCInterfaceType *IFaceT =
15712             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15713         IFace = IFaceT->getDecl();
15714     }
15715     if (getLangOpts().CPlusPlus) {
15716       DiagKind = diag::err_incompatible_qualified_id;
15717       isInvalid = true;
15718     } else {
15719       DiagKind = diag::warn_incompatible_qualified_id;
15720     }
15721     break;
15722   }
15723   case IncompatibleVectors:
15724     if (getLangOpts().CPlusPlus) {
15725       DiagKind = diag::err_incompatible_vectors;
15726       isInvalid = true;
15727     } else {
15728       DiagKind = diag::warn_incompatible_vectors;
15729     }
15730     break;
15731   case IncompatibleObjCWeakRef:
15732     DiagKind = diag::err_arc_weak_unavailable_assign;
15733     isInvalid = true;
15734     break;
15735   case Incompatible:
15736     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15737       if (Complained)
15738         *Complained = true;
15739       return true;
15740     }
15741 
15742     DiagKind = diag::err_typecheck_convert_incompatible;
15743     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15744     MayHaveConvFixit = true;
15745     isInvalid = true;
15746     MayHaveFunctionDiff = true;
15747     break;
15748   }
15749 
15750   QualType FirstType, SecondType;
15751   switch (Action) {
15752   case AA_Assigning:
15753   case AA_Initializing:
15754     // The destination type comes first.
15755     FirstType = DstType;
15756     SecondType = SrcType;
15757     break;
15758 
15759   case AA_Returning:
15760   case AA_Passing:
15761   case AA_Passing_CFAudited:
15762   case AA_Converting:
15763   case AA_Sending:
15764   case AA_Casting:
15765     // The source type comes first.
15766     FirstType = SrcType;
15767     SecondType = DstType;
15768     break;
15769   }
15770 
15771   PartialDiagnostic FDiag = PDiag(DiagKind);
15772   if (Action == AA_Passing_CFAudited)
15773     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15774   else
15775     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15776 
15777   // If we can fix the conversion, suggest the FixIts.
15778   if (!ConvHints.isNull()) {
15779     for (FixItHint &H : ConvHints.Hints)
15780       FDiag << H;
15781   }
15782 
15783   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15784 
15785   if (MayHaveFunctionDiff)
15786     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15787 
15788   Diag(Loc, FDiag);
15789   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15790        DiagKind == diag::err_incompatible_qualified_id) &&
15791       PDecl && IFace && !IFace->hasDefinition())
15792     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15793         << IFace << PDecl;
15794 
15795   if (SecondType == Context.OverloadTy)
15796     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15797                               FirstType, /*TakingAddress=*/true);
15798 
15799   if (CheckInferredResultType)
15800     EmitRelatedResultTypeNote(SrcExpr);
15801 
15802   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15803     EmitRelatedResultTypeNoteForReturn(DstType);
15804 
15805   if (Complained)
15806     *Complained = true;
15807   return isInvalid;
15808 }
15809 
15810 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15811                                                  llvm::APSInt *Result) {
15812   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15813   public:
15814     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15815       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15816     }
15817   } Diagnoser;
15818 
15819   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15820 }
15821 
15822 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15823                                                  llvm::APSInt *Result,
15824                                                  unsigned DiagID,
15825                                                  bool AllowFold) {
15826   class IDDiagnoser : public VerifyICEDiagnoser {
15827     unsigned DiagID;
15828 
15829   public:
15830     IDDiagnoser(unsigned DiagID)
15831       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15832 
15833     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15834       S.Diag(Loc, DiagID) << SR;
15835     }
15836   } Diagnoser(DiagID);
15837 
15838   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15839 }
15840 
15841 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15842                                             SourceRange SR) {
15843   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15844 }
15845 
15846 ExprResult
15847 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15848                                       VerifyICEDiagnoser &Diagnoser,
15849                                       bool AllowFold) {
15850   SourceLocation DiagLoc = E->getBeginLoc();
15851 
15852   if (getLangOpts().CPlusPlus11) {
15853     // C++11 [expr.const]p5:
15854     //   If an expression of literal class type is used in a context where an
15855     //   integral constant expression is required, then that class type shall
15856     //   have a single non-explicit conversion function to an integral or
15857     //   unscoped enumeration type
15858     ExprResult Converted;
15859     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15860     public:
15861       CXX11ConvertDiagnoser(bool Silent)
15862           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15863                                 Silent, true) {}
15864 
15865       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15866                                            QualType T) override {
15867         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15868       }
15869 
15870       SemaDiagnosticBuilder diagnoseIncomplete(
15871           Sema &S, SourceLocation Loc, QualType T) override {
15872         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15873       }
15874 
15875       SemaDiagnosticBuilder diagnoseExplicitConv(
15876           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15877         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15878       }
15879 
15880       SemaDiagnosticBuilder noteExplicitConv(
15881           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15882         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15883                  << ConvTy->isEnumeralType() << ConvTy;
15884       }
15885 
15886       SemaDiagnosticBuilder diagnoseAmbiguous(
15887           Sema &S, SourceLocation Loc, QualType T) override {
15888         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15889       }
15890 
15891       SemaDiagnosticBuilder noteAmbiguous(
15892           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15893         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15894                  << ConvTy->isEnumeralType() << ConvTy;
15895       }
15896 
15897       SemaDiagnosticBuilder diagnoseConversion(
15898           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15899         llvm_unreachable("conversion functions are permitted");
15900       }
15901     } ConvertDiagnoser(Diagnoser.Suppress);
15902 
15903     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15904                                                     ConvertDiagnoser);
15905     if (Converted.isInvalid())
15906       return Converted;
15907     E = Converted.get();
15908     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15909       return ExprError();
15910   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15911     // An ICE must be of integral or unscoped enumeration type.
15912     if (!Diagnoser.Suppress)
15913       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15914     return ExprError();
15915   }
15916 
15917   ExprResult RValueExpr = DefaultLvalueConversion(E);
15918   if (RValueExpr.isInvalid())
15919     return ExprError();
15920 
15921   E = RValueExpr.get();
15922 
15923   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15924   // in the non-ICE case.
15925   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15926     if (Result)
15927       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15928     if (!isa<ConstantExpr>(E))
15929       E = ConstantExpr::Create(Context, E);
15930     return E;
15931   }
15932 
15933   Expr::EvalResult EvalResult;
15934   SmallVector<PartialDiagnosticAt, 8> Notes;
15935   EvalResult.Diag = &Notes;
15936 
15937   // Try to evaluate the expression, and produce diagnostics explaining why it's
15938   // not a constant expression as a side-effect.
15939   bool Folded =
15940       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15941       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15942 
15943   if (!isa<ConstantExpr>(E))
15944     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15945 
15946   // In C++11, we can rely on diagnostics being produced for any expression
15947   // which is not a constant expression. If no diagnostics were produced, then
15948   // this is a constant expression.
15949   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15950     if (Result)
15951       *Result = EvalResult.Val.getInt();
15952     return E;
15953   }
15954 
15955   // If our only note is the usual "invalid subexpression" note, just point
15956   // the caret at its location rather than producing an essentially
15957   // redundant note.
15958   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15959         diag::note_invalid_subexpr_in_const_expr) {
15960     DiagLoc = Notes[0].first;
15961     Notes.clear();
15962   }
15963 
15964   if (!Folded || !AllowFold) {
15965     if (!Diagnoser.Suppress) {
15966       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15967       for (const PartialDiagnosticAt &Note : Notes)
15968         Diag(Note.first, Note.second);
15969     }
15970 
15971     return ExprError();
15972   }
15973 
15974   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15975   for (const PartialDiagnosticAt &Note : Notes)
15976     Diag(Note.first, Note.second);
15977 
15978   if (Result)
15979     *Result = EvalResult.Val.getInt();
15980   return E;
15981 }
15982 
15983 namespace {
15984   // Handle the case where we conclude a expression which we speculatively
15985   // considered to be unevaluated is actually evaluated.
15986   class TransformToPE : public TreeTransform<TransformToPE> {
15987     typedef TreeTransform<TransformToPE> BaseTransform;
15988 
15989   public:
15990     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15991 
15992     // Make sure we redo semantic analysis
15993     bool AlwaysRebuild() { return true; }
15994     bool ReplacingOriginal() { return true; }
15995 
15996     // We need to special-case DeclRefExprs referring to FieldDecls which
15997     // are not part of a member pointer formation; normal TreeTransforming
15998     // doesn't catch this case because of the way we represent them in the AST.
15999     // FIXME: This is a bit ugly; is it really the best way to handle this
16000     // case?
16001     //
16002     // Error on DeclRefExprs referring to FieldDecls.
16003     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16004       if (isa<FieldDecl>(E->getDecl()) &&
16005           !SemaRef.isUnevaluatedContext())
16006         return SemaRef.Diag(E->getLocation(),
16007                             diag::err_invalid_non_static_member_use)
16008             << E->getDecl() << E->getSourceRange();
16009 
16010       return BaseTransform::TransformDeclRefExpr(E);
16011     }
16012 
16013     // Exception: filter out member pointer formation
16014     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16015       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16016         return E;
16017 
16018       return BaseTransform::TransformUnaryOperator(E);
16019     }
16020 
16021     // The body of a lambda-expression is in a separate expression evaluation
16022     // context so never needs to be transformed.
16023     // FIXME: Ideally we wouldn't transform the closure type either, and would
16024     // just recreate the capture expressions and lambda expression.
16025     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16026       return SkipLambdaBody(E, Body);
16027     }
16028   };
16029 }
16030 
16031 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16032   assert(isUnevaluatedContext() &&
16033          "Should only transform unevaluated expressions");
16034   ExprEvalContexts.back().Context =
16035       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16036   if (isUnevaluatedContext())
16037     return E;
16038   return TransformToPE(*this).TransformExpr(E);
16039 }
16040 
16041 void
16042 Sema::PushExpressionEvaluationContext(
16043     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16044     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16045   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16046                                 LambdaContextDecl, ExprContext);
16047   Cleanup.reset();
16048   if (!MaybeODRUseExprs.empty())
16049     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16050 }
16051 
16052 void
16053 Sema::PushExpressionEvaluationContext(
16054     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16055     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16056   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16057   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16058 }
16059 
16060 namespace {
16061 
16062 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16063   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16064   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16065     if (E->getOpcode() == UO_Deref)
16066       return CheckPossibleDeref(S, E->getSubExpr());
16067   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16068     return CheckPossibleDeref(S, E->getBase());
16069   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16070     return CheckPossibleDeref(S, E->getBase());
16071   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16072     QualType Inner;
16073     QualType Ty = E->getType();
16074     if (const auto *Ptr = Ty->getAs<PointerType>())
16075       Inner = Ptr->getPointeeType();
16076     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16077       Inner = Arr->getElementType();
16078     else
16079       return nullptr;
16080 
16081     if (Inner->hasAttr(attr::NoDeref))
16082       return E;
16083   }
16084   return nullptr;
16085 }
16086 
16087 } // namespace
16088 
16089 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16090   for (const Expr *E : Rec.PossibleDerefs) {
16091     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16092     if (DeclRef) {
16093       const ValueDecl *Decl = DeclRef->getDecl();
16094       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16095           << Decl->getName() << E->getSourceRange();
16096       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16097     } else {
16098       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16099           << E->getSourceRange();
16100     }
16101   }
16102   Rec.PossibleDerefs.clear();
16103 }
16104 
16105 /// Check whether E, which is either a discarded-value expression or an
16106 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16107 /// and if so, remove it from the list of volatile-qualified assignments that
16108 /// we are going to warn are deprecated.
16109 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16110   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16111     return;
16112 
16113   // Note: ignoring parens here is not justified by the standard rules, but
16114   // ignoring parentheses seems like a more reasonable approach, and this only
16115   // drives a deprecation warning so doesn't affect conformance.
16116   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16117     if (BO->getOpcode() == BO_Assign) {
16118       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16119       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16120                  LHSs.end());
16121     }
16122   }
16123 }
16124 
16125 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16126   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16127       RebuildingImmediateInvocation)
16128     return E;
16129 
16130   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16131   /// It's OK if this fails; we'll also remove this in
16132   /// HandleImmediateInvocations, but catching it here allows us to avoid
16133   /// walking the AST looking for it in simple cases.
16134   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16135     if (auto *DeclRef =
16136             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16137       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16138 
16139   E = MaybeCreateExprWithCleanups(E);
16140 
16141   ConstantExpr *Res = ConstantExpr::Create(
16142       getASTContext(), E.get(),
16143       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16144                                    getASTContext()),
16145       /*IsImmediateInvocation*/ true);
16146   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16147   return Res;
16148 }
16149 
16150 static void EvaluateAndDiagnoseImmediateInvocation(
16151     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16152   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16153   Expr::EvalResult Eval;
16154   Eval.Diag = &Notes;
16155   ConstantExpr *CE = Candidate.getPointer();
16156   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16157                                            SemaRef.getASTContext(), true);
16158   if (!Result || !Notes.empty()) {
16159     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16160     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16161       InnerExpr = FunctionalCast->getSubExpr();
16162     FunctionDecl *FD = nullptr;
16163     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16164       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16165     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16166       FD = Call->getConstructor();
16167     else
16168       llvm_unreachable("unhandled decl kind");
16169     assert(FD->isConsteval());
16170     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16171     for (auto &Note : Notes)
16172       SemaRef.Diag(Note.first, Note.second);
16173     return;
16174   }
16175   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16176 }
16177 
16178 static void RemoveNestedImmediateInvocation(
16179     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16180     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16181   struct ComplexRemove : TreeTransform<ComplexRemove> {
16182     using Base = TreeTransform<ComplexRemove>;
16183     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16184     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16185     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16186         CurrentII;
16187     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16188                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16189                   SmallVector<Sema::ImmediateInvocationCandidate,
16190                               4>::reverse_iterator Current)
16191         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16192     void RemoveImmediateInvocation(ConstantExpr* E) {
16193       auto It = std::find_if(CurrentII, IISet.rend(),
16194                              [E](Sema::ImmediateInvocationCandidate Elem) {
16195                                return Elem.getPointer() == E;
16196                              });
16197       assert(It != IISet.rend() &&
16198              "ConstantExpr marked IsImmediateInvocation should "
16199              "be present");
16200       It->setInt(1); // Mark as deleted
16201     }
16202     ExprResult TransformConstantExpr(ConstantExpr *E) {
16203       if (!E->isImmediateInvocation())
16204         return Base::TransformConstantExpr(E);
16205       RemoveImmediateInvocation(E);
16206       return Base::TransformExpr(E->getSubExpr());
16207     }
16208     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16209     /// we need to remove its DeclRefExpr from the DRSet.
16210     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16211       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16212       return Base::TransformCXXOperatorCallExpr(E);
16213     }
16214     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16215     /// here.
16216     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16217       if (!Init)
16218         return Init;
16219       /// ConstantExpr are the first layer of implicit node to be removed so if
16220       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16221       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16222         if (CE->isImmediateInvocation())
16223           RemoveImmediateInvocation(CE);
16224       return Base::TransformInitializer(Init, NotCopyInit);
16225     }
16226     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16227       DRSet.erase(E);
16228       return E;
16229     }
16230     bool AlwaysRebuild() { return false; }
16231     bool ReplacingOriginal() { return true; }
16232     bool AllowSkippingCXXConstructExpr() {
16233       bool Res = AllowSkippingFirstCXXConstructExpr;
16234       AllowSkippingFirstCXXConstructExpr = true;
16235       return Res;
16236     }
16237     bool AllowSkippingFirstCXXConstructExpr = true;
16238   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16239                 Rec.ImmediateInvocationCandidates, It);
16240 
16241   /// CXXConstructExpr with a single argument are getting skipped by
16242   /// TreeTransform in some situtation because they could be implicit. This
16243   /// can only occur for the top-level CXXConstructExpr because it is used
16244   /// nowhere in the expression being transformed therefore will not be rebuilt.
16245   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16246   /// skipping the first CXXConstructExpr.
16247   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16248     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16249 
16250   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16251   assert(Res.isUsable());
16252   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16253   It->getPointer()->setSubExpr(Res.get());
16254 }
16255 
16256 static void
16257 HandleImmediateInvocations(Sema &SemaRef,
16258                            Sema::ExpressionEvaluationContextRecord &Rec) {
16259   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16260        Rec.ReferenceToConsteval.size() == 0) ||
16261       SemaRef.RebuildingImmediateInvocation)
16262     return;
16263 
16264   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16265   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16266   /// need to remove ReferenceToConsteval in the immediate invocation.
16267   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16268 
16269     /// Prevent sema calls during the tree transform from adding pointers that
16270     /// are already in the sets.
16271     llvm::SaveAndRestore<bool> DisableIITracking(
16272         SemaRef.RebuildingImmediateInvocation, true);
16273 
16274     /// Prevent diagnostic during tree transfrom as they are duplicates
16275     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16276 
16277     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16278          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16279       if (!It->getInt())
16280         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16281   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16282              Rec.ReferenceToConsteval.size()) {
16283     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16284       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16285       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16286       bool VisitDeclRefExpr(DeclRefExpr *E) {
16287         DRSet.erase(E);
16288         return DRSet.size();
16289       }
16290     } Visitor(Rec.ReferenceToConsteval);
16291     Visitor.TraverseStmt(
16292         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16293   }
16294   for (auto CE : Rec.ImmediateInvocationCandidates)
16295     if (!CE.getInt())
16296       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16297   for (auto DR : Rec.ReferenceToConsteval) {
16298     auto *FD = cast<FunctionDecl>(DR->getDecl());
16299     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16300         << FD;
16301     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16302   }
16303 }
16304 
16305 void Sema::PopExpressionEvaluationContext() {
16306   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16307   unsigned NumTypos = Rec.NumTypos;
16308 
16309   if (!Rec.Lambdas.empty()) {
16310     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16311     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16312         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16313       unsigned D;
16314       if (Rec.isUnevaluated()) {
16315         // C++11 [expr.prim.lambda]p2:
16316         //   A lambda-expression shall not appear in an unevaluated operand
16317         //   (Clause 5).
16318         D = diag::err_lambda_unevaluated_operand;
16319       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16320         // C++1y [expr.const]p2:
16321         //   A conditional-expression e is a core constant expression unless the
16322         //   evaluation of e, following the rules of the abstract machine, would
16323         //   evaluate [...] a lambda-expression.
16324         D = diag::err_lambda_in_constant_expression;
16325       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16326         // C++17 [expr.prim.lamda]p2:
16327         // A lambda-expression shall not appear [...] in a template-argument.
16328         D = diag::err_lambda_in_invalid_context;
16329       } else
16330         llvm_unreachable("Couldn't infer lambda error message.");
16331 
16332       for (const auto *L : Rec.Lambdas)
16333         Diag(L->getBeginLoc(), D);
16334     }
16335   }
16336 
16337   WarnOnPendingNoDerefs(Rec);
16338   HandleImmediateInvocations(*this, Rec);
16339 
16340   // Warn on any volatile-qualified simple-assignments that are not discarded-
16341   // value expressions nor unevaluated operands (those cases get removed from
16342   // this list by CheckUnusedVolatileAssignment).
16343   for (auto *BO : Rec.VolatileAssignmentLHSs)
16344     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16345         << BO->getType();
16346 
16347   // When are coming out of an unevaluated context, clear out any
16348   // temporaries that we may have created as part of the evaluation of
16349   // the expression in that context: they aren't relevant because they
16350   // will never be constructed.
16351   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16352     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16353                              ExprCleanupObjects.end());
16354     Cleanup = Rec.ParentCleanup;
16355     CleanupVarDeclMarking();
16356     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16357   // Otherwise, merge the contexts together.
16358   } else {
16359     Cleanup.mergeFrom(Rec.ParentCleanup);
16360     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16361                             Rec.SavedMaybeODRUseExprs.end());
16362   }
16363 
16364   // Pop the current expression evaluation context off the stack.
16365   ExprEvalContexts.pop_back();
16366 
16367   // The global expression evaluation context record is never popped.
16368   ExprEvalContexts.back().NumTypos += NumTypos;
16369 }
16370 
16371 void Sema::DiscardCleanupsInEvaluationContext() {
16372   ExprCleanupObjects.erase(
16373          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16374          ExprCleanupObjects.end());
16375   Cleanup.reset();
16376   MaybeODRUseExprs.clear();
16377 }
16378 
16379 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16380   ExprResult Result = CheckPlaceholderExpr(E);
16381   if (Result.isInvalid())
16382     return ExprError();
16383   E = Result.get();
16384   if (!E->getType()->isVariablyModifiedType())
16385     return E;
16386   return TransformToPotentiallyEvaluated(E);
16387 }
16388 
16389 /// Are we in a context that is potentially constant evaluated per C++20
16390 /// [expr.const]p12?
16391 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16392   /// C++2a [expr.const]p12:
16393   //   An expression or conversion is potentially constant evaluated if it is
16394   switch (SemaRef.ExprEvalContexts.back().Context) {
16395     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16396       // -- a manifestly constant-evaluated expression,
16397     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16398     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16399     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16400       // -- a potentially-evaluated expression,
16401     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16402       // -- an immediate subexpression of a braced-init-list,
16403 
16404       // -- [FIXME] an expression of the form & cast-expression that occurs
16405       //    within a templated entity
16406       // -- a subexpression of one of the above that is not a subexpression of
16407       // a nested unevaluated operand.
16408       return true;
16409 
16410     case Sema::ExpressionEvaluationContext::Unevaluated:
16411     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16412       // Expressions in this context are never evaluated.
16413       return false;
16414   }
16415   llvm_unreachable("Invalid context");
16416 }
16417 
16418 /// Return true if this function has a calling convention that requires mangling
16419 /// in the size of the parameter pack.
16420 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16421   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16422   // we don't need parameter type sizes.
16423   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16424   if (!TT.isOSWindows() || !TT.isX86())
16425     return false;
16426 
16427   // If this is C++ and this isn't an extern "C" function, parameters do not
16428   // need to be complete. In this case, C++ mangling will apply, which doesn't
16429   // use the size of the parameters.
16430   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16431     return false;
16432 
16433   // Stdcall, fastcall, and vectorcall need this special treatment.
16434   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16435   switch (CC) {
16436   case CC_X86StdCall:
16437   case CC_X86FastCall:
16438   case CC_X86VectorCall:
16439     return true;
16440   default:
16441     break;
16442   }
16443   return false;
16444 }
16445 
16446 /// Require that all of the parameter types of function be complete. Normally,
16447 /// parameter types are only required to be complete when a function is called
16448 /// or defined, but to mangle functions with certain calling conventions, the
16449 /// mangler needs to know the size of the parameter list. In this situation,
16450 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16451 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16452 /// result in a linker error. Clang doesn't implement this behavior, and instead
16453 /// attempts to error at compile time.
16454 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16455                                                   SourceLocation Loc) {
16456   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16457     FunctionDecl *FD;
16458     ParmVarDecl *Param;
16459 
16460   public:
16461     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16462         : FD(FD), Param(Param) {}
16463 
16464     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16465       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16466       StringRef CCName;
16467       switch (CC) {
16468       case CC_X86StdCall:
16469         CCName = "stdcall";
16470         break;
16471       case CC_X86FastCall:
16472         CCName = "fastcall";
16473         break;
16474       case CC_X86VectorCall:
16475         CCName = "vectorcall";
16476         break;
16477       default:
16478         llvm_unreachable("CC does not need mangling");
16479       }
16480 
16481       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16482           << Param->getDeclName() << FD->getDeclName() << CCName;
16483     }
16484   };
16485 
16486   for (ParmVarDecl *Param : FD->parameters()) {
16487     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16488     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16489   }
16490 }
16491 
16492 namespace {
16493 enum class OdrUseContext {
16494   /// Declarations in this context are not odr-used.
16495   None,
16496   /// Declarations in this context are formally odr-used, but this is a
16497   /// dependent context.
16498   Dependent,
16499   /// Declarations in this context are odr-used but not actually used (yet).
16500   FormallyOdrUsed,
16501   /// Declarations in this context are used.
16502   Used
16503 };
16504 }
16505 
16506 /// Are we within a context in which references to resolved functions or to
16507 /// variables result in odr-use?
16508 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16509   OdrUseContext Result;
16510 
16511   switch (SemaRef.ExprEvalContexts.back().Context) {
16512     case Sema::ExpressionEvaluationContext::Unevaluated:
16513     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16514     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16515       return OdrUseContext::None;
16516 
16517     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16518     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16519       Result = OdrUseContext::Used;
16520       break;
16521 
16522     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16523       Result = OdrUseContext::FormallyOdrUsed;
16524       break;
16525 
16526     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16527       // A default argument formally results in odr-use, but doesn't actually
16528       // result in a use in any real sense until it itself is used.
16529       Result = OdrUseContext::FormallyOdrUsed;
16530       break;
16531   }
16532 
16533   if (SemaRef.CurContext->isDependentContext())
16534     return OdrUseContext::Dependent;
16535 
16536   return Result;
16537 }
16538 
16539 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16540   return Func->isConstexpr() &&
16541          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16542 }
16543 
16544 /// Mark a function referenced, and check whether it is odr-used
16545 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16546 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16547                                   bool MightBeOdrUse) {
16548   assert(Func && "No function?");
16549 
16550   Func->setReferenced();
16551 
16552   // Recursive functions aren't really used until they're used from some other
16553   // context.
16554   bool IsRecursiveCall = CurContext == Func;
16555 
16556   // C++11 [basic.def.odr]p3:
16557   //   A function whose name appears as a potentially-evaluated expression is
16558   //   odr-used if it is the unique lookup result or the selected member of a
16559   //   set of overloaded functions [...].
16560   //
16561   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16562   // can just check that here.
16563   OdrUseContext OdrUse =
16564       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16565   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16566     OdrUse = OdrUseContext::FormallyOdrUsed;
16567 
16568   // Trivial default constructors and destructors are never actually used.
16569   // FIXME: What about other special members?
16570   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16571       OdrUse == OdrUseContext::Used) {
16572     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16573       if (Constructor->isDefaultConstructor())
16574         OdrUse = OdrUseContext::FormallyOdrUsed;
16575     if (isa<CXXDestructorDecl>(Func))
16576       OdrUse = OdrUseContext::FormallyOdrUsed;
16577   }
16578 
16579   // C++20 [expr.const]p12:
16580   //   A function [...] is needed for constant evaluation if it is [...] a
16581   //   constexpr function that is named by an expression that is potentially
16582   //   constant evaluated
16583   bool NeededForConstantEvaluation =
16584       isPotentiallyConstantEvaluatedContext(*this) &&
16585       isImplicitlyDefinableConstexprFunction(Func);
16586 
16587   // Determine whether we require a function definition to exist, per
16588   // C++11 [temp.inst]p3:
16589   //   Unless a function template specialization has been explicitly
16590   //   instantiated or explicitly specialized, the function template
16591   //   specialization is implicitly instantiated when the specialization is
16592   //   referenced in a context that requires a function definition to exist.
16593   // C++20 [temp.inst]p7:
16594   //   The existence of a definition of a [...] function is considered to
16595   //   affect the semantics of the program if the [...] function is needed for
16596   //   constant evaluation by an expression
16597   // C++20 [basic.def.odr]p10:
16598   //   Every program shall contain exactly one definition of every non-inline
16599   //   function or variable that is odr-used in that program outside of a
16600   //   discarded statement
16601   // C++20 [special]p1:
16602   //   The implementation will implicitly define [defaulted special members]
16603   //   if they are odr-used or needed for constant evaluation.
16604   //
16605   // Note that we skip the implicit instantiation of templates that are only
16606   // used in unused default arguments or by recursive calls to themselves.
16607   // This is formally non-conforming, but seems reasonable in practice.
16608   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16609                                              NeededForConstantEvaluation);
16610 
16611   // C++14 [temp.expl.spec]p6:
16612   //   If a template [...] is explicitly specialized then that specialization
16613   //   shall be declared before the first use of that specialization that would
16614   //   cause an implicit instantiation to take place, in every translation unit
16615   //   in which such a use occurs
16616   if (NeedDefinition &&
16617       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16618        Func->getMemberSpecializationInfo()))
16619     checkSpecializationVisibility(Loc, Func);
16620 
16621   if (getLangOpts().CUDA)
16622     CheckCUDACall(Loc, Func);
16623 
16624   if (getLangOpts().SYCLIsDevice)
16625     checkSYCLDeviceFunction(Loc, Func);
16626 
16627   // If we need a definition, try to create one.
16628   if (NeedDefinition && !Func->getBody()) {
16629     runWithSufficientStackSpace(Loc, [&] {
16630       if (CXXConstructorDecl *Constructor =
16631               dyn_cast<CXXConstructorDecl>(Func)) {
16632         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16633         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16634           if (Constructor->isDefaultConstructor()) {
16635             if (Constructor->isTrivial() &&
16636                 !Constructor->hasAttr<DLLExportAttr>())
16637               return;
16638             DefineImplicitDefaultConstructor(Loc, Constructor);
16639           } else if (Constructor->isCopyConstructor()) {
16640             DefineImplicitCopyConstructor(Loc, Constructor);
16641           } else if (Constructor->isMoveConstructor()) {
16642             DefineImplicitMoveConstructor(Loc, Constructor);
16643           }
16644         } else if (Constructor->getInheritedConstructor()) {
16645           DefineInheritingConstructor(Loc, Constructor);
16646         }
16647       } else if (CXXDestructorDecl *Destructor =
16648                      dyn_cast<CXXDestructorDecl>(Func)) {
16649         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16650         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16651           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16652             return;
16653           DefineImplicitDestructor(Loc, Destructor);
16654         }
16655         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16656           MarkVTableUsed(Loc, Destructor->getParent());
16657       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16658         if (MethodDecl->isOverloadedOperator() &&
16659             MethodDecl->getOverloadedOperator() == OO_Equal) {
16660           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16661           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16662             if (MethodDecl->isCopyAssignmentOperator())
16663               DefineImplicitCopyAssignment(Loc, MethodDecl);
16664             else if (MethodDecl->isMoveAssignmentOperator())
16665               DefineImplicitMoveAssignment(Loc, MethodDecl);
16666           }
16667         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16668                    MethodDecl->getParent()->isLambda()) {
16669           CXXConversionDecl *Conversion =
16670               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16671           if (Conversion->isLambdaToBlockPointerConversion())
16672             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16673           else
16674             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16675         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16676           MarkVTableUsed(Loc, MethodDecl->getParent());
16677       }
16678 
16679       if (Func->isDefaulted() && !Func->isDeleted()) {
16680         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16681         if (DCK != DefaultedComparisonKind::None)
16682           DefineDefaultedComparison(Loc, Func, DCK);
16683       }
16684 
16685       // Implicit instantiation of function templates and member functions of
16686       // class templates.
16687       if (Func->isImplicitlyInstantiable()) {
16688         TemplateSpecializationKind TSK =
16689             Func->getTemplateSpecializationKindForInstantiation();
16690         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16691         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16692         if (FirstInstantiation) {
16693           PointOfInstantiation = Loc;
16694           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16695         } else if (TSK != TSK_ImplicitInstantiation) {
16696           // Use the point of use as the point of instantiation, instead of the
16697           // point of explicit instantiation (which we track as the actual point
16698           // of instantiation). This gives better backtraces in diagnostics.
16699           PointOfInstantiation = Loc;
16700         }
16701 
16702         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16703             Func->isConstexpr()) {
16704           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16705               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16706               CodeSynthesisContexts.size())
16707             PendingLocalImplicitInstantiations.push_back(
16708                 std::make_pair(Func, PointOfInstantiation));
16709           else if (Func->isConstexpr())
16710             // Do not defer instantiations of constexpr functions, to avoid the
16711             // expression evaluator needing to call back into Sema if it sees a
16712             // call to such a function.
16713             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16714           else {
16715             Func->setInstantiationIsPending(true);
16716             PendingInstantiations.push_back(
16717                 std::make_pair(Func, PointOfInstantiation));
16718             // Notify the consumer that a function was implicitly instantiated.
16719             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16720           }
16721         }
16722       } else {
16723         // Walk redefinitions, as some of them may be instantiable.
16724         for (auto i : Func->redecls()) {
16725           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16726             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16727         }
16728       }
16729     });
16730   }
16731 
16732   // C++14 [except.spec]p17:
16733   //   An exception-specification is considered to be needed when:
16734   //   - the function is odr-used or, if it appears in an unevaluated operand,
16735   //     would be odr-used if the expression were potentially-evaluated;
16736   //
16737   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16738   // function is a pure virtual function we're calling, and in that case the
16739   // function was selected by overload resolution and we need to resolve its
16740   // exception specification for a different reason.
16741   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16742   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16743     ResolveExceptionSpec(Loc, FPT);
16744 
16745   // If this is the first "real" use, act on that.
16746   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16747     // Keep track of used but undefined functions.
16748     if (!Func->isDefined()) {
16749       if (mightHaveNonExternalLinkage(Func))
16750         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16751       else if (Func->getMostRecentDecl()->isInlined() &&
16752                !LangOpts.GNUInline &&
16753                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16754         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16755       else if (isExternalWithNoLinkageType(Func))
16756         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16757     }
16758 
16759     // Some x86 Windows calling conventions mangle the size of the parameter
16760     // pack into the name. Computing the size of the parameters requires the
16761     // parameter types to be complete. Check that now.
16762     if (funcHasParameterSizeMangling(*this, Func))
16763       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16764 
16765     // In the MS C++ ABI, the compiler emits destructor variants where they are
16766     // used. If the destructor is used here but defined elsewhere, mark the
16767     // virtual base destructors referenced. If those virtual base destructors
16768     // are inline, this will ensure they are defined when emitting the complete
16769     // destructor variant. This checking may be redundant if the destructor is
16770     // provided later in this TU.
16771     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16772       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16773         CXXRecordDecl *Parent = Dtor->getParent();
16774         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16775           CheckCompleteDestructorVariant(Loc, Dtor);
16776       }
16777     }
16778 
16779     Func->markUsed(Context);
16780   }
16781 }
16782 
16783 /// Directly mark a variable odr-used. Given a choice, prefer to use
16784 /// MarkVariableReferenced since it does additional checks and then
16785 /// calls MarkVarDeclODRUsed.
16786 /// If the variable must be captured:
16787 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16788 ///  - else capture it in the DeclContext that maps to the
16789 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16790 static void
16791 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16792                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16793   // Keep track of used but undefined variables.
16794   // FIXME: We shouldn't suppress this warning for static data members.
16795   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16796       (!Var->isExternallyVisible() || Var->isInline() ||
16797        SemaRef.isExternalWithNoLinkageType(Var)) &&
16798       !(Var->isStaticDataMember() && Var->hasInit())) {
16799     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16800     if (old.isInvalid())
16801       old = Loc;
16802   }
16803   QualType CaptureType, DeclRefType;
16804   if (SemaRef.LangOpts.OpenMP)
16805     SemaRef.tryCaptureOpenMPLambdas(Var);
16806   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16807     /*EllipsisLoc*/ SourceLocation(),
16808     /*BuildAndDiagnose*/ true,
16809     CaptureType, DeclRefType,
16810     FunctionScopeIndexToStopAt);
16811 
16812   Var->markUsed(SemaRef.Context);
16813 }
16814 
16815 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16816                                              SourceLocation Loc,
16817                                              unsigned CapturingScopeIndex) {
16818   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16819 }
16820 
16821 static void
16822 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16823                                    ValueDecl *var, DeclContext *DC) {
16824   DeclContext *VarDC = var->getDeclContext();
16825 
16826   //  If the parameter still belongs to the translation unit, then
16827   //  we're actually just using one parameter in the declaration of
16828   //  the next.
16829   if (isa<ParmVarDecl>(var) &&
16830       isa<TranslationUnitDecl>(VarDC))
16831     return;
16832 
16833   // For C code, don't diagnose about capture if we're not actually in code
16834   // right now; it's impossible to write a non-constant expression outside of
16835   // function context, so we'll get other (more useful) diagnostics later.
16836   //
16837   // For C++, things get a bit more nasty... it would be nice to suppress this
16838   // diagnostic for certain cases like using a local variable in an array bound
16839   // for a member of a local class, but the correct predicate is not obvious.
16840   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16841     return;
16842 
16843   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16844   unsigned ContextKind = 3; // unknown
16845   if (isa<CXXMethodDecl>(VarDC) &&
16846       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16847     ContextKind = 2;
16848   } else if (isa<FunctionDecl>(VarDC)) {
16849     ContextKind = 0;
16850   } else if (isa<BlockDecl>(VarDC)) {
16851     ContextKind = 1;
16852   }
16853 
16854   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16855     << var << ValueKind << ContextKind << VarDC;
16856   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16857       << var;
16858 
16859   // FIXME: Add additional diagnostic info about class etc. which prevents
16860   // capture.
16861 }
16862 
16863 
16864 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16865                                       bool &SubCapturesAreNested,
16866                                       QualType &CaptureType,
16867                                       QualType &DeclRefType) {
16868    // Check whether we've already captured it.
16869   if (CSI->CaptureMap.count(Var)) {
16870     // If we found a capture, any subcaptures are nested.
16871     SubCapturesAreNested = true;
16872 
16873     // Retrieve the capture type for this variable.
16874     CaptureType = CSI->getCapture(Var).getCaptureType();
16875 
16876     // Compute the type of an expression that refers to this variable.
16877     DeclRefType = CaptureType.getNonReferenceType();
16878 
16879     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16880     // are mutable in the sense that user can change their value - they are
16881     // private instances of the captured declarations.
16882     const Capture &Cap = CSI->getCapture(Var);
16883     if (Cap.isCopyCapture() &&
16884         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16885         !(isa<CapturedRegionScopeInfo>(CSI) &&
16886           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16887       DeclRefType.addConst();
16888     return true;
16889   }
16890   return false;
16891 }
16892 
16893 // Only block literals, captured statements, and lambda expressions can
16894 // capture; other scopes don't work.
16895 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16896                                  SourceLocation Loc,
16897                                  const bool Diagnose, Sema &S) {
16898   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16899     return getLambdaAwareParentOfDeclContext(DC);
16900   else if (Var->hasLocalStorage()) {
16901     if (Diagnose)
16902        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16903   }
16904   return nullptr;
16905 }
16906 
16907 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16908 // certain types of variables (unnamed, variably modified types etc.)
16909 // so check for eligibility.
16910 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16911                                  SourceLocation Loc,
16912                                  const bool Diagnose, Sema &S) {
16913 
16914   bool IsBlock = isa<BlockScopeInfo>(CSI);
16915   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16916 
16917   // Lambdas are not allowed to capture unnamed variables
16918   // (e.g. anonymous unions).
16919   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16920   // assuming that's the intent.
16921   if (IsLambda && !Var->getDeclName()) {
16922     if (Diagnose) {
16923       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16924       S.Diag(Var->getLocation(), diag::note_declared_at);
16925     }
16926     return false;
16927   }
16928 
16929   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16930   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16931     if (Diagnose) {
16932       S.Diag(Loc, diag::err_ref_vm_type);
16933       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16934     }
16935     return false;
16936   }
16937   // Prohibit structs with flexible array members too.
16938   // We cannot capture what is in the tail end of the struct.
16939   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16940     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16941       if (Diagnose) {
16942         if (IsBlock)
16943           S.Diag(Loc, diag::err_ref_flexarray_type);
16944         else
16945           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16946         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16947       }
16948       return false;
16949     }
16950   }
16951   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16952   // Lambdas and captured statements are not allowed to capture __block
16953   // variables; they don't support the expected semantics.
16954   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16955     if (Diagnose) {
16956       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
16957       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16958     }
16959     return false;
16960   }
16961   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16962   if (S.getLangOpts().OpenCL && IsBlock &&
16963       Var->getType()->isBlockPointerType()) {
16964     if (Diagnose)
16965       S.Diag(Loc, diag::err_opencl_block_ref_block);
16966     return false;
16967   }
16968 
16969   return true;
16970 }
16971 
16972 // Returns true if the capture by block was successful.
16973 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16974                                  SourceLocation Loc,
16975                                  const bool BuildAndDiagnose,
16976                                  QualType &CaptureType,
16977                                  QualType &DeclRefType,
16978                                  const bool Nested,
16979                                  Sema &S, bool Invalid) {
16980   bool ByRef = false;
16981 
16982   // Blocks are not allowed to capture arrays, excepting OpenCL.
16983   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16984   // (decayed to pointers).
16985   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16986     if (BuildAndDiagnose) {
16987       S.Diag(Loc, diag::err_ref_array_type);
16988       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16989       Invalid = true;
16990     } else {
16991       return false;
16992     }
16993   }
16994 
16995   // Forbid the block-capture of autoreleasing variables.
16996   if (!Invalid &&
16997       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16998     if (BuildAndDiagnose) {
16999       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17000         << /*block*/ 0;
17001       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17002       Invalid = true;
17003     } else {
17004       return false;
17005     }
17006   }
17007 
17008   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17009   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17010     QualType PointeeTy = PT->getPointeeType();
17011 
17012     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17013         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17014         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17015       if (BuildAndDiagnose) {
17016         SourceLocation VarLoc = Var->getLocation();
17017         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17018         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17019       }
17020     }
17021   }
17022 
17023   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17024   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17025       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17026     // Block capture by reference does not change the capture or
17027     // declaration reference types.
17028     ByRef = true;
17029   } else {
17030     // Block capture by copy introduces 'const'.
17031     CaptureType = CaptureType.getNonReferenceType().withConst();
17032     DeclRefType = CaptureType;
17033   }
17034 
17035   // Actually capture the variable.
17036   if (BuildAndDiagnose)
17037     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17038                     CaptureType, Invalid);
17039 
17040   return !Invalid;
17041 }
17042 
17043 
17044 /// Capture the given variable in the captured region.
17045 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17046                                     VarDecl *Var,
17047                                     SourceLocation Loc,
17048                                     const bool BuildAndDiagnose,
17049                                     QualType &CaptureType,
17050                                     QualType &DeclRefType,
17051                                     const bool RefersToCapturedVariable,
17052                                     Sema &S, bool Invalid) {
17053   // By default, capture variables by reference.
17054   bool ByRef = true;
17055   // Using an LValue reference type is consistent with Lambdas (see below).
17056   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17057     if (S.isOpenMPCapturedDecl(Var)) {
17058       bool HasConst = DeclRefType.isConstQualified();
17059       DeclRefType = DeclRefType.getUnqualifiedType();
17060       // Don't lose diagnostics about assignments to const.
17061       if (HasConst)
17062         DeclRefType.addConst();
17063     }
17064     // Do not capture firstprivates in tasks.
17065     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17066         OMPC_unknown)
17067       return true;
17068     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17069                                     RSI->OpenMPCaptureLevel);
17070   }
17071 
17072   if (ByRef)
17073     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17074   else
17075     CaptureType = DeclRefType;
17076 
17077   // Actually capture the variable.
17078   if (BuildAndDiagnose)
17079     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17080                     Loc, SourceLocation(), CaptureType, Invalid);
17081 
17082   return !Invalid;
17083 }
17084 
17085 /// Capture the given variable in the lambda.
17086 static bool captureInLambda(LambdaScopeInfo *LSI,
17087                             VarDecl *Var,
17088                             SourceLocation Loc,
17089                             const bool BuildAndDiagnose,
17090                             QualType &CaptureType,
17091                             QualType &DeclRefType,
17092                             const bool RefersToCapturedVariable,
17093                             const Sema::TryCaptureKind Kind,
17094                             SourceLocation EllipsisLoc,
17095                             const bool IsTopScope,
17096                             Sema &S, bool Invalid) {
17097   // Determine whether we are capturing by reference or by value.
17098   bool ByRef = false;
17099   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17100     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17101   } else {
17102     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17103   }
17104 
17105   // Compute the type of the field that will capture this variable.
17106   if (ByRef) {
17107     // C++11 [expr.prim.lambda]p15:
17108     //   An entity is captured by reference if it is implicitly or
17109     //   explicitly captured but not captured by copy. It is
17110     //   unspecified whether additional unnamed non-static data
17111     //   members are declared in the closure type for entities
17112     //   captured by reference.
17113     //
17114     // FIXME: It is not clear whether we want to build an lvalue reference
17115     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17116     // to do the former, while EDG does the latter. Core issue 1249 will
17117     // clarify, but for now we follow GCC because it's a more permissive and
17118     // easily defensible position.
17119     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17120   } else {
17121     // C++11 [expr.prim.lambda]p14:
17122     //   For each entity captured by copy, an unnamed non-static
17123     //   data member is declared in the closure type. The
17124     //   declaration order of these members is unspecified. The type
17125     //   of such a data member is the type of the corresponding
17126     //   captured entity if the entity is not a reference to an
17127     //   object, or the referenced type otherwise. [Note: If the
17128     //   captured entity is a reference to a function, the
17129     //   corresponding data member is also a reference to a
17130     //   function. - end note ]
17131     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17132       if (!RefType->getPointeeType()->isFunctionType())
17133         CaptureType = RefType->getPointeeType();
17134     }
17135 
17136     // Forbid the lambda copy-capture of autoreleasing variables.
17137     if (!Invalid &&
17138         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17139       if (BuildAndDiagnose) {
17140         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17141         S.Diag(Var->getLocation(), diag::note_previous_decl)
17142           << Var->getDeclName();
17143         Invalid = true;
17144       } else {
17145         return false;
17146       }
17147     }
17148 
17149     // Make sure that by-copy captures are of a complete and non-abstract type.
17150     if (!Invalid && BuildAndDiagnose) {
17151       if (!CaptureType->isDependentType() &&
17152           S.RequireCompleteSizedType(
17153               Loc, CaptureType,
17154               diag::err_capture_of_incomplete_or_sizeless_type,
17155               Var->getDeclName()))
17156         Invalid = true;
17157       else if (S.RequireNonAbstractType(Loc, CaptureType,
17158                                         diag::err_capture_of_abstract_type))
17159         Invalid = true;
17160     }
17161   }
17162 
17163   // Compute the type of a reference to this captured variable.
17164   if (ByRef)
17165     DeclRefType = CaptureType.getNonReferenceType();
17166   else {
17167     // C++ [expr.prim.lambda]p5:
17168     //   The closure type for a lambda-expression has a public inline
17169     //   function call operator [...]. This function call operator is
17170     //   declared const (9.3.1) if and only if the lambda-expression's
17171     //   parameter-declaration-clause is not followed by mutable.
17172     DeclRefType = CaptureType.getNonReferenceType();
17173     if (!LSI->Mutable && !CaptureType->isReferenceType())
17174       DeclRefType.addConst();
17175   }
17176 
17177   // Add the capture.
17178   if (BuildAndDiagnose)
17179     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17180                     Loc, EllipsisLoc, CaptureType, Invalid);
17181 
17182   return !Invalid;
17183 }
17184 
17185 bool Sema::tryCaptureVariable(
17186     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17187     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17188     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17189   // An init-capture is notionally from the context surrounding its
17190   // declaration, but its parent DC is the lambda class.
17191   DeclContext *VarDC = Var->getDeclContext();
17192   if (Var->isInitCapture())
17193     VarDC = VarDC->getParent();
17194 
17195   DeclContext *DC = CurContext;
17196   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17197       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17198   // We need to sync up the Declaration Context with the
17199   // FunctionScopeIndexToStopAt
17200   if (FunctionScopeIndexToStopAt) {
17201     unsigned FSIndex = FunctionScopes.size() - 1;
17202     while (FSIndex != MaxFunctionScopesIndex) {
17203       DC = getLambdaAwareParentOfDeclContext(DC);
17204       --FSIndex;
17205     }
17206   }
17207 
17208 
17209   // If the variable is declared in the current context, there is no need to
17210   // capture it.
17211   if (VarDC == DC) return true;
17212 
17213   // Capture global variables if it is required to use private copy of this
17214   // variable.
17215   bool IsGlobal = !Var->hasLocalStorage();
17216   if (IsGlobal &&
17217       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17218                                                 MaxFunctionScopesIndex)))
17219     return true;
17220   Var = Var->getCanonicalDecl();
17221 
17222   // Walk up the stack to determine whether we can capture the variable,
17223   // performing the "simple" checks that don't depend on type. We stop when
17224   // we've either hit the declared scope of the variable or find an existing
17225   // capture of that variable.  We start from the innermost capturing-entity
17226   // (the DC) and ensure that all intervening capturing-entities
17227   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17228   // declcontext can either capture the variable or have already captured
17229   // the variable.
17230   CaptureType = Var->getType();
17231   DeclRefType = CaptureType.getNonReferenceType();
17232   bool Nested = false;
17233   bool Explicit = (Kind != TryCapture_Implicit);
17234   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17235   do {
17236     // Only block literals, captured statements, and lambda expressions can
17237     // capture; other scopes don't work.
17238     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17239                                                               ExprLoc,
17240                                                               BuildAndDiagnose,
17241                                                               *this);
17242     // We need to check for the parent *first* because, if we *have*
17243     // private-captured a global variable, we need to recursively capture it in
17244     // intermediate blocks, lambdas, etc.
17245     if (!ParentDC) {
17246       if (IsGlobal) {
17247         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17248         break;
17249       }
17250       return true;
17251     }
17252 
17253     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17254     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17255 
17256 
17257     // Check whether we've already captured it.
17258     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17259                                              DeclRefType)) {
17260       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17261       break;
17262     }
17263     // If we are instantiating a generic lambda call operator body,
17264     // we do not want to capture new variables.  What was captured
17265     // during either a lambdas transformation or initial parsing
17266     // should be used.
17267     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17268       if (BuildAndDiagnose) {
17269         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17270         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17271           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17272           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17273           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17274         } else
17275           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17276       }
17277       return true;
17278     }
17279 
17280     // Try to capture variable-length arrays types.
17281     if (Var->getType()->isVariablyModifiedType()) {
17282       // We're going to walk down into the type and look for VLA
17283       // expressions.
17284       QualType QTy = Var->getType();
17285       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17286         QTy = PVD->getOriginalType();
17287       captureVariablyModifiedType(Context, QTy, CSI);
17288     }
17289 
17290     if (getLangOpts().OpenMP) {
17291       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17292         // OpenMP private variables should not be captured in outer scope, so
17293         // just break here. Similarly, global variables that are captured in a
17294         // target region should not be captured outside the scope of the region.
17295         if (RSI->CapRegionKind == CR_OpenMP) {
17296           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17297               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17298           // If the variable is private (i.e. not captured) and has variably
17299           // modified type, we still need to capture the type for correct
17300           // codegen in all regions, associated with the construct. Currently,
17301           // it is captured in the innermost captured region only.
17302           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17303               Var->getType()->isVariablyModifiedType()) {
17304             QualType QTy = Var->getType();
17305             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17306               QTy = PVD->getOriginalType();
17307             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17308                  I < E; ++I) {
17309               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17310                   FunctionScopes[FunctionScopesIndex - I]);
17311               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17312                      "Wrong number of captured regions associated with the "
17313                      "OpenMP construct.");
17314               captureVariablyModifiedType(Context, QTy, OuterRSI);
17315             }
17316           }
17317           bool IsTargetCap =
17318               IsOpenMPPrivateDecl != OMPC_private &&
17319               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17320                                          RSI->OpenMPCaptureLevel);
17321           // Do not capture global if it is not privatized in outer regions.
17322           bool IsGlobalCap =
17323               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17324                                                      RSI->OpenMPCaptureLevel);
17325 
17326           // When we detect target captures we are looking from inside the
17327           // target region, therefore we need to propagate the capture from the
17328           // enclosing region. Therefore, the capture is not initially nested.
17329           if (IsTargetCap)
17330             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17331 
17332           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17333               (IsGlobal && !IsGlobalCap)) {
17334             Nested = !IsTargetCap;
17335             DeclRefType = DeclRefType.getUnqualifiedType();
17336             CaptureType = Context.getLValueReferenceType(DeclRefType);
17337             break;
17338           }
17339         }
17340       }
17341     }
17342     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17343       // No capture-default, and this is not an explicit capture
17344       // so cannot capture this variable.
17345       if (BuildAndDiagnose) {
17346         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17347         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17348         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17349           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17350                diag::note_lambda_decl);
17351         // FIXME: If we error out because an outer lambda can not implicitly
17352         // capture a variable that an inner lambda explicitly captures, we
17353         // should have the inner lambda do the explicit capture - because
17354         // it makes for cleaner diagnostics later.  This would purely be done
17355         // so that the diagnostic does not misleadingly claim that a variable
17356         // can not be captured by a lambda implicitly even though it is captured
17357         // explicitly.  Suggestion:
17358         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17359         //    at the function head
17360         //  - cache the StartingDeclContext - this must be a lambda
17361         //  - captureInLambda in the innermost lambda the variable.
17362       }
17363       return true;
17364     }
17365 
17366     FunctionScopesIndex--;
17367     DC = ParentDC;
17368     Explicit = false;
17369   } while (!VarDC->Equals(DC));
17370 
17371   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17372   // computing the type of the capture at each step, checking type-specific
17373   // requirements, and adding captures if requested.
17374   // If the variable had already been captured previously, we start capturing
17375   // at the lambda nested within that one.
17376   bool Invalid = false;
17377   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17378        ++I) {
17379     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17380 
17381     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17382     // certain types of variables (unnamed, variably modified types etc.)
17383     // so check for eligibility.
17384     if (!Invalid)
17385       Invalid =
17386           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17387 
17388     // After encountering an error, if we're actually supposed to capture, keep
17389     // capturing in nested contexts to suppress any follow-on diagnostics.
17390     if (Invalid && !BuildAndDiagnose)
17391       return true;
17392 
17393     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17394       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17395                                DeclRefType, Nested, *this, Invalid);
17396       Nested = true;
17397     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17398       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17399                                          CaptureType, DeclRefType, Nested,
17400                                          *this, Invalid);
17401       Nested = true;
17402     } else {
17403       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17404       Invalid =
17405           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17406                            DeclRefType, Nested, Kind, EllipsisLoc,
17407                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17408       Nested = true;
17409     }
17410 
17411     if (Invalid && !BuildAndDiagnose)
17412       return true;
17413   }
17414   return Invalid;
17415 }
17416 
17417 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17418                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17419   QualType CaptureType;
17420   QualType DeclRefType;
17421   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17422                             /*BuildAndDiagnose=*/true, CaptureType,
17423                             DeclRefType, nullptr);
17424 }
17425 
17426 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17427   QualType CaptureType;
17428   QualType DeclRefType;
17429   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17430                              /*BuildAndDiagnose=*/false, CaptureType,
17431                              DeclRefType, nullptr);
17432 }
17433 
17434 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17435   QualType CaptureType;
17436   QualType DeclRefType;
17437 
17438   // Determine whether we can capture this variable.
17439   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17440                          /*BuildAndDiagnose=*/false, CaptureType,
17441                          DeclRefType, nullptr))
17442     return QualType();
17443 
17444   return DeclRefType;
17445 }
17446 
17447 namespace {
17448 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17449 // The produced TemplateArgumentListInfo* points to data stored within this
17450 // object, so should only be used in contexts where the pointer will not be
17451 // used after the CopiedTemplateArgs object is destroyed.
17452 class CopiedTemplateArgs {
17453   bool HasArgs;
17454   TemplateArgumentListInfo TemplateArgStorage;
17455 public:
17456   template<typename RefExpr>
17457   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17458     if (HasArgs)
17459       E->copyTemplateArgumentsInto(TemplateArgStorage);
17460   }
17461   operator TemplateArgumentListInfo*()
17462 #ifdef __has_cpp_attribute
17463 #if __has_cpp_attribute(clang::lifetimebound)
17464   [[clang::lifetimebound]]
17465 #endif
17466 #endif
17467   {
17468     return HasArgs ? &TemplateArgStorage : nullptr;
17469   }
17470 };
17471 }
17472 
17473 /// Walk the set of potential results of an expression and mark them all as
17474 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17475 ///
17476 /// \return A new expression if we found any potential results, ExprEmpty() if
17477 ///         not, and ExprError() if we diagnosed an error.
17478 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17479                                                       NonOdrUseReason NOUR) {
17480   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17481   // an object that satisfies the requirements for appearing in a
17482   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17483   // is immediately applied."  This function handles the lvalue-to-rvalue
17484   // conversion part.
17485   //
17486   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17487   // transform it into the relevant kind of non-odr-use node and rebuild the
17488   // tree of nodes leading to it.
17489   //
17490   // This is a mini-TreeTransform that only transforms a restricted subset of
17491   // nodes (and only certain operands of them).
17492 
17493   // Rebuild a subexpression.
17494   auto Rebuild = [&](Expr *Sub) {
17495     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17496   };
17497 
17498   // Check whether a potential result satisfies the requirements of NOUR.
17499   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17500     // Any entity other than a VarDecl is always odr-used whenever it's named
17501     // in a potentially-evaluated expression.
17502     auto *VD = dyn_cast<VarDecl>(D);
17503     if (!VD)
17504       return true;
17505 
17506     // C++2a [basic.def.odr]p4:
17507     //   A variable x whose name appears as a potentially-evalauted expression
17508     //   e is odr-used by e unless
17509     //   -- x is a reference that is usable in constant expressions, or
17510     //   -- x is a variable of non-reference type that is usable in constant
17511     //      expressions and has no mutable subobjects, and e is an element of
17512     //      the set of potential results of an expression of
17513     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17514     //      conversion is applied, or
17515     //   -- x is a variable of non-reference type, and e is an element of the
17516     //      set of potential results of a discarded-value expression to which
17517     //      the lvalue-to-rvalue conversion is not applied
17518     //
17519     // We check the first bullet and the "potentially-evaluated" condition in
17520     // BuildDeclRefExpr. We check the type requirements in the second bullet
17521     // in CheckLValueToRValueConversionOperand below.
17522     switch (NOUR) {
17523     case NOUR_None:
17524     case NOUR_Unevaluated:
17525       llvm_unreachable("unexpected non-odr-use-reason");
17526 
17527     case NOUR_Constant:
17528       // Constant references were handled when they were built.
17529       if (VD->getType()->isReferenceType())
17530         return true;
17531       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17532         if (RD->hasMutableFields())
17533           return true;
17534       if (!VD->isUsableInConstantExpressions(S.Context))
17535         return true;
17536       break;
17537 
17538     case NOUR_Discarded:
17539       if (VD->getType()->isReferenceType())
17540         return true;
17541       break;
17542     }
17543     return false;
17544   };
17545 
17546   // Mark that this expression does not constitute an odr-use.
17547   auto MarkNotOdrUsed = [&] {
17548     S.MaybeODRUseExprs.remove(E);
17549     if (LambdaScopeInfo *LSI = S.getCurLambda())
17550       LSI->markVariableExprAsNonODRUsed(E);
17551   };
17552 
17553   // C++2a [basic.def.odr]p2:
17554   //   The set of potential results of an expression e is defined as follows:
17555   switch (E->getStmtClass()) {
17556   //   -- If e is an id-expression, ...
17557   case Expr::DeclRefExprClass: {
17558     auto *DRE = cast<DeclRefExpr>(E);
17559     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17560       break;
17561 
17562     // Rebuild as a non-odr-use DeclRefExpr.
17563     MarkNotOdrUsed();
17564     return DeclRefExpr::Create(
17565         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17566         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17567         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17568         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17569   }
17570 
17571   case Expr::FunctionParmPackExprClass: {
17572     auto *FPPE = cast<FunctionParmPackExpr>(E);
17573     // If any of the declarations in the pack is odr-used, then the expression
17574     // as a whole constitutes an odr-use.
17575     for (VarDecl *D : *FPPE)
17576       if (IsPotentialResultOdrUsed(D))
17577         return ExprEmpty();
17578 
17579     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17580     // nothing cares about whether we marked this as an odr-use, but it might
17581     // be useful for non-compiler tools.
17582     MarkNotOdrUsed();
17583     break;
17584   }
17585 
17586   //   -- If e is a subscripting operation with an array operand...
17587   case Expr::ArraySubscriptExprClass: {
17588     auto *ASE = cast<ArraySubscriptExpr>(E);
17589     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17590     if (!OldBase->getType()->isArrayType())
17591       break;
17592     ExprResult Base = Rebuild(OldBase);
17593     if (!Base.isUsable())
17594       return Base;
17595     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17596     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17597     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17598     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17599                                      ASE->getRBracketLoc());
17600   }
17601 
17602   case Expr::MemberExprClass: {
17603     auto *ME = cast<MemberExpr>(E);
17604     // -- If e is a class member access expression [...] naming a non-static
17605     //    data member...
17606     if (isa<FieldDecl>(ME->getMemberDecl())) {
17607       ExprResult Base = Rebuild(ME->getBase());
17608       if (!Base.isUsable())
17609         return Base;
17610       return MemberExpr::Create(
17611           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17612           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17613           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17614           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17615           ME->getObjectKind(), ME->isNonOdrUse());
17616     }
17617 
17618     if (ME->getMemberDecl()->isCXXInstanceMember())
17619       break;
17620 
17621     // -- If e is a class member access expression naming a static data member,
17622     //    ...
17623     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17624       break;
17625 
17626     // Rebuild as a non-odr-use MemberExpr.
17627     MarkNotOdrUsed();
17628     return MemberExpr::Create(
17629         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17630         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17631         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17632         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17633     return ExprEmpty();
17634   }
17635 
17636   case Expr::BinaryOperatorClass: {
17637     auto *BO = cast<BinaryOperator>(E);
17638     Expr *LHS = BO->getLHS();
17639     Expr *RHS = BO->getRHS();
17640     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17641     if (BO->getOpcode() == BO_PtrMemD) {
17642       ExprResult Sub = Rebuild(LHS);
17643       if (!Sub.isUsable())
17644         return Sub;
17645       LHS = Sub.get();
17646     //   -- If e is a comma expression, ...
17647     } else if (BO->getOpcode() == BO_Comma) {
17648       ExprResult Sub = Rebuild(RHS);
17649       if (!Sub.isUsable())
17650         return Sub;
17651       RHS = Sub.get();
17652     } else {
17653       break;
17654     }
17655     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17656                         LHS, RHS);
17657   }
17658 
17659   //   -- If e has the form (e1)...
17660   case Expr::ParenExprClass: {
17661     auto *PE = cast<ParenExpr>(E);
17662     ExprResult Sub = Rebuild(PE->getSubExpr());
17663     if (!Sub.isUsable())
17664       return Sub;
17665     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17666   }
17667 
17668   //   -- If e is a glvalue conditional expression, ...
17669   // We don't apply this to a binary conditional operator. FIXME: Should we?
17670   case Expr::ConditionalOperatorClass: {
17671     auto *CO = cast<ConditionalOperator>(E);
17672     ExprResult LHS = Rebuild(CO->getLHS());
17673     if (LHS.isInvalid())
17674       return ExprError();
17675     ExprResult RHS = Rebuild(CO->getRHS());
17676     if (RHS.isInvalid())
17677       return ExprError();
17678     if (!LHS.isUsable() && !RHS.isUsable())
17679       return ExprEmpty();
17680     if (!LHS.isUsable())
17681       LHS = CO->getLHS();
17682     if (!RHS.isUsable())
17683       RHS = CO->getRHS();
17684     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17685                                 CO->getCond(), LHS.get(), RHS.get());
17686   }
17687 
17688   // [Clang extension]
17689   //   -- If e has the form __extension__ e1...
17690   case Expr::UnaryOperatorClass: {
17691     auto *UO = cast<UnaryOperator>(E);
17692     if (UO->getOpcode() != UO_Extension)
17693       break;
17694     ExprResult Sub = Rebuild(UO->getSubExpr());
17695     if (!Sub.isUsable())
17696       return Sub;
17697     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17698                           Sub.get());
17699   }
17700 
17701   // [Clang extension]
17702   //   -- If e has the form _Generic(...), the set of potential results is the
17703   //      union of the sets of potential results of the associated expressions.
17704   case Expr::GenericSelectionExprClass: {
17705     auto *GSE = cast<GenericSelectionExpr>(E);
17706 
17707     SmallVector<Expr *, 4> AssocExprs;
17708     bool AnyChanged = false;
17709     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17710       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17711       if (AssocExpr.isInvalid())
17712         return ExprError();
17713       if (AssocExpr.isUsable()) {
17714         AssocExprs.push_back(AssocExpr.get());
17715         AnyChanged = true;
17716       } else {
17717         AssocExprs.push_back(OrigAssocExpr);
17718       }
17719     }
17720 
17721     return AnyChanged ? S.CreateGenericSelectionExpr(
17722                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17723                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17724                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17725                       : ExprEmpty();
17726   }
17727 
17728   // [Clang extension]
17729   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17730   //      results is the union of the sets of potential results of the
17731   //      second and third subexpressions.
17732   case Expr::ChooseExprClass: {
17733     auto *CE = cast<ChooseExpr>(E);
17734 
17735     ExprResult LHS = Rebuild(CE->getLHS());
17736     if (LHS.isInvalid())
17737       return ExprError();
17738 
17739     ExprResult RHS = Rebuild(CE->getLHS());
17740     if (RHS.isInvalid())
17741       return ExprError();
17742 
17743     if (!LHS.get() && !RHS.get())
17744       return ExprEmpty();
17745     if (!LHS.isUsable())
17746       LHS = CE->getLHS();
17747     if (!RHS.isUsable())
17748       RHS = CE->getRHS();
17749 
17750     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17751                              RHS.get(), CE->getRParenLoc());
17752   }
17753 
17754   // Step through non-syntactic nodes.
17755   case Expr::ConstantExprClass: {
17756     auto *CE = cast<ConstantExpr>(E);
17757     ExprResult Sub = Rebuild(CE->getSubExpr());
17758     if (!Sub.isUsable())
17759       return Sub;
17760     return ConstantExpr::Create(S.Context, Sub.get());
17761   }
17762 
17763   // We could mostly rely on the recursive rebuilding to rebuild implicit
17764   // casts, but not at the top level, so rebuild them here.
17765   case Expr::ImplicitCastExprClass: {
17766     auto *ICE = cast<ImplicitCastExpr>(E);
17767     // Only step through the narrow set of cast kinds we expect to encounter.
17768     // Anything else suggests we've left the region in which potential results
17769     // can be found.
17770     switch (ICE->getCastKind()) {
17771     case CK_NoOp:
17772     case CK_DerivedToBase:
17773     case CK_UncheckedDerivedToBase: {
17774       ExprResult Sub = Rebuild(ICE->getSubExpr());
17775       if (!Sub.isUsable())
17776         return Sub;
17777       CXXCastPath Path(ICE->path());
17778       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17779                                  ICE->getValueKind(), &Path);
17780     }
17781 
17782     default:
17783       break;
17784     }
17785     break;
17786   }
17787 
17788   default:
17789     break;
17790   }
17791 
17792   // Can't traverse through this node. Nothing to do.
17793   return ExprEmpty();
17794 }
17795 
17796 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17797   // Check whether the operand is or contains an object of non-trivial C union
17798   // type.
17799   if (E->getType().isVolatileQualified() &&
17800       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17801        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17802     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17803                           Sema::NTCUC_LValueToRValueVolatile,
17804                           NTCUK_Destruct|NTCUK_Copy);
17805 
17806   // C++2a [basic.def.odr]p4:
17807   //   [...] an expression of non-volatile-qualified non-class type to which
17808   //   the lvalue-to-rvalue conversion is applied [...]
17809   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17810     return E;
17811 
17812   ExprResult Result =
17813       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17814   if (Result.isInvalid())
17815     return ExprError();
17816   return Result.get() ? Result : E;
17817 }
17818 
17819 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17820   Res = CorrectDelayedTyposInExpr(Res);
17821 
17822   if (!Res.isUsable())
17823     return Res;
17824 
17825   // If a constant-expression is a reference to a variable where we delay
17826   // deciding whether it is an odr-use, just assume we will apply the
17827   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17828   // (a non-type template argument), we have special handling anyway.
17829   return CheckLValueToRValueConversionOperand(Res.get());
17830 }
17831 
17832 void Sema::CleanupVarDeclMarking() {
17833   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17834   // call.
17835   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17836   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17837 
17838   for (Expr *E : LocalMaybeODRUseExprs) {
17839     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17840       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17841                          DRE->getLocation(), *this);
17842     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17843       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17844                          *this);
17845     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17846       for (VarDecl *VD : *FP)
17847         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17848     } else {
17849       llvm_unreachable("Unexpected expression");
17850     }
17851   }
17852 
17853   assert(MaybeODRUseExprs.empty() &&
17854          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17855 }
17856 
17857 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17858                                     VarDecl *Var, Expr *E) {
17859   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17860           isa<FunctionParmPackExpr>(E)) &&
17861          "Invalid Expr argument to DoMarkVarDeclReferenced");
17862   Var->setReferenced();
17863 
17864   if (Var->isInvalidDecl())
17865     return;
17866 
17867   auto *MSI = Var->getMemberSpecializationInfo();
17868   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17869                                        : Var->getTemplateSpecializationKind();
17870 
17871   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17872   bool UsableInConstantExpr =
17873       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17874 
17875   // C++20 [expr.const]p12:
17876   //   A variable [...] is needed for constant evaluation if it is [...] a
17877   //   variable whose name appears as a potentially constant evaluated
17878   //   expression that is either a contexpr variable or is of non-volatile
17879   //   const-qualified integral type or of reference type
17880   bool NeededForConstantEvaluation =
17881       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17882 
17883   bool NeedDefinition =
17884       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17885 
17886   VarTemplateSpecializationDecl *VarSpec =
17887       dyn_cast<VarTemplateSpecializationDecl>(Var);
17888   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17889          "Can't instantiate a partial template specialization.");
17890 
17891   // If this might be a member specialization of a static data member, check
17892   // the specialization is visible. We already did the checks for variable
17893   // template specializations when we created them.
17894   if (NeedDefinition && TSK != TSK_Undeclared &&
17895       !isa<VarTemplateSpecializationDecl>(Var))
17896     SemaRef.checkSpecializationVisibility(Loc, Var);
17897 
17898   // Perform implicit instantiation of static data members, static data member
17899   // templates of class templates, and variable template specializations. Delay
17900   // instantiations of variable templates, except for those that could be used
17901   // in a constant expression.
17902   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17903     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17904     // instantiation declaration if a variable is usable in a constant
17905     // expression (among other cases).
17906     bool TryInstantiating =
17907         TSK == TSK_ImplicitInstantiation ||
17908         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17909 
17910     if (TryInstantiating) {
17911       SourceLocation PointOfInstantiation =
17912           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17913       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17914       if (FirstInstantiation) {
17915         PointOfInstantiation = Loc;
17916         if (MSI)
17917           MSI->setPointOfInstantiation(PointOfInstantiation);
17918         else
17919           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17920       }
17921 
17922       bool InstantiationDependent = false;
17923       bool IsNonDependent =
17924           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17925                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17926                   : true;
17927 
17928       // Do not instantiate specializations that are still type-dependent.
17929       if (IsNonDependent) {
17930         if (UsableInConstantExpr) {
17931           // Do not defer instantiations of variables that could be used in a
17932           // constant expression.
17933           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17934             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17935           });
17936         } else if (FirstInstantiation ||
17937                    isa<VarTemplateSpecializationDecl>(Var)) {
17938           // FIXME: For a specialization of a variable template, we don't
17939           // distinguish between "declaration and type implicitly instantiated"
17940           // and "implicit instantiation of definition requested", so we have
17941           // no direct way to avoid enqueueing the pending instantiation
17942           // multiple times.
17943           SemaRef.PendingInstantiations
17944               .push_back(std::make_pair(Var, PointOfInstantiation));
17945         }
17946       }
17947     }
17948   }
17949 
17950   // C++2a [basic.def.odr]p4:
17951   //   A variable x whose name appears as a potentially-evaluated expression e
17952   //   is odr-used by e unless
17953   //   -- x is a reference that is usable in constant expressions
17954   //   -- x is a variable of non-reference type that is usable in constant
17955   //      expressions and has no mutable subobjects [FIXME], and e is an
17956   //      element of the set of potential results of an expression of
17957   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17958   //      conversion is applied
17959   //   -- x is a variable of non-reference type, and e is an element of the set
17960   //      of potential results of a discarded-value expression to which the
17961   //      lvalue-to-rvalue conversion is not applied [FIXME]
17962   //
17963   // We check the first part of the second bullet here, and
17964   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17965   // FIXME: To get the third bullet right, we need to delay this even for
17966   // variables that are not usable in constant expressions.
17967 
17968   // If we already know this isn't an odr-use, there's nothing more to do.
17969   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17970     if (DRE->isNonOdrUse())
17971       return;
17972   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17973     if (ME->isNonOdrUse())
17974       return;
17975 
17976   switch (OdrUse) {
17977   case OdrUseContext::None:
17978     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17979            "missing non-odr-use marking for unevaluated decl ref");
17980     break;
17981 
17982   case OdrUseContext::FormallyOdrUsed:
17983     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17984     // behavior.
17985     break;
17986 
17987   case OdrUseContext::Used:
17988     // If we might later find that this expression isn't actually an odr-use,
17989     // delay the marking.
17990     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17991       SemaRef.MaybeODRUseExprs.insert(E);
17992     else
17993       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17994     break;
17995 
17996   case OdrUseContext::Dependent:
17997     // If this is a dependent context, we don't need to mark variables as
17998     // odr-used, but we may still need to track them for lambda capture.
17999     // FIXME: Do we also need to do this inside dependent typeid expressions
18000     // (which are modeled as unevaluated at this point)?
18001     const bool RefersToEnclosingScope =
18002         (SemaRef.CurContext != Var->getDeclContext() &&
18003          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18004     if (RefersToEnclosingScope) {
18005       LambdaScopeInfo *const LSI =
18006           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18007       if (LSI && (!LSI->CallOperator ||
18008                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18009         // If a variable could potentially be odr-used, defer marking it so
18010         // until we finish analyzing the full expression for any
18011         // lvalue-to-rvalue
18012         // or discarded value conversions that would obviate odr-use.
18013         // Add it to the list of potential captures that will be analyzed
18014         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18015         // unless the variable is a reference that was initialized by a constant
18016         // expression (this will never need to be captured or odr-used).
18017         //
18018         // FIXME: We can simplify this a lot after implementing P0588R1.
18019         assert(E && "Capture variable should be used in an expression.");
18020         if (!Var->getType()->isReferenceType() ||
18021             !Var->isUsableInConstantExpressions(SemaRef.Context))
18022           LSI->addPotentialCapture(E->IgnoreParens());
18023       }
18024     }
18025     break;
18026   }
18027 }
18028 
18029 /// Mark a variable referenced, and check whether it is odr-used
18030 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18031 /// used directly for normal expressions referring to VarDecl.
18032 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18033   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18034 }
18035 
18036 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18037                                Decl *D, Expr *E, bool MightBeOdrUse) {
18038   if (SemaRef.isInOpenMPDeclareTargetContext())
18039     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18040 
18041   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18042     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18043     return;
18044   }
18045 
18046   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18047 
18048   // If this is a call to a method via a cast, also mark the method in the
18049   // derived class used in case codegen can devirtualize the call.
18050   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18051   if (!ME)
18052     return;
18053   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18054   if (!MD)
18055     return;
18056   // Only attempt to devirtualize if this is truly a virtual call.
18057   bool IsVirtualCall = MD->isVirtual() &&
18058                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18059   if (!IsVirtualCall)
18060     return;
18061 
18062   // If it's possible to devirtualize the call, mark the called function
18063   // referenced.
18064   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18065       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18066   if (DM)
18067     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18068 }
18069 
18070 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18071 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18072   // TODO: update this with DR# once a defect report is filed.
18073   // C++11 defect. The address of a pure member should not be an ODR use, even
18074   // if it's a qualified reference.
18075   bool OdrUse = true;
18076   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18077     if (Method->isVirtual() &&
18078         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18079       OdrUse = false;
18080 
18081   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18082     if (!isConstantEvaluated() && FD->isConsteval() &&
18083         !RebuildingImmediateInvocation)
18084       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18085   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18086 }
18087 
18088 /// Perform reference-marking and odr-use handling for a MemberExpr.
18089 void Sema::MarkMemberReferenced(MemberExpr *E) {
18090   // C++11 [basic.def.odr]p2:
18091   //   A non-overloaded function whose name appears as a potentially-evaluated
18092   //   expression or a member of a set of candidate functions, if selected by
18093   //   overload resolution when referred to from a potentially-evaluated
18094   //   expression, is odr-used, unless it is a pure virtual function and its
18095   //   name is not explicitly qualified.
18096   bool MightBeOdrUse = true;
18097   if (E->performsVirtualDispatch(getLangOpts())) {
18098     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18099       if (Method->isPure())
18100         MightBeOdrUse = false;
18101   }
18102   SourceLocation Loc =
18103       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18104   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18105 }
18106 
18107 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18108 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18109   for (VarDecl *VD : *E)
18110     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18111 }
18112 
18113 /// Perform marking for a reference to an arbitrary declaration.  It
18114 /// marks the declaration referenced, and performs odr-use checking for
18115 /// functions and variables. This method should not be used when building a
18116 /// normal expression which refers to a variable.
18117 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18118                                  bool MightBeOdrUse) {
18119   if (MightBeOdrUse) {
18120     if (auto *VD = dyn_cast<VarDecl>(D)) {
18121       MarkVariableReferenced(Loc, VD);
18122       return;
18123     }
18124   }
18125   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18126     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18127     return;
18128   }
18129   D->setReferenced();
18130 }
18131 
18132 namespace {
18133   // Mark all of the declarations used by a type as referenced.
18134   // FIXME: Not fully implemented yet! We need to have a better understanding
18135   // of when we're entering a context we should not recurse into.
18136   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18137   // TreeTransforms rebuilding the type in a new context. Rather than
18138   // duplicating the TreeTransform logic, we should consider reusing it here.
18139   // Currently that causes problems when rebuilding LambdaExprs.
18140   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18141     Sema &S;
18142     SourceLocation Loc;
18143 
18144   public:
18145     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18146 
18147     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18148 
18149     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18150   };
18151 }
18152 
18153 bool MarkReferencedDecls::TraverseTemplateArgument(
18154     const TemplateArgument &Arg) {
18155   {
18156     // A non-type template argument is a constant-evaluated context.
18157     EnterExpressionEvaluationContext Evaluated(
18158         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18159     if (Arg.getKind() == TemplateArgument::Declaration) {
18160       if (Decl *D = Arg.getAsDecl())
18161         S.MarkAnyDeclReferenced(Loc, D, true);
18162     } else if (Arg.getKind() == TemplateArgument::Expression) {
18163       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18164     }
18165   }
18166 
18167   return Inherited::TraverseTemplateArgument(Arg);
18168 }
18169 
18170 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18171   MarkReferencedDecls Marker(*this, Loc);
18172   Marker.TraverseType(T);
18173 }
18174 
18175 namespace {
18176 /// Helper class that marks all of the declarations referenced by
18177 /// potentially-evaluated subexpressions as "referenced".
18178 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18179 public:
18180   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18181   bool SkipLocalVariables;
18182 
18183   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18184       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18185 
18186   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18187     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18188   }
18189 
18190   void VisitDeclRefExpr(DeclRefExpr *E) {
18191     // If we were asked not to visit local variables, don't.
18192     if (SkipLocalVariables) {
18193       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18194         if (VD->hasLocalStorage())
18195           return;
18196     }
18197     S.MarkDeclRefReferenced(E);
18198   }
18199 
18200   void VisitMemberExpr(MemberExpr *E) {
18201     S.MarkMemberReferenced(E);
18202     Visit(E->getBase());
18203   }
18204 };
18205 } // namespace
18206 
18207 /// Mark any declarations that appear within this expression or any
18208 /// potentially-evaluated subexpressions as "referenced".
18209 ///
18210 /// \param SkipLocalVariables If true, don't mark local variables as
18211 /// 'referenced'.
18212 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18213                                             bool SkipLocalVariables) {
18214   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18215 }
18216 
18217 /// Emit a diagnostic that describes an effect on the run-time behavior
18218 /// of the program being compiled.
18219 ///
18220 /// This routine emits the given diagnostic when the code currently being
18221 /// type-checked is "potentially evaluated", meaning that there is a
18222 /// possibility that the code will actually be executable. Code in sizeof()
18223 /// expressions, code used only during overload resolution, etc., are not
18224 /// potentially evaluated. This routine will suppress such diagnostics or,
18225 /// in the absolutely nutty case of potentially potentially evaluated
18226 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18227 /// later.
18228 ///
18229 /// This routine should be used for all diagnostics that describe the run-time
18230 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18231 /// Failure to do so will likely result in spurious diagnostics or failures
18232 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18233 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18234                                const PartialDiagnostic &PD) {
18235   switch (ExprEvalContexts.back().Context) {
18236   case ExpressionEvaluationContext::Unevaluated:
18237   case ExpressionEvaluationContext::UnevaluatedList:
18238   case ExpressionEvaluationContext::UnevaluatedAbstract:
18239   case ExpressionEvaluationContext::DiscardedStatement:
18240     // The argument will never be evaluated, so don't complain.
18241     break;
18242 
18243   case ExpressionEvaluationContext::ConstantEvaluated:
18244     // Relevant diagnostics should be produced by constant evaluation.
18245     break;
18246 
18247   case ExpressionEvaluationContext::PotentiallyEvaluated:
18248   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18249     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18250       FunctionScopes.back()->PossiblyUnreachableDiags.
18251         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18252       return true;
18253     }
18254 
18255     // The initializer of a constexpr variable or of the first declaration of a
18256     // static data member is not syntactically a constant evaluated constant,
18257     // but nonetheless is always required to be a constant expression, so we
18258     // can skip diagnosing.
18259     // FIXME: Using the mangling context here is a hack.
18260     if (auto *VD = dyn_cast_or_null<VarDecl>(
18261             ExprEvalContexts.back().ManglingContextDecl)) {
18262       if (VD->isConstexpr() ||
18263           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18264         break;
18265       // FIXME: For any other kind of variable, we should build a CFG for its
18266       // initializer and check whether the context in question is reachable.
18267     }
18268 
18269     Diag(Loc, PD);
18270     return true;
18271   }
18272 
18273   return false;
18274 }
18275 
18276 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18277                                const PartialDiagnostic &PD) {
18278   return DiagRuntimeBehavior(
18279       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18280 }
18281 
18282 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18283                                CallExpr *CE, FunctionDecl *FD) {
18284   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18285     return false;
18286 
18287   // If we're inside a decltype's expression, don't check for a valid return
18288   // type or construct temporaries until we know whether this is the last call.
18289   if (ExprEvalContexts.back().ExprContext ==
18290       ExpressionEvaluationContextRecord::EK_Decltype) {
18291     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18292     return false;
18293   }
18294 
18295   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18296     FunctionDecl *FD;
18297     CallExpr *CE;
18298 
18299   public:
18300     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18301       : FD(FD), CE(CE) { }
18302 
18303     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18304       if (!FD) {
18305         S.Diag(Loc, diag::err_call_incomplete_return)
18306           << T << CE->getSourceRange();
18307         return;
18308       }
18309 
18310       S.Diag(Loc, diag::err_call_function_incomplete_return)
18311           << CE->getSourceRange() << FD << T;
18312       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18313           << FD->getDeclName();
18314     }
18315   } Diagnoser(FD, CE);
18316 
18317   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18318     return true;
18319 
18320   return false;
18321 }
18322 
18323 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18324 // will prevent this condition from triggering, which is what we want.
18325 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18326   SourceLocation Loc;
18327 
18328   unsigned diagnostic = diag::warn_condition_is_assignment;
18329   bool IsOrAssign = false;
18330 
18331   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18332     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18333       return;
18334 
18335     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18336 
18337     // Greylist some idioms by putting them into a warning subcategory.
18338     if (ObjCMessageExpr *ME
18339           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18340       Selector Sel = ME->getSelector();
18341 
18342       // self = [<foo> init...]
18343       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18344         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18345 
18346       // <foo> = [<bar> nextObject]
18347       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18348         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18349     }
18350 
18351     Loc = Op->getOperatorLoc();
18352   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18353     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18354       return;
18355 
18356     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18357     Loc = Op->getOperatorLoc();
18358   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18359     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18360   else {
18361     // Not an assignment.
18362     return;
18363   }
18364 
18365   Diag(Loc, diagnostic) << E->getSourceRange();
18366 
18367   SourceLocation Open = E->getBeginLoc();
18368   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18369   Diag(Loc, diag::note_condition_assign_silence)
18370         << FixItHint::CreateInsertion(Open, "(")
18371         << FixItHint::CreateInsertion(Close, ")");
18372 
18373   if (IsOrAssign)
18374     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18375       << FixItHint::CreateReplacement(Loc, "!=");
18376   else
18377     Diag(Loc, diag::note_condition_assign_to_comparison)
18378       << FixItHint::CreateReplacement(Loc, "==");
18379 }
18380 
18381 /// Redundant parentheses over an equality comparison can indicate
18382 /// that the user intended an assignment used as condition.
18383 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18384   // Don't warn if the parens came from a macro.
18385   SourceLocation parenLoc = ParenE->getBeginLoc();
18386   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18387     return;
18388   // Don't warn for dependent expressions.
18389   if (ParenE->isTypeDependent())
18390     return;
18391 
18392   Expr *E = ParenE->IgnoreParens();
18393 
18394   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18395     if (opE->getOpcode() == BO_EQ &&
18396         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18397                                                            == Expr::MLV_Valid) {
18398       SourceLocation Loc = opE->getOperatorLoc();
18399 
18400       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18401       SourceRange ParenERange = ParenE->getSourceRange();
18402       Diag(Loc, diag::note_equality_comparison_silence)
18403         << FixItHint::CreateRemoval(ParenERange.getBegin())
18404         << FixItHint::CreateRemoval(ParenERange.getEnd());
18405       Diag(Loc, diag::note_equality_comparison_to_assign)
18406         << FixItHint::CreateReplacement(Loc, "=");
18407     }
18408 }
18409 
18410 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18411                                        bool IsConstexpr) {
18412   DiagnoseAssignmentAsCondition(E);
18413   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18414     DiagnoseEqualityWithExtraParens(parenE);
18415 
18416   ExprResult result = CheckPlaceholderExpr(E);
18417   if (result.isInvalid()) return ExprError();
18418   E = result.get();
18419 
18420   if (!E->isTypeDependent()) {
18421     if (getLangOpts().CPlusPlus)
18422       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18423 
18424     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18425     if (ERes.isInvalid())
18426       return ExprError();
18427     E = ERes.get();
18428 
18429     QualType T = E->getType();
18430     if (!T->isScalarType()) { // C99 6.8.4.1p1
18431       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18432         << T << E->getSourceRange();
18433       return ExprError();
18434     }
18435     CheckBoolLikeConversion(E, Loc);
18436   }
18437 
18438   return E;
18439 }
18440 
18441 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18442                                            Expr *SubExpr, ConditionKind CK) {
18443   // Empty conditions are valid in for-statements.
18444   if (!SubExpr)
18445     return ConditionResult();
18446 
18447   ExprResult Cond;
18448   switch (CK) {
18449   case ConditionKind::Boolean:
18450     Cond = CheckBooleanCondition(Loc, SubExpr);
18451     break;
18452 
18453   case ConditionKind::ConstexprIf:
18454     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18455     break;
18456 
18457   case ConditionKind::Switch:
18458     Cond = CheckSwitchCondition(Loc, SubExpr);
18459     break;
18460   }
18461   if (Cond.isInvalid()) {
18462     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18463                               {SubExpr});
18464     if (!Cond.get())
18465       return ConditionError();
18466   }
18467   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18468   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18469   if (!FullExpr.get())
18470     return ConditionError();
18471 
18472   return ConditionResult(*this, nullptr, FullExpr,
18473                          CK == ConditionKind::ConstexprIf);
18474 }
18475 
18476 namespace {
18477   /// A visitor for rebuilding a call to an __unknown_any expression
18478   /// to have an appropriate type.
18479   struct RebuildUnknownAnyFunction
18480     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18481 
18482     Sema &S;
18483 
18484     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18485 
18486     ExprResult VisitStmt(Stmt *S) {
18487       llvm_unreachable("unexpected statement!");
18488     }
18489 
18490     ExprResult VisitExpr(Expr *E) {
18491       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18492         << E->getSourceRange();
18493       return ExprError();
18494     }
18495 
18496     /// Rebuild an expression which simply semantically wraps another
18497     /// expression which it shares the type and value kind of.
18498     template <class T> ExprResult rebuildSugarExpr(T *E) {
18499       ExprResult SubResult = Visit(E->getSubExpr());
18500       if (SubResult.isInvalid()) return ExprError();
18501 
18502       Expr *SubExpr = SubResult.get();
18503       E->setSubExpr(SubExpr);
18504       E->setType(SubExpr->getType());
18505       E->setValueKind(SubExpr->getValueKind());
18506       assert(E->getObjectKind() == OK_Ordinary);
18507       return E;
18508     }
18509 
18510     ExprResult VisitParenExpr(ParenExpr *E) {
18511       return rebuildSugarExpr(E);
18512     }
18513 
18514     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18515       return rebuildSugarExpr(E);
18516     }
18517 
18518     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18519       ExprResult SubResult = Visit(E->getSubExpr());
18520       if (SubResult.isInvalid()) return ExprError();
18521 
18522       Expr *SubExpr = SubResult.get();
18523       E->setSubExpr(SubExpr);
18524       E->setType(S.Context.getPointerType(SubExpr->getType()));
18525       assert(E->getValueKind() == VK_RValue);
18526       assert(E->getObjectKind() == OK_Ordinary);
18527       return E;
18528     }
18529 
18530     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18531       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18532 
18533       E->setType(VD->getType());
18534 
18535       assert(E->getValueKind() == VK_RValue);
18536       if (S.getLangOpts().CPlusPlus &&
18537           !(isa<CXXMethodDecl>(VD) &&
18538             cast<CXXMethodDecl>(VD)->isInstance()))
18539         E->setValueKind(VK_LValue);
18540 
18541       return E;
18542     }
18543 
18544     ExprResult VisitMemberExpr(MemberExpr *E) {
18545       return resolveDecl(E, E->getMemberDecl());
18546     }
18547 
18548     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18549       return resolveDecl(E, E->getDecl());
18550     }
18551   };
18552 }
18553 
18554 /// Given a function expression of unknown-any type, try to rebuild it
18555 /// to have a function type.
18556 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18557   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18558   if (Result.isInvalid()) return ExprError();
18559   return S.DefaultFunctionArrayConversion(Result.get());
18560 }
18561 
18562 namespace {
18563   /// A visitor for rebuilding an expression of type __unknown_anytype
18564   /// into one which resolves the type directly on the referring
18565   /// expression.  Strict preservation of the original source
18566   /// structure is not a goal.
18567   struct RebuildUnknownAnyExpr
18568     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18569 
18570     Sema &S;
18571 
18572     /// The current destination type.
18573     QualType DestType;
18574 
18575     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18576       : S(S), DestType(CastType) {}
18577 
18578     ExprResult VisitStmt(Stmt *S) {
18579       llvm_unreachable("unexpected statement!");
18580     }
18581 
18582     ExprResult VisitExpr(Expr *E) {
18583       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18584         << E->getSourceRange();
18585       return ExprError();
18586     }
18587 
18588     ExprResult VisitCallExpr(CallExpr *E);
18589     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18590 
18591     /// Rebuild an expression which simply semantically wraps another
18592     /// expression which it shares the type and value kind of.
18593     template <class T> ExprResult rebuildSugarExpr(T *E) {
18594       ExprResult SubResult = Visit(E->getSubExpr());
18595       if (SubResult.isInvalid()) return ExprError();
18596       Expr *SubExpr = SubResult.get();
18597       E->setSubExpr(SubExpr);
18598       E->setType(SubExpr->getType());
18599       E->setValueKind(SubExpr->getValueKind());
18600       assert(E->getObjectKind() == OK_Ordinary);
18601       return E;
18602     }
18603 
18604     ExprResult VisitParenExpr(ParenExpr *E) {
18605       return rebuildSugarExpr(E);
18606     }
18607 
18608     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18609       return rebuildSugarExpr(E);
18610     }
18611 
18612     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18613       const PointerType *Ptr = DestType->getAs<PointerType>();
18614       if (!Ptr) {
18615         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18616           << E->getSourceRange();
18617         return ExprError();
18618       }
18619 
18620       if (isa<CallExpr>(E->getSubExpr())) {
18621         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18622           << E->getSourceRange();
18623         return ExprError();
18624       }
18625 
18626       assert(E->getValueKind() == VK_RValue);
18627       assert(E->getObjectKind() == OK_Ordinary);
18628       E->setType(DestType);
18629 
18630       // Build the sub-expression as if it were an object of the pointee type.
18631       DestType = Ptr->getPointeeType();
18632       ExprResult SubResult = Visit(E->getSubExpr());
18633       if (SubResult.isInvalid()) return ExprError();
18634       E->setSubExpr(SubResult.get());
18635       return E;
18636     }
18637 
18638     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18639 
18640     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18641 
18642     ExprResult VisitMemberExpr(MemberExpr *E) {
18643       return resolveDecl(E, E->getMemberDecl());
18644     }
18645 
18646     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18647       return resolveDecl(E, E->getDecl());
18648     }
18649   };
18650 }
18651 
18652 /// Rebuilds a call expression which yielded __unknown_anytype.
18653 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18654   Expr *CalleeExpr = E->getCallee();
18655 
18656   enum FnKind {
18657     FK_MemberFunction,
18658     FK_FunctionPointer,
18659     FK_BlockPointer
18660   };
18661 
18662   FnKind Kind;
18663   QualType CalleeType = CalleeExpr->getType();
18664   if (CalleeType == S.Context.BoundMemberTy) {
18665     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18666     Kind = FK_MemberFunction;
18667     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18668   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18669     CalleeType = Ptr->getPointeeType();
18670     Kind = FK_FunctionPointer;
18671   } else {
18672     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18673     Kind = FK_BlockPointer;
18674   }
18675   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18676 
18677   // Verify that this is a legal result type of a function.
18678   if (DestType->isArrayType() || DestType->isFunctionType()) {
18679     unsigned diagID = diag::err_func_returning_array_function;
18680     if (Kind == FK_BlockPointer)
18681       diagID = diag::err_block_returning_array_function;
18682 
18683     S.Diag(E->getExprLoc(), diagID)
18684       << DestType->isFunctionType() << DestType;
18685     return ExprError();
18686   }
18687 
18688   // Otherwise, go ahead and set DestType as the call's result.
18689   E->setType(DestType.getNonLValueExprType(S.Context));
18690   E->setValueKind(Expr::getValueKindForType(DestType));
18691   assert(E->getObjectKind() == OK_Ordinary);
18692 
18693   // Rebuild the function type, replacing the result type with DestType.
18694   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18695   if (Proto) {
18696     // __unknown_anytype(...) is a special case used by the debugger when
18697     // it has no idea what a function's signature is.
18698     //
18699     // We want to build this call essentially under the K&R
18700     // unprototyped rules, but making a FunctionNoProtoType in C++
18701     // would foul up all sorts of assumptions.  However, we cannot
18702     // simply pass all arguments as variadic arguments, nor can we
18703     // portably just call the function under a non-variadic type; see
18704     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18705     // However, it turns out that in practice it is generally safe to
18706     // call a function declared as "A foo(B,C,D);" under the prototype
18707     // "A foo(B,C,D,...);".  The only known exception is with the
18708     // Windows ABI, where any variadic function is implicitly cdecl
18709     // regardless of its normal CC.  Therefore we change the parameter
18710     // types to match the types of the arguments.
18711     //
18712     // This is a hack, but it is far superior to moving the
18713     // corresponding target-specific code from IR-gen to Sema/AST.
18714 
18715     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18716     SmallVector<QualType, 8> ArgTypes;
18717     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18718       ArgTypes.reserve(E->getNumArgs());
18719       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18720         Expr *Arg = E->getArg(i);
18721         QualType ArgType = Arg->getType();
18722         if (E->isLValue()) {
18723           ArgType = S.Context.getLValueReferenceType(ArgType);
18724         } else if (E->isXValue()) {
18725           ArgType = S.Context.getRValueReferenceType(ArgType);
18726         }
18727         ArgTypes.push_back(ArgType);
18728       }
18729       ParamTypes = ArgTypes;
18730     }
18731     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18732                                          Proto->getExtProtoInfo());
18733   } else {
18734     DestType = S.Context.getFunctionNoProtoType(DestType,
18735                                                 FnType->getExtInfo());
18736   }
18737 
18738   // Rebuild the appropriate pointer-to-function type.
18739   switch (Kind) {
18740   case FK_MemberFunction:
18741     // Nothing to do.
18742     break;
18743 
18744   case FK_FunctionPointer:
18745     DestType = S.Context.getPointerType(DestType);
18746     break;
18747 
18748   case FK_BlockPointer:
18749     DestType = S.Context.getBlockPointerType(DestType);
18750     break;
18751   }
18752 
18753   // Finally, we can recurse.
18754   ExprResult CalleeResult = Visit(CalleeExpr);
18755   if (!CalleeResult.isUsable()) return ExprError();
18756   E->setCallee(CalleeResult.get());
18757 
18758   // Bind a temporary if necessary.
18759   return S.MaybeBindToTemporary(E);
18760 }
18761 
18762 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18763   // Verify that this is a legal result type of a call.
18764   if (DestType->isArrayType() || DestType->isFunctionType()) {
18765     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18766       << DestType->isFunctionType() << DestType;
18767     return ExprError();
18768   }
18769 
18770   // Rewrite the method result type if available.
18771   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18772     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18773     Method->setReturnType(DestType);
18774   }
18775 
18776   // Change the type of the message.
18777   E->setType(DestType.getNonReferenceType());
18778   E->setValueKind(Expr::getValueKindForType(DestType));
18779 
18780   return S.MaybeBindToTemporary(E);
18781 }
18782 
18783 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18784   // The only case we should ever see here is a function-to-pointer decay.
18785   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18786     assert(E->getValueKind() == VK_RValue);
18787     assert(E->getObjectKind() == OK_Ordinary);
18788 
18789     E->setType(DestType);
18790 
18791     // Rebuild the sub-expression as the pointee (function) type.
18792     DestType = DestType->castAs<PointerType>()->getPointeeType();
18793 
18794     ExprResult Result = Visit(E->getSubExpr());
18795     if (!Result.isUsable()) return ExprError();
18796 
18797     E->setSubExpr(Result.get());
18798     return E;
18799   } else if (E->getCastKind() == CK_LValueToRValue) {
18800     assert(E->getValueKind() == VK_RValue);
18801     assert(E->getObjectKind() == OK_Ordinary);
18802 
18803     assert(isa<BlockPointerType>(E->getType()));
18804 
18805     E->setType(DestType);
18806 
18807     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18808     DestType = S.Context.getLValueReferenceType(DestType);
18809 
18810     ExprResult Result = Visit(E->getSubExpr());
18811     if (!Result.isUsable()) return ExprError();
18812 
18813     E->setSubExpr(Result.get());
18814     return E;
18815   } else {
18816     llvm_unreachable("Unhandled cast type!");
18817   }
18818 }
18819 
18820 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18821   ExprValueKind ValueKind = VK_LValue;
18822   QualType Type = DestType;
18823 
18824   // We know how to make this work for certain kinds of decls:
18825 
18826   //  - functions
18827   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18828     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18829       DestType = Ptr->getPointeeType();
18830       ExprResult Result = resolveDecl(E, VD);
18831       if (Result.isInvalid()) return ExprError();
18832       return S.ImpCastExprToType(Result.get(), Type,
18833                                  CK_FunctionToPointerDecay, VK_RValue);
18834     }
18835 
18836     if (!Type->isFunctionType()) {
18837       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18838         << VD << E->getSourceRange();
18839       return ExprError();
18840     }
18841     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18842       // We must match the FunctionDecl's type to the hack introduced in
18843       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18844       // type. See the lengthy commentary in that routine.
18845       QualType FDT = FD->getType();
18846       const FunctionType *FnType = FDT->castAs<FunctionType>();
18847       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18848       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18849       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18850         SourceLocation Loc = FD->getLocation();
18851         FunctionDecl *NewFD = FunctionDecl::Create(
18852             S.Context, FD->getDeclContext(), Loc, Loc,
18853             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18854             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18855             /*ConstexprKind*/ CSK_unspecified);
18856 
18857         if (FD->getQualifier())
18858           NewFD->setQualifierInfo(FD->getQualifierLoc());
18859 
18860         SmallVector<ParmVarDecl*, 16> Params;
18861         for (const auto &AI : FT->param_types()) {
18862           ParmVarDecl *Param =
18863             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18864           Param->setScopeInfo(0, Params.size());
18865           Params.push_back(Param);
18866         }
18867         NewFD->setParams(Params);
18868         DRE->setDecl(NewFD);
18869         VD = DRE->getDecl();
18870       }
18871     }
18872 
18873     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18874       if (MD->isInstance()) {
18875         ValueKind = VK_RValue;
18876         Type = S.Context.BoundMemberTy;
18877       }
18878 
18879     // Function references aren't l-values in C.
18880     if (!S.getLangOpts().CPlusPlus)
18881       ValueKind = VK_RValue;
18882 
18883   //  - variables
18884   } else if (isa<VarDecl>(VD)) {
18885     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18886       Type = RefTy->getPointeeType();
18887     } else if (Type->isFunctionType()) {
18888       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18889         << VD << E->getSourceRange();
18890       return ExprError();
18891     }
18892 
18893   //  - nothing else
18894   } else {
18895     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18896       << VD << E->getSourceRange();
18897     return ExprError();
18898   }
18899 
18900   // Modifying the declaration like this is friendly to IR-gen but
18901   // also really dangerous.
18902   VD->setType(DestType);
18903   E->setType(Type);
18904   E->setValueKind(ValueKind);
18905   return E;
18906 }
18907 
18908 /// Check a cast of an unknown-any type.  We intentionally only
18909 /// trigger this for C-style casts.
18910 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18911                                      Expr *CastExpr, CastKind &CastKind,
18912                                      ExprValueKind &VK, CXXCastPath &Path) {
18913   // The type we're casting to must be either void or complete.
18914   if (!CastType->isVoidType() &&
18915       RequireCompleteType(TypeRange.getBegin(), CastType,
18916                           diag::err_typecheck_cast_to_incomplete))
18917     return ExprError();
18918 
18919   // Rewrite the casted expression from scratch.
18920   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18921   if (!result.isUsable()) return ExprError();
18922 
18923   CastExpr = result.get();
18924   VK = CastExpr->getValueKind();
18925   CastKind = CK_NoOp;
18926 
18927   return CastExpr;
18928 }
18929 
18930 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18931   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18932 }
18933 
18934 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18935                                     Expr *arg, QualType &paramType) {
18936   // If the syntactic form of the argument is not an explicit cast of
18937   // any sort, just do default argument promotion.
18938   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18939   if (!castArg) {
18940     ExprResult result = DefaultArgumentPromotion(arg);
18941     if (result.isInvalid()) return ExprError();
18942     paramType = result.get()->getType();
18943     return result;
18944   }
18945 
18946   // Otherwise, use the type that was written in the explicit cast.
18947   assert(!arg->hasPlaceholderType());
18948   paramType = castArg->getTypeAsWritten();
18949 
18950   // Copy-initialize a parameter of that type.
18951   InitializedEntity entity =
18952     InitializedEntity::InitializeParameter(Context, paramType,
18953                                            /*consumed*/ false);
18954   return PerformCopyInitialization(entity, callLoc, arg);
18955 }
18956 
18957 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18958   Expr *orig = E;
18959   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18960   while (true) {
18961     E = E->IgnoreParenImpCasts();
18962     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18963       E = call->getCallee();
18964       diagID = diag::err_uncasted_call_of_unknown_any;
18965     } else {
18966       break;
18967     }
18968   }
18969 
18970   SourceLocation loc;
18971   NamedDecl *d;
18972   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18973     loc = ref->getLocation();
18974     d = ref->getDecl();
18975   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18976     loc = mem->getMemberLoc();
18977     d = mem->getMemberDecl();
18978   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18979     diagID = diag::err_uncasted_call_of_unknown_any;
18980     loc = msg->getSelectorStartLoc();
18981     d = msg->getMethodDecl();
18982     if (!d) {
18983       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18984         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18985         << orig->getSourceRange();
18986       return ExprError();
18987     }
18988   } else {
18989     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18990       << E->getSourceRange();
18991     return ExprError();
18992   }
18993 
18994   S.Diag(loc, diagID) << d << orig->getSourceRange();
18995 
18996   // Never recoverable.
18997   return ExprError();
18998 }
18999 
19000 /// Check for operands with placeholder types and complain if found.
19001 /// Returns ExprError() if there was an error and no recovery was possible.
19002 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19003   if (!getLangOpts().CPlusPlus) {
19004     // C cannot handle TypoExpr nodes on either side of a binop because it
19005     // doesn't handle dependent types properly, so make sure any TypoExprs have
19006     // been dealt with before checking the operands.
19007     ExprResult Result = CorrectDelayedTyposInExpr(E);
19008     if (!Result.isUsable()) return ExprError();
19009     E = Result.get();
19010   }
19011 
19012   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19013   if (!placeholderType) return E;
19014 
19015   switch (placeholderType->getKind()) {
19016 
19017   // Overloaded expressions.
19018   case BuiltinType::Overload: {
19019     // Try to resolve a single function template specialization.
19020     // This is obligatory.
19021     ExprResult Result = E;
19022     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19023       return Result;
19024 
19025     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19026     // leaves Result unchanged on failure.
19027     Result = E;
19028     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19029       return Result;
19030 
19031     // If that failed, try to recover with a call.
19032     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19033                          /*complain*/ true);
19034     return Result;
19035   }
19036 
19037   // Bound member functions.
19038   case BuiltinType::BoundMember: {
19039     ExprResult result = E;
19040     const Expr *BME = E->IgnoreParens();
19041     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19042     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19043     if (isa<CXXPseudoDestructorExpr>(BME)) {
19044       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19045     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19046       if (ME->getMemberNameInfo().getName().getNameKind() ==
19047           DeclarationName::CXXDestructorName)
19048         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19049     }
19050     tryToRecoverWithCall(result, PD,
19051                          /*complain*/ true);
19052     return result;
19053   }
19054 
19055   // ARC unbridged casts.
19056   case BuiltinType::ARCUnbridgedCast: {
19057     Expr *realCast = stripARCUnbridgedCast(E);
19058     diagnoseARCUnbridgedCast(realCast);
19059     return realCast;
19060   }
19061 
19062   // Expressions of unknown type.
19063   case BuiltinType::UnknownAny:
19064     return diagnoseUnknownAnyExpr(*this, E);
19065 
19066   // Pseudo-objects.
19067   case BuiltinType::PseudoObject:
19068     return checkPseudoObjectRValue(E);
19069 
19070   case BuiltinType::BuiltinFn: {
19071     // Accept __noop without parens by implicitly converting it to a call expr.
19072     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19073     if (DRE) {
19074       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19075       if (FD->getBuiltinID() == Builtin::BI__noop) {
19076         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19077                               CK_BuiltinFnToFnPtr)
19078                 .get();
19079         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19080                                 VK_RValue, SourceLocation(),
19081                                 FPOptionsOverride());
19082       }
19083     }
19084 
19085     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19086     return ExprError();
19087   }
19088 
19089   case BuiltinType::IncompleteMatrixIdx:
19090     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19091              ->getRowIdx()
19092              ->getBeginLoc(),
19093          diag::err_matrix_incomplete_index);
19094     return ExprError();
19095 
19096   // Expressions of unknown type.
19097   case BuiltinType::OMPArraySection:
19098     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19099     return ExprError();
19100 
19101   // Expressions of unknown type.
19102   case BuiltinType::OMPArrayShaping:
19103     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19104 
19105   case BuiltinType::OMPIterator:
19106     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19107 
19108   // Everything else should be impossible.
19109 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19110   case BuiltinType::Id:
19111 #include "clang/Basic/OpenCLImageTypes.def"
19112 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19113   case BuiltinType::Id:
19114 #include "clang/Basic/OpenCLExtensionTypes.def"
19115 #define SVE_TYPE(Name, Id, SingletonId) \
19116   case BuiltinType::Id:
19117 #include "clang/Basic/AArch64SVEACLETypes.def"
19118 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19119 #define PLACEHOLDER_TYPE(Id, SingletonId)
19120 #include "clang/AST/BuiltinTypes.def"
19121     break;
19122   }
19123 
19124   llvm_unreachable("invalid placeholder type!");
19125 }
19126 
19127 bool Sema::CheckCaseExpression(Expr *E) {
19128   if (E->isTypeDependent())
19129     return true;
19130   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19131     return E->getType()->isIntegralOrEnumerationType();
19132   return false;
19133 }
19134 
19135 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19136 ExprResult
19137 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19138   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19139          "Unknown Objective-C Boolean value!");
19140   QualType BoolT = Context.ObjCBuiltinBoolTy;
19141   if (!Context.getBOOLDecl()) {
19142     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19143                         Sema::LookupOrdinaryName);
19144     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19145       NamedDecl *ND = Result.getFoundDecl();
19146       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19147         Context.setBOOLDecl(TD);
19148     }
19149   }
19150   if (Context.getBOOLDecl())
19151     BoolT = Context.getBOOLType();
19152   return new (Context)
19153       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19154 }
19155 
19156 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19157     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19158     SourceLocation RParen) {
19159 
19160   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19161 
19162   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19163     return Spec.getPlatform() == Platform;
19164   });
19165 
19166   VersionTuple Version;
19167   if (Spec != AvailSpecs.end())
19168     Version = Spec->getVersion();
19169 
19170   // The use of `@available` in the enclosing function should be analyzed to
19171   // warn when it's used inappropriately (i.e. not if(@available)).
19172   if (getCurFunctionOrMethodDecl())
19173     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19174   else if (getCurBlock() || getCurLambda())
19175     getCurFunction()->HasPotentialAvailabilityViolations = true;
19176 
19177   return new (Context)
19178       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19179 }
19180 
19181 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19182                                     ArrayRef<Expr *> SubExprs, QualType T) {
19183   if (!Context.getLangOpts().RecoveryAST)
19184     return ExprError();
19185 
19186   if (isSFINAEContext())
19187     return ExprError();
19188 
19189   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19190     // We don't know the concrete type, fallback to dependent type.
19191     T = Context.DependentTy;
19192   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19193 }
19194