1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296   }
297 
298   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
299     // Lambdas are only default-constructible or assignable in C++2a onwards.
300     if (MD->getParent()->isLambda() &&
301         ((isa<CXXConstructorDecl>(MD) &&
302           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
303          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
304       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
305         << !isa<CXXConstructorDecl>(MD);
306     }
307   }
308 
309   auto getReferencedObjCProp = [](const NamedDecl *D) ->
310                                       const ObjCPropertyDecl * {
311     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
312       return MD->findPropertyDecl();
313     return nullptr;
314   };
315   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
316     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
317       return true;
318   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
319       return true;
320   }
321 
322   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
323   // Only the variables omp_in and omp_out are allowed in the combiner.
324   // Only the variables omp_priv and omp_orig are allowed in the
325   // initializer-clause.
326   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
327   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
328       isa<VarDecl>(D)) {
329     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
330         << getCurFunction()->HasOMPDeclareReductionCombiner;
331     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
332     return true;
333   }
334 
335   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
336   //  List-items in map clauses on this construct may only refer to the declared
337   //  variable var and entities that could be referenced by a procedure defined
338   //  at the same location
339   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
340   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
341       isa<VarDecl>(D)) {
342     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
343         << DMD->getVarName().getAsString();
344     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
345     return true;
346   }
347 
348   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
349                              AvoidPartialAvailabilityChecks, ClassReceiver);
350 
351   DiagnoseUnusedOfDecl(*this, D, Loc);
352 
353   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
354 
355   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
356       !isUnevaluatedContext()) {
357     // C++ [expr.prim.req.nested] p3
358     //   A local parameter shall only appear as an unevaluated operand
359     //   (Clause 8) within the constraint-expression.
360     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
361         << D;
362     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
363     return true;
364   }
365 
366   return false;
367 }
368 
369 /// DiagnoseSentinelCalls - This routine checks whether a call or
370 /// message-send is to a declaration with the sentinel attribute, and
371 /// if so, it checks that the requirements of the sentinel are
372 /// satisfied.
373 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
374                                  ArrayRef<Expr *> Args) {
375   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
376   if (!attr)
377     return;
378 
379   // The number of formal parameters of the declaration.
380   unsigned numFormalParams;
381 
382   // The kind of declaration.  This is also an index into a %select in
383   // the diagnostic.
384   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
385 
386   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
387     numFormalParams = MD->param_size();
388     calleeType = CT_Method;
389   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
390     numFormalParams = FD->param_size();
391     calleeType = CT_Function;
392   } else if (isa<VarDecl>(D)) {
393     QualType type = cast<ValueDecl>(D)->getType();
394     const FunctionType *fn = nullptr;
395     if (const PointerType *ptr = type->getAs<PointerType>()) {
396       fn = ptr->getPointeeType()->getAs<FunctionType>();
397       if (!fn) return;
398       calleeType = CT_Function;
399     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
400       fn = ptr->getPointeeType()->castAs<FunctionType>();
401       calleeType = CT_Block;
402     } else {
403       return;
404     }
405 
406     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
407       numFormalParams = proto->getNumParams();
408     } else {
409       numFormalParams = 0;
410     }
411   } else {
412     return;
413   }
414 
415   // "nullPos" is the number of formal parameters at the end which
416   // effectively count as part of the variadic arguments.  This is
417   // useful if you would prefer to not have *any* formal parameters,
418   // but the language forces you to have at least one.
419   unsigned nullPos = attr->getNullPos();
420   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
421   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
422 
423   // The number of arguments which should follow the sentinel.
424   unsigned numArgsAfterSentinel = attr->getSentinel();
425 
426   // If there aren't enough arguments for all the formal parameters,
427   // the sentinel, and the args after the sentinel, complain.
428   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
429     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
430     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
431     return;
432   }
433 
434   // Otherwise, find the sentinel expression.
435   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
436   if (!sentinelExpr) return;
437   if (sentinelExpr->isValueDependent()) return;
438   if (Context.isSentinelNullExpr(sentinelExpr)) return;
439 
440   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
441   // or 'NULL' if those are actually defined in the context.  Only use
442   // 'nil' for ObjC methods, where it's much more likely that the
443   // variadic arguments form a list of object pointers.
444   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
445   std::string NullValue;
446   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
447     NullValue = "nil";
448   else if (getLangOpts().CPlusPlus11)
449     NullValue = "nullptr";
450   else if (PP.isMacroDefined("NULL"))
451     NullValue = "NULL";
452   else
453     NullValue = "(void*) 0";
454 
455   if (MissingNilLoc.isInvalid())
456     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
457   else
458     Diag(MissingNilLoc, diag::warn_missing_sentinel)
459       << int(calleeType)
460       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
461   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
462 }
463 
464 SourceRange Sema::getExprRange(Expr *E) const {
465   return E ? E->getSourceRange() : SourceRange();
466 }
467 
468 //===----------------------------------------------------------------------===//
469 //  Standard Promotions and Conversions
470 //===----------------------------------------------------------------------===//
471 
472 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
473 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
474   // Handle any placeholder expressions which made it here.
475   if (E->getType()->isPlaceholderType()) {
476     ExprResult result = CheckPlaceholderExpr(E);
477     if (result.isInvalid()) return ExprError();
478     E = result.get();
479   }
480 
481   QualType Ty = E->getType();
482   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
483 
484   if (Ty->isFunctionType()) {
485     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
486       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
487         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
488           return ExprError();
489 
490     E = ImpCastExprToType(E, Context.getPointerType(Ty),
491                           CK_FunctionToPointerDecay).get();
492   } else if (Ty->isArrayType()) {
493     // In C90 mode, arrays only promote to pointers if the array expression is
494     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
495     // type 'array of type' is converted to an expression that has type 'pointer
496     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
497     // that has type 'array of type' ...".  The relevant change is "an lvalue"
498     // (C90) to "an expression" (C99).
499     //
500     // C++ 4.2p1:
501     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
502     // T" can be converted to an rvalue of type "pointer to T".
503     //
504     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
505       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
506                             CK_ArrayToPointerDecay).get();
507   }
508   return E;
509 }
510 
511 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
512   // Check to see if we are dereferencing a null pointer.  If so,
513   // and if not volatile-qualified, this is undefined behavior that the
514   // optimizer will delete, so warn about it.  People sometimes try to use this
515   // to get a deterministic trap and are surprised by clang's behavior.  This
516   // only handles the pattern "*null", which is a very syntactic check.
517   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
518   if (UO && UO->getOpcode() == UO_Deref &&
519       UO->getSubExpr()->getType()->isPointerType()) {
520     const LangAS AS =
521         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
522     if ((!isTargetAddressSpace(AS) ||
523          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
524         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
525             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
526         !UO->getType().isVolatileQualified()) {
527       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
528                             S.PDiag(diag::warn_indirection_through_null)
529                                 << UO->getSubExpr()->getSourceRange());
530       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
531                             S.PDiag(diag::note_indirection_through_null));
532     }
533   }
534 }
535 
536 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
537                                     SourceLocation AssignLoc,
538                                     const Expr* RHS) {
539   const ObjCIvarDecl *IV = OIRE->getDecl();
540   if (!IV)
541     return;
542 
543   DeclarationName MemberName = IV->getDeclName();
544   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
545   if (!Member || !Member->isStr("isa"))
546     return;
547 
548   const Expr *Base = OIRE->getBase();
549   QualType BaseType = Base->getType();
550   if (OIRE->isArrow())
551     BaseType = BaseType->getPointeeType();
552   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
553     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
554       ObjCInterfaceDecl *ClassDeclared = nullptr;
555       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
556       if (!ClassDeclared->getSuperClass()
557           && (*ClassDeclared->ivar_begin()) == IV) {
558         if (RHS) {
559           NamedDecl *ObjectSetClass =
560             S.LookupSingleName(S.TUScope,
561                                &S.Context.Idents.get("object_setClass"),
562                                SourceLocation(), S.LookupOrdinaryName);
563           if (ObjectSetClass) {
564             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
565             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
566                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
567                                               "object_setClass(")
568                 << FixItHint::CreateReplacement(
569                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
570                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
571           }
572           else
573             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
574         } else {
575           NamedDecl *ObjectGetClass =
576             S.LookupSingleName(S.TUScope,
577                                &S.Context.Idents.get("object_getClass"),
578                                SourceLocation(), S.LookupOrdinaryName);
579           if (ObjectGetClass)
580             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
581                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
582                                               "object_getClass(")
583                 << FixItHint::CreateReplacement(
584                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
587         }
588         S.Diag(IV->getLocation(), diag::note_ivar_decl);
589       }
590     }
591 }
592 
593 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
594   // Handle any placeholder expressions which made it here.
595   if (E->getType()->isPlaceholderType()) {
596     ExprResult result = CheckPlaceholderExpr(E);
597     if (result.isInvalid()) return ExprError();
598     E = result.get();
599   }
600 
601   // C++ [conv.lval]p1:
602   //   A glvalue of a non-function, non-array type T can be
603   //   converted to a prvalue.
604   if (!E->isGLValue()) return E;
605 
606   QualType T = E->getType();
607   assert(!T.isNull() && "r-value conversion on typeless expression?");
608 
609   // We don't want to throw lvalue-to-rvalue casts on top of
610   // expressions of certain types in C++.
611   if (getLangOpts().CPlusPlus &&
612       (E->getType() == Context.OverloadTy ||
613        T->isDependentType() ||
614        T->isRecordType()))
615     return E;
616 
617   // The C standard is actually really unclear on this point, and
618   // DR106 tells us what the result should be but not why.  It's
619   // generally best to say that void types just doesn't undergo
620   // lvalue-to-rvalue at all.  Note that expressions of unqualified
621   // 'void' type are never l-values, but qualified void can be.
622   if (T->isVoidType())
623     return E;
624 
625   // OpenCL usually rejects direct accesses to values of 'half' type.
626   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
627       T->isHalfType()) {
628     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
629       << 0 << T;
630     return ExprError();
631   }
632 
633   CheckForNullPointerDereference(*this, E);
634   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
635     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
636                                      &Context.Idents.get("object_getClass"),
637                                      SourceLocation(), LookupOrdinaryName);
638     if (ObjectGetClass)
639       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
640           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
641           << FixItHint::CreateReplacement(
642                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
643     else
644       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
645   }
646   else if (const ObjCIvarRefExpr *OIRE =
647             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
648     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
649 
650   // C++ [conv.lval]p1:
651   //   [...] If T is a non-class type, the type of the prvalue is the
652   //   cv-unqualified version of T. Otherwise, the type of the
653   //   rvalue is T.
654   //
655   // C99 6.3.2.1p2:
656   //   If the lvalue has qualified type, the value has the unqualified
657   //   version of the type of the lvalue; otherwise, the value has the
658   //   type of the lvalue.
659   if (T.hasQualifiers())
660     T = T.getUnqualifiedType();
661 
662   // Under the MS ABI, lock down the inheritance model now.
663   if (T->isMemberPointerType() &&
664       Context.getTargetInfo().getCXXABI().isMicrosoft())
665     (void)isCompleteType(E->getExprLoc(), T);
666 
667   ExprResult Res = CheckLValueToRValueConversionOperand(E);
668   if (Res.isInvalid())
669     return Res;
670   E = Res.get();
671 
672   // Loading a __weak object implicitly retains the value, so we need a cleanup to
673   // balance that.
674   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
675     Cleanup.setExprNeedsCleanups(true);
676 
677   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
678     Cleanup.setExprNeedsCleanups(true);
679 
680   // C++ [conv.lval]p3:
681   //   If T is cv std::nullptr_t, the result is a null pointer constant.
682   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
683   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
684 
685   // C11 6.3.2.1p2:
686   //   ... if the lvalue has atomic type, the value has the non-atomic version
687   //   of the type of the lvalue ...
688   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
689     T = Atomic->getValueType().getUnqualifiedType();
690     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
691                                    nullptr, VK_RValue);
692   }
693 
694   return Res;
695 }
696 
697 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
698   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
699   if (Res.isInvalid())
700     return ExprError();
701   Res = DefaultLvalueConversion(Res.get());
702   if (Res.isInvalid())
703     return ExprError();
704   return Res;
705 }
706 
707 /// CallExprUnaryConversions - a special case of an unary conversion
708 /// performed on a function designator of a call expression.
709 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
710   QualType Ty = E->getType();
711   ExprResult Res = E;
712   // Only do implicit cast for a function type, but not for a pointer
713   // to function type.
714   if (Ty->isFunctionType()) {
715     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
716                             CK_FunctionToPointerDecay).get();
717     if (Res.isInvalid())
718       return ExprError();
719   }
720   Res = DefaultLvalueConversion(Res.get());
721   if (Res.isInvalid())
722     return ExprError();
723   return Res.get();
724 }
725 
726 /// UsualUnaryConversions - Performs various conversions that are common to most
727 /// operators (C99 6.3). The conversions of array and function types are
728 /// sometimes suppressed. For example, the array->pointer conversion doesn't
729 /// apply if the array is an argument to the sizeof or address (&) operators.
730 /// In these instances, this routine should *not* be called.
731 ExprResult Sema::UsualUnaryConversions(Expr *E) {
732   // First, convert to an r-value.
733   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
734   if (Res.isInvalid())
735     return ExprError();
736   E = Res.get();
737 
738   QualType Ty = E->getType();
739   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
740 
741   // Half FP have to be promoted to float unless it is natively supported
742   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
743     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
744 
745   // Try to perform integral promotions if the object has a theoretically
746   // promotable type.
747   if (Ty->isIntegralOrUnscopedEnumerationType()) {
748     // C99 6.3.1.1p2:
749     //
750     //   The following may be used in an expression wherever an int or
751     //   unsigned int may be used:
752     //     - an object or expression with an integer type whose integer
753     //       conversion rank is less than or equal to the rank of int
754     //       and unsigned int.
755     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
756     //
757     //   If an int can represent all values of the original type, the
758     //   value is converted to an int; otherwise, it is converted to an
759     //   unsigned int. These are called the integer promotions. All
760     //   other types are unchanged by the integer promotions.
761 
762     QualType PTy = Context.isPromotableBitField(E);
763     if (!PTy.isNull()) {
764       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
765       return E;
766     }
767     if (Ty->isPromotableIntegerType()) {
768       QualType PT = Context.getPromotedIntegerType(Ty);
769       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
770       return E;
771     }
772   }
773   return E;
774 }
775 
776 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
777 /// do not have a prototype. Arguments that have type float or __fp16
778 /// are promoted to double. All other argument types are converted by
779 /// UsualUnaryConversions().
780 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
781   QualType Ty = E->getType();
782   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
783 
784   ExprResult Res = UsualUnaryConversions(E);
785   if (Res.isInvalid())
786     return ExprError();
787   E = Res.get();
788 
789   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
790   // promote to double.
791   // Note that default argument promotion applies only to float (and
792   // half/fp16); it does not apply to _Float16.
793   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
794   if (BTy && (BTy->getKind() == BuiltinType::Half ||
795               BTy->getKind() == BuiltinType::Float)) {
796     if (getLangOpts().OpenCL &&
797         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
798         if (BTy->getKind() == BuiltinType::Half) {
799             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
800         }
801     } else {
802       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
803     }
804   }
805 
806   // C++ performs lvalue-to-rvalue conversion as a default argument
807   // promotion, even on class types, but note:
808   //   C++11 [conv.lval]p2:
809   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
810   //     operand or a subexpression thereof the value contained in the
811   //     referenced object is not accessed. Otherwise, if the glvalue
812   //     has a class type, the conversion copy-initializes a temporary
813   //     of type T from the glvalue and the result of the conversion
814   //     is a prvalue for the temporary.
815   // FIXME: add some way to gate this entire thing for correctness in
816   // potentially potentially evaluated contexts.
817   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
818     ExprResult Temp = PerformCopyInitialization(
819                        InitializedEntity::InitializeTemporary(E->getType()),
820                                                 E->getExprLoc(), E);
821     if (Temp.isInvalid())
822       return ExprError();
823     E = Temp.get();
824   }
825 
826   return E;
827 }
828 
829 /// Determine the degree of POD-ness for an expression.
830 /// Incomplete types are considered POD, since this check can be performed
831 /// when we're in an unevaluated context.
832 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
833   if (Ty->isIncompleteType()) {
834     // C++11 [expr.call]p7:
835     //   After these conversions, if the argument does not have arithmetic,
836     //   enumeration, pointer, pointer to member, or class type, the program
837     //   is ill-formed.
838     //
839     // Since we've already performed array-to-pointer and function-to-pointer
840     // decay, the only such type in C++ is cv void. This also handles
841     // initializer lists as variadic arguments.
842     if (Ty->isVoidType())
843       return VAK_Invalid;
844 
845     if (Ty->isObjCObjectType())
846       return VAK_Invalid;
847     return VAK_Valid;
848   }
849 
850   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
851     return VAK_Invalid;
852 
853   if (Ty.isCXX98PODType(Context))
854     return VAK_Valid;
855 
856   // C++11 [expr.call]p7:
857   //   Passing a potentially-evaluated argument of class type (Clause 9)
858   //   having a non-trivial copy constructor, a non-trivial move constructor,
859   //   or a non-trivial destructor, with no corresponding parameter,
860   //   is conditionally-supported with implementation-defined semantics.
861   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
862     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
863       if (!Record->hasNonTrivialCopyConstructor() &&
864           !Record->hasNonTrivialMoveConstructor() &&
865           !Record->hasNonTrivialDestructor())
866         return VAK_ValidInCXX11;
867 
868   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
869     return VAK_Valid;
870 
871   if (Ty->isObjCObjectType())
872     return VAK_Invalid;
873 
874   if (getLangOpts().MSVCCompat)
875     return VAK_MSVCUndefined;
876 
877   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
878   // permitted to reject them. We should consider doing so.
879   return VAK_Undefined;
880 }
881 
882 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
883   // Don't allow one to pass an Objective-C interface to a vararg.
884   const QualType &Ty = E->getType();
885   VarArgKind VAK = isValidVarArgType(Ty);
886 
887   // Complain about passing non-POD types through varargs.
888   switch (VAK) {
889   case VAK_ValidInCXX11:
890     DiagRuntimeBehavior(
891         E->getBeginLoc(), nullptr,
892         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
893     LLVM_FALLTHROUGH;
894   case VAK_Valid:
895     if (Ty->isRecordType()) {
896       // This is unlikely to be what the user intended. If the class has a
897       // 'c_str' member function, the user probably meant to call that.
898       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
899                           PDiag(diag::warn_pass_class_arg_to_vararg)
900                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
901     }
902     break;
903 
904   case VAK_Undefined:
905   case VAK_MSVCUndefined:
906     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
907                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
908                             << getLangOpts().CPlusPlus11 << Ty << CT);
909     break;
910 
911   case VAK_Invalid:
912     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
913       Diag(E->getBeginLoc(),
914            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
915           << Ty << CT;
916     else if (Ty->isObjCObjectType())
917       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
918                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
919                               << Ty << CT);
920     else
921       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
922           << isa<InitListExpr>(E) << Ty << CT;
923     break;
924   }
925 }
926 
927 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
928 /// will create a trap if the resulting type is not a POD type.
929 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
930                                                   FunctionDecl *FDecl) {
931   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
932     // Strip the unbridged-cast placeholder expression off, if applicable.
933     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
934         (CT == VariadicMethod ||
935          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
936       E = stripARCUnbridgedCast(E);
937 
938     // Otherwise, do normal placeholder checking.
939     } else {
940       ExprResult ExprRes = CheckPlaceholderExpr(E);
941       if (ExprRes.isInvalid())
942         return ExprError();
943       E = ExprRes.get();
944     }
945   }
946 
947   ExprResult ExprRes = DefaultArgumentPromotion(E);
948   if (ExprRes.isInvalid())
949     return ExprError();
950   E = ExprRes.get();
951 
952   // Diagnostics regarding non-POD argument types are
953   // emitted along with format string checking in Sema::CheckFunctionCall().
954   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
955     // Turn this into a trap.
956     CXXScopeSpec SS;
957     SourceLocation TemplateKWLoc;
958     UnqualifiedId Name;
959     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
960                        E->getBeginLoc());
961     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
962                                           /*HasTrailingLParen=*/true,
963                                           /*IsAddressOfOperand=*/false);
964     if (TrapFn.isInvalid())
965       return ExprError();
966 
967     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
968                                     None, E->getEndLoc());
969     if (Call.isInvalid())
970       return ExprError();
971 
972     ExprResult Comma =
973         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
974     if (Comma.isInvalid())
975       return ExprError();
976     return Comma.get();
977   }
978 
979   if (!getLangOpts().CPlusPlus &&
980       RequireCompleteType(E->getExprLoc(), E->getType(),
981                           diag::err_call_incomplete_argument))
982     return ExprError();
983 
984   return E;
985 }
986 
987 /// Converts an integer to complex float type.  Helper function of
988 /// UsualArithmeticConversions()
989 ///
990 /// \return false if the integer expression is an integer type and is
991 /// successfully converted to the complex type.
992 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
993                                                   ExprResult &ComplexExpr,
994                                                   QualType IntTy,
995                                                   QualType ComplexTy,
996                                                   bool SkipCast) {
997   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
998   if (SkipCast) return false;
999   if (IntTy->isIntegerType()) {
1000     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1001     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1002     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1003                                   CK_FloatingRealToComplex);
1004   } else {
1005     assert(IntTy->isComplexIntegerType());
1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1007                                   CK_IntegralComplexToFloatingComplex);
1008   }
1009   return false;
1010 }
1011 
1012 /// Handle arithmetic conversion with complex types.  Helper function of
1013 /// UsualArithmeticConversions()
1014 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1015                                              ExprResult &RHS, QualType LHSType,
1016                                              QualType RHSType,
1017                                              bool IsCompAssign) {
1018   // if we have an integer operand, the result is the complex type.
1019   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1020                                              /*skipCast*/false))
1021     return LHSType;
1022   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1023                                              /*skipCast*/IsCompAssign))
1024     return RHSType;
1025 
1026   // This handles complex/complex, complex/float, or float/complex.
1027   // When both operands are complex, the shorter operand is converted to the
1028   // type of the longer, and that is the type of the result. This corresponds
1029   // to what is done when combining two real floating-point operands.
1030   // The fun begins when size promotion occur across type domains.
1031   // From H&S 6.3.4: When one operand is complex and the other is a real
1032   // floating-point type, the less precise type is converted, within it's
1033   // real or complex domain, to the precision of the other type. For example,
1034   // when combining a "long double" with a "double _Complex", the
1035   // "double _Complex" is promoted to "long double _Complex".
1036 
1037   // Compute the rank of the two types, regardless of whether they are complex.
1038   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1039 
1040   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1041   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1042   QualType LHSElementType =
1043       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1044   QualType RHSElementType =
1045       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1046 
1047   QualType ResultType = S.Context.getComplexType(LHSElementType);
1048   if (Order < 0) {
1049     // Promote the precision of the LHS if not an assignment.
1050     ResultType = S.Context.getComplexType(RHSElementType);
1051     if (!IsCompAssign) {
1052       if (LHSComplexType)
1053         LHS =
1054             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1055       else
1056         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1057     }
1058   } else if (Order > 0) {
1059     // Promote the precision of the RHS.
1060     if (RHSComplexType)
1061       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1062     else
1063       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1064   }
1065   return ResultType;
1066 }
1067 
1068 /// Handle arithmetic conversion from integer to float.  Helper function
1069 /// of UsualArithmeticConversions()
1070 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1071                                            ExprResult &IntExpr,
1072                                            QualType FloatTy, QualType IntTy,
1073                                            bool ConvertFloat, bool ConvertInt) {
1074   if (IntTy->isIntegerType()) {
1075     if (ConvertInt)
1076       // Convert intExpr to the lhs floating point type.
1077       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1078                                     CK_IntegralToFloating);
1079     return FloatTy;
1080   }
1081 
1082   // Convert both sides to the appropriate complex float.
1083   assert(IntTy->isComplexIntegerType());
1084   QualType result = S.Context.getComplexType(FloatTy);
1085 
1086   // _Complex int -> _Complex float
1087   if (ConvertInt)
1088     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1089                                   CK_IntegralComplexToFloatingComplex);
1090 
1091   // float -> _Complex float
1092   if (ConvertFloat)
1093     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1094                                     CK_FloatingRealToComplex);
1095 
1096   return result;
1097 }
1098 
1099 /// Handle arithmethic conversion with floating point types.  Helper
1100 /// function of UsualArithmeticConversions()
1101 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1102                                       ExprResult &RHS, QualType LHSType,
1103                                       QualType RHSType, bool IsCompAssign) {
1104   bool LHSFloat = LHSType->isRealFloatingType();
1105   bool RHSFloat = RHSType->isRealFloatingType();
1106 
1107   // If we have two real floating types, convert the smaller operand
1108   // to the bigger result.
1109   if (LHSFloat && RHSFloat) {
1110     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1111     if (order > 0) {
1112       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1113       return LHSType;
1114     }
1115 
1116     assert(order < 0 && "illegal float comparison");
1117     if (!IsCompAssign)
1118       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1119     return RHSType;
1120   }
1121 
1122   if (LHSFloat) {
1123     // Half FP has to be promoted to float unless it is natively supported
1124     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1125       LHSType = S.Context.FloatTy;
1126 
1127     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1128                                       /*ConvertFloat=*/!IsCompAssign,
1129                                       /*ConvertInt=*/ true);
1130   }
1131   assert(RHSFloat);
1132   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1133                                     /*convertInt=*/ true,
1134                                     /*convertFloat=*/!IsCompAssign);
1135 }
1136 
1137 /// Diagnose attempts to convert between __float128 and long double if
1138 /// there is no support for such conversion. Helper function of
1139 /// UsualArithmeticConversions().
1140 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1141                                       QualType RHSType) {
1142   /*  No issue converting if at least one of the types is not a floating point
1143       type or the two types have the same rank.
1144   */
1145   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1146       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1147     return false;
1148 
1149   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1150          "The remaining types must be floating point types.");
1151 
1152   auto *LHSComplex = LHSType->getAs<ComplexType>();
1153   auto *RHSComplex = RHSType->getAs<ComplexType>();
1154 
1155   QualType LHSElemType = LHSComplex ?
1156     LHSComplex->getElementType() : LHSType;
1157   QualType RHSElemType = RHSComplex ?
1158     RHSComplex->getElementType() : RHSType;
1159 
1160   // No issue if the two types have the same representation
1161   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1162       &S.Context.getFloatTypeSemantics(RHSElemType))
1163     return false;
1164 
1165   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1166                                 RHSElemType == S.Context.LongDoubleTy);
1167   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1168                             RHSElemType == S.Context.Float128Ty);
1169 
1170   // We've handled the situation where __float128 and long double have the same
1171   // representation. We allow all conversions for all possible long double types
1172   // except PPC's double double.
1173   return Float128AndLongDouble &&
1174     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1175      &llvm::APFloat::PPCDoubleDouble());
1176 }
1177 
1178 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1179 
1180 namespace {
1181 /// These helper callbacks are placed in an anonymous namespace to
1182 /// permit their use as function template parameters.
1183 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1184   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1185 }
1186 
1187 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1188   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1189                              CK_IntegralComplexCast);
1190 }
1191 }
1192 
1193 /// Handle integer arithmetic conversions.  Helper function of
1194 /// UsualArithmeticConversions()
1195 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1196 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1197                                         ExprResult &RHS, QualType LHSType,
1198                                         QualType RHSType, bool IsCompAssign) {
1199   // The rules for this case are in C99 6.3.1.8
1200   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1201   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1202   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1203   if (LHSSigned == RHSSigned) {
1204     // Same signedness; use the higher-ranked type
1205     if (order >= 0) {
1206       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1207       return LHSType;
1208     } else if (!IsCompAssign)
1209       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1210     return RHSType;
1211   } else if (order != (LHSSigned ? 1 : -1)) {
1212     // The unsigned type has greater than or equal rank to the
1213     // signed type, so use the unsigned type
1214     if (RHSSigned) {
1215       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1216       return LHSType;
1217     } else if (!IsCompAssign)
1218       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1219     return RHSType;
1220   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1221     // The two types are different widths; if we are here, that
1222     // means the signed type is larger than the unsigned type, so
1223     // use the signed type.
1224     if (LHSSigned) {
1225       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1226       return LHSType;
1227     } else if (!IsCompAssign)
1228       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1229     return RHSType;
1230   } else {
1231     // The signed type is higher-ranked than the unsigned type,
1232     // but isn't actually any bigger (like unsigned int and long
1233     // on most 32-bit systems).  Use the unsigned type corresponding
1234     // to the signed type.
1235     QualType result =
1236       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1237     RHS = (*doRHSCast)(S, RHS.get(), result);
1238     if (!IsCompAssign)
1239       LHS = (*doLHSCast)(S, LHS.get(), result);
1240     return result;
1241   }
1242 }
1243 
1244 /// Handle conversions with GCC complex int extension.  Helper function
1245 /// of UsualArithmeticConversions()
1246 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1247                                            ExprResult &RHS, QualType LHSType,
1248                                            QualType RHSType,
1249                                            bool IsCompAssign) {
1250   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1251   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1252 
1253   if (LHSComplexInt && RHSComplexInt) {
1254     QualType LHSEltType = LHSComplexInt->getElementType();
1255     QualType RHSEltType = RHSComplexInt->getElementType();
1256     QualType ScalarType =
1257       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1258         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1259 
1260     return S.Context.getComplexType(ScalarType);
1261   }
1262 
1263   if (LHSComplexInt) {
1264     QualType LHSEltType = LHSComplexInt->getElementType();
1265     QualType ScalarType =
1266       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1267         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1268     QualType ComplexType = S.Context.getComplexType(ScalarType);
1269     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1270                               CK_IntegralRealToComplex);
1271 
1272     return ComplexType;
1273   }
1274 
1275   assert(RHSComplexInt);
1276 
1277   QualType RHSEltType = RHSComplexInt->getElementType();
1278   QualType ScalarType =
1279     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1280       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1281   QualType ComplexType = S.Context.getComplexType(ScalarType);
1282 
1283   if (!IsCompAssign)
1284     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1285                               CK_IntegralRealToComplex);
1286   return ComplexType;
1287 }
1288 
1289 /// Return the rank of a given fixed point or integer type. The value itself
1290 /// doesn't matter, but the values must be increasing with proper increasing
1291 /// rank as described in N1169 4.1.1.
1292 static unsigned GetFixedPointRank(QualType Ty) {
1293   const auto *BTy = Ty->getAs<BuiltinType>();
1294   assert(BTy && "Expected a builtin type.");
1295 
1296   switch (BTy->getKind()) {
1297   case BuiltinType::ShortFract:
1298   case BuiltinType::UShortFract:
1299   case BuiltinType::SatShortFract:
1300   case BuiltinType::SatUShortFract:
1301     return 1;
1302   case BuiltinType::Fract:
1303   case BuiltinType::UFract:
1304   case BuiltinType::SatFract:
1305   case BuiltinType::SatUFract:
1306     return 2;
1307   case BuiltinType::LongFract:
1308   case BuiltinType::ULongFract:
1309   case BuiltinType::SatLongFract:
1310   case BuiltinType::SatULongFract:
1311     return 3;
1312   case BuiltinType::ShortAccum:
1313   case BuiltinType::UShortAccum:
1314   case BuiltinType::SatShortAccum:
1315   case BuiltinType::SatUShortAccum:
1316     return 4;
1317   case BuiltinType::Accum:
1318   case BuiltinType::UAccum:
1319   case BuiltinType::SatAccum:
1320   case BuiltinType::SatUAccum:
1321     return 5;
1322   case BuiltinType::LongAccum:
1323   case BuiltinType::ULongAccum:
1324   case BuiltinType::SatLongAccum:
1325   case BuiltinType::SatULongAccum:
1326     return 6;
1327   default:
1328     if (BTy->isInteger())
1329       return 0;
1330     llvm_unreachable("Unexpected fixed point or integer type");
1331   }
1332 }
1333 
1334 /// handleFixedPointConversion - Fixed point operations between fixed
1335 /// point types and integers or other fixed point types do not fall under
1336 /// usual arithmetic conversion since these conversions could result in loss
1337 /// of precsision (N1169 4.1.4). These operations should be calculated with
1338 /// the full precision of their result type (N1169 4.1.6.2.1).
1339 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1340                                            QualType RHSTy) {
1341   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1342          "Expected at least one of the operands to be a fixed point type");
1343   assert((LHSTy->isFixedPointOrIntegerType() ||
1344           RHSTy->isFixedPointOrIntegerType()) &&
1345          "Special fixed point arithmetic operation conversions are only "
1346          "applied to ints or other fixed point types");
1347 
1348   // If one operand has signed fixed-point type and the other operand has
1349   // unsigned fixed-point type, then the unsigned fixed-point operand is
1350   // converted to its corresponding signed fixed-point type and the resulting
1351   // type is the type of the converted operand.
1352   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1353     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1354   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1355     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1356 
1357   // The result type is the type with the highest rank, whereby a fixed-point
1358   // conversion rank is always greater than an integer conversion rank; if the
1359   // type of either of the operands is a saturating fixedpoint type, the result
1360   // type shall be the saturating fixed-point type corresponding to the type
1361   // with the highest rank; the resulting value is converted (taking into
1362   // account rounding and overflow) to the precision of the resulting type.
1363   // Same ranks between signed and unsigned types are resolved earlier, so both
1364   // types are either signed or both unsigned at this point.
1365   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1366   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1367 
1368   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1369 
1370   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1371     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1372 
1373   return ResultTy;
1374 }
1375 
1376 /// Check that the usual arithmetic conversions can be performed on this pair of
1377 /// expressions that might be of enumeration type.
1378 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1379                                            SourceLocation Loc,
1380                                            Sema::ArithConvKind ACK) {
1381   // C++2a [expr.arith.conv]p1:
1382   //   If one operand is of enumeration type and the other operand is of a
1383   //   different enumeration type or a floating-point type, this behavior is
1384   //   deprecated ([depr.arith.conv.enum]).
1385   //
1386   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1387   // Eventually we will presumably reject these cases (in C++23 onwards?).
1388   QualType L = LHS->getType(), R = RHS->getType();
1389   bool LEnum = L->isUnscopedEnumerationType(),
1390        REnum = R->isUnscopedEnumerationType();
1391   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1392   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1393       (REnum && L->isFloatingType())) {
1394     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1395                     ? diag::warn_arith_conv_enum_float_cxx20
1396                     : diag::warn_arith_conv_enum_float)
1397         << LHS->getSourceRange() << RHS->getSourceRange()
1398         << (int)ACK << LEnum << L << R;
1399   } else if (!IsCompAssign && LEnum && REnum &&
1400              !S.Context.hasSameUnqualifiedType(L, R)) {
1401     unsigned DiagID;
1402     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1403         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1404       // If either enumeration type is unnamed, it's less likely that the
1405       // user cares about this, but this situation is still deprecated in
1406       // C++2a. Use a different warning group.
1407       DiagID = S.getLangOpts().CPlusPlus20
1408                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1409                     : diag::warn_arith_conv_mixed_anon_enum_types;
1410     } else if (ACK == Sema::ACK_Conditional) {
1411       // Conditional expressions are separated out because they have
1412       // historically had a different warning flag.
1413       DiagID = S.getLangOpts().CPlusPlus20
1414                    ? diag::warn_conditional_mixed_enum_types_cxx20
1415                    : diag::warn_conditional_mixed_enum_types;
1416     } else if (ACK == Sema::ACK_Comparison) {
1417       // Comparison expressions are separated out because they have
1418       // historically had a different warning flag.
1419       DiagID = S.getLangOpts().CPlusPlus20
1420                    ? diag::warn_comparison_mixed_enum_types_cxx20
1421                    : diag::warn_comparison_mixed_enum_types;
1422     } else {
1423       DiagID = S.getLangOpts().CPlusPlus20
1424                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1425                    : diag::warn_arith_conv_mixed_enum_types;
1426     }
1427     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1428                         << (int)ACK << L << R;
1429   }
1430 }
1431 
1432 /// UsualArithmeticConversions - Performs various conversions that are common to
1433 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1434 /// routine returns the first non-arithmetic type found. The client is
1435 /// responsible for emitting appropriate error diagnostics.
1436 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1437                                           SourceLocation Loc,
1438                                           ArithConvKind ACK) {
1439   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1440 
1441   if (ACK != ACK_CompAssign) {
1442     LHS = UsualUnaryConversions(LHS.get());
1443     if (LHS.isInvalid())
1444       return QualType();
1445   }
1446 
1447   RHS = UsualUnaryConversions(RHS.get());
1448   if (RHS.isInvalid())
1449     return QualType();
1450 
1451   // For conversion purposes, we ignore any qualifiers.
1452   // For example, "const float" and "float" are equivalent.
1453   QualType LHSType =
1454     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1455   QualType RHSType =
1456     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1457 
1458   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1459   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1460     LHSType = AtomicLHS->getValueType();
1461 
1462   // If both types are identical, no conversion is needed.
1463   if (LHSType == RHSType)
1464     return LHSType;
1465 
1466   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1467   // The caller can deal with this (e.g. pointer + int).
1468   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1469     return QualType();
1470 
1471   // Apply unary and bitfield promotions to the LHS's type.
1472   QualType LHSUnpromotedType = LHSType;
1473   if (LHSType->isPromotableIntegerType())
1474     LHSType = Context.getPromotedIntegerType(LHSType);
1475   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1476   if (!LHSBitfieldPromoteTy.isNull())
1477     LHSType = LHSBitfieldPromoteTy;
1478   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1479     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1480 
1481   // If both types are identical, no conversion is needed.
1482   if (LHSType == RHSType)
1483     return LHSType;
1484 
1485   // ExtInt types aren't subject to conversions between them or normal integers,
1486   // so this fails.
1487   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1488     return QualType();
1489 
1490   // At this point, we have two different arithmetic types.
1491 
1492   // Diagnose attempts to convert between __float128 and long double where
1493   // such conversions currently can't be handled.
1494   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1495     return QualType();
1496 
1497   // Handle complex types first (C99 6.3.1.8p1).
1498   if (LHSType->isComplexType() || RHSType->isComplexType())
1499     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1500                                         ACK == ACK_CompAssign);
1501 
1502   // Now handle "real" floating types (i.e. float, double, long double).
1503   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1504     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1505                                  ACK == ACK_CompAssign);
1506 
1507   // Handle GCC complex int extension.
1508   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1509     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1510                                       ACK == ACK_CompAssign);
1511 
1512   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1513     return handleFixedPointConversion(*this, LHSType, RHSType);
1514 
1515   // Finally, we have two differing integer types.
1516   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1517            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1518 }
1519 
1520 //===----------------------------------------------------------------------===//
1521 //  Semantic Analysis for various Expression Types
1522 //===----------------------------------------------------------------------===//
1523 
1524 
1525 ExprResult
1526 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1527                                 SourceLocation DefaultLoc,
1528                                 SourceLocation RParenLoc,
1529                                 Expr *ControllingExpr,
1530                                 ArrayRef<ParsedType> ArgTypes,
1531                                 ArrayRef<Expr *> ArgExprs) {
1532   unsigned NumAssocs = ArgTypes.size();
1533   assert(NumAssocs == ArgExprs.size());
1534 
1535   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1536   for (unsigned i = 0; i < NumAssocs; ++i) {
1537     if (ArgTypes[i])
1538       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1539     else
1540       Types[i] = nullptr;
1541   }
1542 
1543   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1544                                              ControllingExpr,
1545                                              llvm::makeArrayRef(Types, NumAssocs),
1546                                              ArgExprs);
1547   delete [] Types;
1548   return ER;
1549 }
1550 
1551 ExprResult
1552 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1553                                  SourceLocation DefaultLoc,
1554                                  SourceLocation RParenLoc,
1555                                  Expr *ControllingExpr,
1556                                  ArrayRef<TypeSourceInfo *> Types,
1557                                  ArrayRef<Expr *> Exprs) {
1558   unsigned NumAssocs = Types.size();
1559   assert(NumAssocs == Exprs.size());
1560 
1561   // Decay and strip qualifiers for the controlling expression type, and handle
1562   // placeholder type replacement. See committee discussion from WG14 DR423.
1563   {
1564     EnterExpressionEvaluationContext Unevaluated(
1565         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1566     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1567     if (R.isInvalid())
1568       return ExprError();
1569     ControllingExpr = R.get();
1570   }
1571 
1572   // The controlling expression is an unevaluated operand, so side effects are
1573   // likely unintended.
1574   if (!inTemplateInstantiation() &&
1575       ControllingExpr->HasSideEffects(Context, false))
1576     Diag(ControllingExpr->getExprLoc(),
1577          diag::warn_side_effects_unevaluated_context);
1578 
1579   bool TypeErrorFound = false,
1580        IsResultDependent = ControllingExpr->isTypeDependent(),
1581        ContainsUnexpandedParameterPack
1582          = ControllingExpr->containsUnexpandedParameterPack();
1583 
1584   for (unsigned i = 0; i < NumAssocs; ++i) {
1585     if (Exprs[i]->containsUnexpandedParameterPack())
1586       ContainsUnexpandedParameterPack = true;
1587 
1588     if (Types[i]) {
1589       if (Types[i]->getType()->containsUnexpandedParameterPack())
1590         ContainsUnexpandedParameterPack = true;
1591 
1592       if (Types[i]->getType()->isDependentType()) {
1593         IsResultDependent = true;
1594       } else {
1595         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1596         // complete object type other than a variably modified type."
1597         unsigned D = 0;
1598         if (Types[i]->getType()->isIncompleteType())
1599           D = diag::err_assoc_type_incomplete;
1600         else if (!Types[i]->getType()->isObjectType())
1601           D = diag::err_assoc_type_nonobject;
1602         else if (Types[i]->getType()->isVariablyModifiedType())
1603           D = diag::err_assoc_type_variably_modified;
1604 
1605         if (D != 0) {
1606           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1607             << Types[i]->getTypeLoc().getSourceRange()
1608             << Types[i]->getType();
1609           TypeErrorFound = true;
1610         }
1611 
1612         // C11 6.5.1.1p2 "No two generic associations in the same generic
1613         // selection shall specify compatible types."
1614         for (unsigned j = i+1; j < NumAssocs; ++j)
1615           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1616               Context.typesAreCompatible(Types[i]->getType(),
1617                                          Types[j]->getType())) {
1618             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1619                  diag::err_assoc_compatible_types)
1620               << Types[j]->getTypeLoc().getSourceRange()
1621               << Types[j]->getType()
1622               << Types[i]->getType();
1623             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1624                  diag::note_compat_assoc)
1625               << Types[i]->getTypeLoc().getSourceRange()
1626               << Types[i]->getType();
1627             TypeErrorFound = true;
1628           }
1629       }
1630     }
1631   }
1632   if (TypeErrorFound)
1633     return ExprError();
1634 
1635   // If we determined that the generic selection is result-dependent, don't
1636   // try to compute the result expression.
1637   if (IsResultDependent)
1638     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1639                                         Exprs, DefaultLoc, RParenLoc,
1640                                         ContainsUnexpandedParameterPack);
1641 
1642   SmallVector<unsigned, 1> CompatIndices;
1643   unsigned DefaultIndex = -1U;
1644   for (unsigned i = 0; i < NumAssocs; ++i) {
1645     if (!Types[i])
1646       DefaultIndex = i;
1647     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1648                                         Types[i]->getType()))
1649       CompatIndices.push_back(i);
1650   }
1651 
1652   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1653   // type compatible with at most one of the types named in its generic
1654   // association list."
1655   if (CompatIndices.size() > 1) {
1656     // We strip parens here because the controlling expression is typically
1657     // parenthesized in macro definitions.
1658     ControllingExpr = ControllingExpr->IgnoreParens();
1659     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1660         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1661         << (unsigned)CompatIndices.size();
1662     for (unsigned I : CompatIndices) {
1663       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1664            diag::note_compat_assoc)
1665         << Types[I]->getTypeLoc().getSourceRange()
1666         << Types[I]->getType();
1667     }
1668     return ExprError();
1669   }
1670 
1671   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1672   // its controlling expression shall have type compatible with exactly one of
1673   // the types named in its generic association list."
1674   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1675     // We strip parens here because the controlling expression is typically
1676     // parenthesized in macro definitions.
1677     ControllingExpr = ControllingExpr->IgnoreParens();
1678     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1679         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1680     return ExprError();
1681   }
1682 
1683   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1684   // type name that is compatible with the type of the controlling expression,
1685   // then the result expression of the generic selection is the expression
1686   // in that generic association. Otherwise, the result expression of the
1687   // generic selection is the expression in the default generic association."
1688   unsigned ResultIndex =
1689     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1690 
1691   return GenericSelectionExpr::Create(
1692       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1693       ContainsUnexpandedParameterPack, ResultIndex);
1694 }
1695 
1696 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1697 /// location of the token and the offset of the ud-suffix within it.
1698 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1699                                      unsigned Offset) {
1700   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1701                                         S.getLangOpts());
1702 }
1703 
1704 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1705 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1706 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1707                                                  IdentifierInfo *UDSuffix,
1708                                                  SourceLocation UDSuffixLoc,
1709                                                  ArrayRef<Expr*> Args,
1710                                                  SourceLocation LitEndLoc) {
1711   assert(Args.size() <= 2 && "too many arguments for literal operator");
1712 
1713   QualType ArgTy[2];
1714   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1715     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1716     if (ArgTy[ArgIdx]->isArrayType())
1717       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1718   }
1719 
1720   DeclarationName OpName =
1721     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1722   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1723   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1724 
1725   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1726   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1727                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                               /*AllowStringTemplate*/ false,
1729                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1730     return ExprError();
1731 
1732   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1733 }
1734 
1735 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1736 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1737 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1738 /// multiple tokens.  However, the common case is that StringToks points to one
1739 /// string.
1740 ///
1741 ExprResult
1742 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1743   assert(!StringToks.empty() && "Must have at least one string!");
1744 
1745   StringLiteralParser Literal(StringToks, PP);
1746   if (Literal.hadError)
1747     return ExprError();
1748 
1749   SmallVector<SourceLocation, 4> StringTokLocs;
1750   for (const Token &Tok : StringToks)
1751     StringTokLocs.push_back(Tok.getLocation());
1752 
1753   QualType CharTy = Context.CharTy;
1754   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1755   if (Literal.isWide()) {
1756     CharTy = Context.getWideCharType();
1757     Kind = StringLiteral::Wide;
1758   } else if (Literal.isUTF8()) {
1759     if (getLangOpts().Char8)
1760       CharTy = Context.Char8Ty;
1761     Kind = StringLiteral::UTF8;
1762   } else if (Literal.isUTF16()) {
1763     CharTy = Context.Char16Ty;
1764     Kind = StringLiteral::UTF16;
1765   } else if (Literal.isUTF32()) {
1766     CharTy = Context.Char32Ty;
1767     Kind = StringLiteral::UTF32;
1768   } else if (Literal.isPascal()) {
1769     CharTy = Context.UnsignedCharTy;
1770   }
1771 
1772   // Warn on initializing an array of char from a u8 string literal; this
1773   // becomes ill-formed in C++2a.
1774   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1775       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1776     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1777 
1778     // Create removals for all 'u8' prefixes in the string literal(s). This
1779     // ensures C++2a compatibility (but may change the program behavior when
1780     // built by non-Clang compilers for which the execution character set is
1781     // not always UTF-8).
1782     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1783     SourceLocation RemovalDiagLoc;
1784     for (const Token &Tok : StringToks) {
1785       if (Tok.getKind() == tok::utf8_string_literal) {
1786         if (RemovalDiagLoc.isInvalid())
1787           RemovalDiagLoc = Tok.getLocation();
1788         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1789             Tok.getLocation(),
1790             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1791                                            getSourceManager(), getLangOpts())));
1792       }
1793     }
1794     Diag(RemovalDiagLoc, RemovalDiag);
1795   }
1796 
1797   QualType StrTy =
1798       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1799 
1800   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1801   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1802                                              Kind, Literal.Pascal, StrTy,
1803                                              &StringTokLocs[0],
1804                                              StringTokLocs.size());
1805   if (Literal.getUDSuffix().empty())
1806     return Lit;
1807 
1808   // We're building a user-defined literal.
1809   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1810   SourceLocation UDSuffixLoc =
1811     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1812                    Literal.getUDSuffixOffset());
1813 
1814   // Make sure we're allowed user-defined literals here.
1815   if (!UDLScope)
1816     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1817 
1818   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1819   //   operator "" X (str, len)
1820   QualType SizeType = Context.getSizeType();
1821 
1822   DeclarationName OpName =
1823     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1824   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1825   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1826 
1827   QualType ArgTy[] = {
1828     Context.getArrayDecayedType(StrTy), SizeType
1829   };
1830 
1831   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1832   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1833                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1834                                 /*AllowStringTemplate*/ true,
1835                                 /*DiagnoseMissing*/ true)) {
1836 
1837   case LOLR_Cooked: {
1838     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1839     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1840                                                     StringTokLocs[0]);
1841     Expr *Args[] = { Lit, LenArg };
1842 
1843     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1844   }
1845 
1846   case LOLR_StringTemplate: {
1847     TemplateArgumentListInfo ExplicitArgs;
1848 
1849     unsigned CharBits = Context.getIntWidth(CharTy);
1850     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1851     llvm::APSInt Value(CharBits, CharIsUnsigned);
1852 
1853     TemplateArgument TypeArg(CharTy);
1854     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1855     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1856 
1857     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1858       Value = Lit->getCodeUnit(I);
1859       TemplateArgument Arg(Context, Value, CharTy);
1860       TemplateArgumentLocInfo ArgInfo;
1861       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1862     }
1863     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1864                                     &ExplicitArgs);
1865   }
1866   case LOLR_Raw:
1867   case LOLR_Template:
1868   case LOLR_ErrorNoDiagnostic:
1869     llvm_unreachable("unexpected literal operator lookup result");
1870   case LOLR_Error:
1871     return ExprError();
1872   }
1873   llvm_unreachable("unexpected literal operator lookup result");
1874 }
1875 
1876 DeclRefExpr *
1877 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1878                        SourceLocation Loc,
1879                        const CXXScopeSpec *SS) {
1880   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1881   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1882 }
1883 
1884 DeclRefExpr *
1885 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1886                        const DeclarationNameInfo &NameInfo,
1887                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1888                        SourceLocation TemplateKWLoc,
1889                        const TemplateArgumentListInfo *TemplateArgs) {
1890   NestedNameSpecifierLoc NNS =
1891       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1892   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1893                           TemplateArgs);
1894 }
1895 
1896 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1897   // A declaration named in an unevaluated operand never constitutes an odr-use.
1898   if (isUnevaluatedContext())
1899     return NOUR_Unevaluated;
1900 
1901   // C++2a [basic.def.odr]p4:
1902   //   A variable x whose name appears as a potentially-evaluated expression e
1903   //   is odr-used by e unless [...] x is a reference that is usable in
1904   //   constant expressions.
1905   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906     if (VD->getType()->isReferenceType() &&
1907         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1908         VD->isUsableInConstantExpressions(Context))
1909       return NOUR_Constant;
1910   }
1911 
1912   // All remaining non-variable cases constitute an odr-use. For variables, we
1913   // need to wait and see how the expression is used.
1914   return NOUR_None;
1915 }
1916 
1917 /// BuildDeclRefExpr - Build an expression that references a
1918 /// declaration that does not require a closure capture.
1919 DeclRefExpr *
1920 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1921                        const DeclarationNameInfo &NameInfo,
1922                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1923                        SourceLocation TemplateKWLoc,
1924                        const TemplateArgumentListInfo *TemplateArgs) {
1925   bool RefersToCapturedVariable =
1926       isa<VarDecl>(D) &&
1927       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1928 
1929   DeclRefExpr *E = DeclRefExpr::Create(
1930       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1931       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1932   MarkDeclRefReferenced(E);
1933 
1934   // C++ [except.spec]p17:
1935   //   An exception-specification is considered to be needed when:
1936   //   - in an expression, the function is the unique lookup result or
1937   //     the selected member of a set of overloaded functions.
1938   //
1939   // We delay doing this until after we've built the function reference and
1940   // marked it as used so that:
1941   //  a) if the function is defaulted, we get errors from defining it before /
1942   //     instead of errors from computing its exception specification, and
1943   //  b) if the function is a defaulted comparison, we can use the body we
1944   //     build when defining it as input to the exception specification
1945   //     computation rather than computing a new body.
1946   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1947     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1948       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1949         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1950     }
1951   }
1952 
1953   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1954       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1955       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1956     getCurFunction()->recordUseOfWeak(E);
1957 
1958   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1959   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1960     FD = IFD->getAnonField();
1961   if (FD) {
1962     UnusedPrivateFields.remove(FD);
1963     // Just in case we're building an illegal pointer-to-member.
1964     if (FD->isBitField())
1965       E->setObjectKind(OK_BitField);
1966   }
1967 
1968   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1969   // designates a bit-field.
1970   if (auto *BD = dyn_cast<BindingDecl>(D))
1971     if (auto *BE = BD->getBinding())
1972       E->setObjectKind(BE->getObjectKind());
1973 
1974   return E;
1975 }
1976 
1977 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1978 /// possibly a list of template arguments.
1979 ///
1980 /// If this produces template arguments, it is permitted to call
1981 /// DecomposeTemplateName.
1982 ///
1983 /// This actually loses a lot of source location information for
1984 /// non-standard name kinds; we should consider preserving that in
1985 /// some way.
1986 void
1987 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1988                              TemplateArgumentListInfo &Buffer,
1989                              DeclarationNameInfo &NameInfo,
1990                              const TemplateArgumentListInfo *&TemplateArgs) {
1991   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1992     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1993     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1994 
1995     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1996                                        Id.TemplateId->NumArgs);
1997     translateTemplateArguments(TemplateArgsPtr, Buffer);
1998 
1999     TemplateName TName = Id.TemplateId->Template.get();
2000     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2001     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2002     TemplateArgs = &Buffer;
2003   } else {
2004     NameInfo = GetNameFromUnqualifiedId(Id);
2005     TemplateArgs = nullptr;
2006   }
2007 }
2008 
2009 static void emitEmptyLookupTypoDiagnostic(
2010     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2011     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2012     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2013   DeclContext *Ctx =
2014       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2015   if (!TC) {
2016     // Emit a special diagnostic for failed member lookups.
2017     // FIXME: computing the declaration context might fail here (?)
2018     if (Ctx)
2019       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2020                                                  << SS.getRange();
2021     else
2022       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2023     return;
2024   }
2025 
2026   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2027   bool DroppedSpecifier =
2028       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2029   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2030                         ? diag::note_implicit_param_decl
2031                         : diag::note_previous_decl;
2032   if (!Ctx)
2033     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2034                          SemaRef.PDiag(NoteID));
2035   else
2036     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2037                                  << Typo << Ctx << DroppedSpecifier
2038                                  << SS.getRange(),
2039                          SemaRef.PDiag(NoteID));
2040 }
2041 
2042 /// Diagnose an empty lookup.
2043 ///
2044 /// \return false if new lookup candidates were found
2045 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2046                                CorrectionCandidateCallback &CCC,
2047                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2048                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2049   DeclarationName Name = R.getLookupName();
2050 
2051   unsigned diagnostic = diag::err_undeclared_var_use;
2052   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2053   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2054       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2055       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2056     diagnostic = diag::err_undeclared_use;
2057     diagnostic_suggest = diag::err_undeclared_use_suggest;
2058   }
2059 
2060   // If the original lookup was an unqualified lookup, fake an
2061   // unqualified lookup.  This is useful when (for example) the
2062   // original lookup would not have found something because it was a
2063   // dependent name.
2064   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2065   while (DC) {
2066     if (isa<CXXRecordDecl>(DC)) {
2067       LookupQualifiedName(R, DC);
2068 
2069       if (!R.empty()) {
2070         // Don't give errors about ambiguities in this lookup.
2071         R.suppressDiagnostics();
2072 
2073         // During a default argument instantiation the CurContext points
2074         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2075         // function parameter list, hence add an explicit check.
2076         bool isDefaultArgument =
2077             !CodeSynthesisContexts.empty() &&
2078             CodeSynthesisContexts.back().Kind ==
2079                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2080         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2081         bool isInstance = CurMethod &&
2082                           CurMethod->isInstance() &&
2083                           DC == CurMethod->getParent() && !isDefaultArgument;
2084 
2085         // Give a code modification hint to insert 'this->'.
2086         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2087         // Actually quite difficult!
2088         if (getLangOpts().MSVCCompat)
2089           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2090         if (isInstance) {
2091           Diag(R.getNameLoc(), diagnostic) << Name
2092             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2093           CheckCXXThisCapture(R.getNameLoc());
2094         } else {
2095           Diag(R.getNameLoc(), diagnostic) << Name;
2096         }
2097 
2098         // Do we really want to note all of these?
2099         for (NamedDecl *D : R)
2100           Diag(D->getLocation(), diag::note_dependent_var_use);
2101 
2102         // Return true if we are inside a default argument instantiation
2103         // and the found name refers to an instance member function, otherwise
2104         // the function calling DiagnoseEmptyLookup will try to create an
2105         // implicit member call and this is wrong for default argument.
2106         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2107           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2108           return true;
2109         }
2110 
2111         // Tell the callee to try to recover.
2112         return false;
2113       }
2114 
2115       R.clear();
2116     }
2117 
2118     DC = DC->getLookupParent();
2119   }
2120 
2121   // We didn't find anything, so try to correct for a typo.
2122   TypoCorrection Corrected;
2123   if (S && Out) {
2124     SourceLocation TypoLoc = R.getNameLoc();
2125     assert(!ExplicitTemplateArgs &&
2126            "Diagnosing an empty lookup with explicit template args!");
2127     *Out = CorrectTypoDelayed(
2128         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2129         [=](const TypoCorrection &TC) {
2130           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2131                                         diagnostic, diagnostic_suggest);
2132         },
2133         nullptr, CTK_ErrorRecovery);
2134     if (*Out)
2135       return true;
2136   } else if (S &&
2137              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2138                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2139     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2140     bool DroppedSpecifier =
2141         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2142     R.setLookupName(Corrected.getCorrection());
2143 
2144     bool AcceptableWithRecovery = false;
2145     bool AcceptableWithoutRecovery = false;
2146     NamedDecl *ND = Corrected.getFoundDecl();
2147     if (ND) {
2148       if (Corrected.isOverloaded()) {
2149         OverloadCandidateSet OCS(R.getNameLoc(),
2150                                  OverloadCandidateSet::CSK_Normal);
2151         OverloadCandidateSet::iterator Best;
2152         for (NamedDecl *CD : Corrected) {
2153           if (FunctionTemplateDecl *FTD =
2154                    dyn_cast<FunctionTemplateDecl>(CD))
2155             AddTemplateOverloadCandidate(
2156                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2157                 Args, OCS);
2158           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2159             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2160               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2161                                    Args, OCS);
2162         }
2163         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2164         case OR_Success:
2165           ND = Best->FoundDecl;
2166           Corrected.setCorrectionDecl(ND);
2167           break;
2168         default:
2169           // FIXME: Arbitrarily pick the first declaration for the note.
2170           Corrected.setCorrectionDecl(ND);
2171           break;
2172         }
2173       }
2174       R.addDecl(ND);
2175       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2176         CXXRecordDecl *Record = nullptr;
2177         if (Corrected.getCorrectionSpecifier()) {
2178           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2179           Record = Ty->getAsCXXRecordDecl();
2180         }
2181         if (!Record)
2182           Record = cast<CXXRecordDecl>(
2183               ND->getDeclContext()->getRedeclContext());
2184         R.setNamingClass(Record);
2185       }
2186 
2187       auto *UnderlyingND = ND->getUnderlyingDecl();
2188       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2189                                isa<FunctionTemplateDecl>(UnderlyingND);
2190       // FIXME: If we ended up with a typo for a type name or
2191       // Objective-C class name, we're in trouble because the parser
2192       // is in the wrong place to recover. Suggest the typo
2193       // correction, but don't make it a fix-it since we're not going
2194       // to recover well anyway.
2195       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2196                                   getAsTypeTemplateDecl(UnderlyingND) ||
2197                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2198     } else {
2199       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2200       // because we aren't able to recover.
2201       AcceptableWithoutRecovery = true;
2202     }
2203 
2204     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2205       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2206                             ? diag::note_implicit_param_decl
2207                             : diag::note_previous_decl;
2208       if (SS.isEmpty())
2209         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2210                      PDiag(NoteID), AcceptableWithRecovery);
2211       else
2212         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2213                                   << Name << computeDeclContext(SS, false)
2214                                   << DroppedSpecifier << SS.getRange(),
2215                      PDiag(NoteID), AcceptableWithRecovery);
2216 
2217       // Tell the callee whether to try to recover.
2218       return !AcceptableWithRecovery;
2219     }
2220   }
2221   R.clear();
2222 
2223   // Emit a special diagnostic for failed member lookups.
2224   // FIXME: computing the declaration context might fail here (?)
2225   if (!SS.isEmpty()) {
2226     Diag(R.getNameLoc(), diag::err_no_member)
2227       << Name << computeDeclContext(SS, false)
2228       << SS.getRange();
2229     return true;
2230   }
2231 
2232   // Give up, we can't recover.
2233   Diag(R.getNameLoc(), diagnostic) << Name;
2234   return true;
2235 }
2236 
2237 /// In Microsoft mode, if we are inside a template class whose parent class has
2238 /// dependent base classes, and we can't resolve an unqualified identifier, then
2239 /// assume the identifier is a member of a dependent base class.  We can only
2240 /// recover successfully in static methods, instance methods, and other contexts
2241 /// where 'this' is available.  This doesn't precisely match MSVC's
2242 /// instantiation model, but it's close enough.
2243 static Expr *
2244 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2245                                DeclarationNameInfo &NameInfo,
2246                                SourceLocation TemplateKWLoc,
2247                                const TemplateArgumentListInfo *TemplateArgs) {
2248   // Only try to recover from lookup into dependent bases in static methods or
2249   // contexts where 'this' is available.
2250   QualType ThisType = S.getCurrentThisType();
2251   const CXXRecordDecl *RD = nullptr;
2252   if (!ThisType.isNull())
2253     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2254   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2255     RD = MD->getParent();
2256   if (!RD || !RD->hasAnyDependentBases())
2257     return nullptr;
2258 
2259   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2260   // is available, suggest inserting 'this->' as a fixit.
2261   SourceLocation Loc = NameInfo.getLoc();
2262   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2263   DB << NameInfo.getName() << RD;
2264 
2265   if (!ThisType.isNull()) {
2266     DB << FixItHint::CreateInsertion(Loc, "this->");
2267     return CXXDependentScopeMemberExpr::Create(
2268         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2269         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2270         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2271   }
2272 
2273   // Synthesize a fake NNS that points to the derived class.  This will
2274   // perform name lookup during template instantiation.
2275   CXXScopeSpec SS;
2276   auto *NNS =
2277       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2278   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2279   return DependentScopeDeclRefExpr::Create(
2280       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2281       TemplateArgs);
2282 }
2283 
2284 ExprResult
2285 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2286                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2287                         bool HasTrailingLParen, bool IsAddressOfOperand,
2288                         CorrectionCandidateCallback *CCC,
2289                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2290   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2291          "cannot be direct & operand and have a trailing lparen");
2292   if (SS.isInvalid())
2293     return ExprError();
2294 
2295   TemplateArgumentListInfo TemplateArgsBuffer;
2296 
2297   // Decompose the UnqualifiedId into the following data.
2298   DeclarationNameInfo NameInfo;
2299   const TemplateArgumentListInfo *TemplateArgs;
2300   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2301 
2302   DeclarationName Name = NameInfo.getName();
2303   IdentifierInfo *II = Name.getAsIdentifierInfo();
2304   SourceLocation NameLoc = NameInfo.getLoc();
2305 
2306   if (II && II->isEditorPlaceholder()) {
2307     // FIXME: When typed placeholders are supported we can create a typed
2308     // placeholder expression node.
2309     return ExprError();
2310   }
2311 
2312   // C++ [temp.dep.expr]p3:
2313   //   An id-expression is type-dependent if it contains:
2314   //     -- an identifier that was declared with a dependent type,
2315   //        (note: handled after lookup)
2316   //     -- a template-id that is dependent,
2317   //        (note: handled in BuildTemplateIdExpr)
2318   //     -- a conversion-function-id that specifies a dependent type,
2319   //     -- a nested-name-specifier that contains a class-name that
2320   //        names a dependent type.
2321   // Determine whether this is a member of an unknown specialization;
2322   // we need to handle these differently.
2323   bool DependentID = false;
2324   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2325       Name.getCXXNameType()->isDependentType()) {
2326     DependentID = true;
2327   } else if (SS.isSet()) {
2328     if (DeclContext *DC = computeDeclContext(SS, false)) {
2329       if (RequireCompleteDeclContext(SS, DC))
2330         return ExprError();
2331     } else {
2332       DependentID = true;
2333     }
2334   }
2335 
2336   if (DependentID)
2337     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2338                                       IsAddressOfOperand, TemplateArgs);
2339 
2340   // Perform the required lookup.
2341   LookupResult R(*this, NameInfo,
2342                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2343                      ? LookupObjCImplicitSelfParam
2344                      : LookupOrdinaryName);
2345   if (TemplateKWLoc.isValid() || TemplateArgs) {
2346     // Lookup the template name again to correctly establish the context in
2347     // which it was found. This is really unfortunate as we already did the
2348     // lookup to determine that it was a template name in the first place. If
2349     // this becomes a performance hit, we can work harder to preserve those
2350     // results until we get here but it's likely not worth it.
2351     bool MemberOfUnknownSpecialization;
2352     AssumedTemplateKind AssumedTemplate;
2353     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2354                            MemberOfUnknownSpecialization, TemplateKWLoc,
2355                            &AssumedTemplate))
2356       return ExprError();
2357 
2358     if (MemberOfUnknownSpecialization ||
2359         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2360       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2361                                         IsAddressOfOperand, TemplateArgs);
2362   } else {
2363     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2364     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2365 
2366     // If the result might be in a dependent base class, this is a dependent
2367     // id-expression.
2368     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2369       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2370                                         IsAddressOfOperand, TemplateArgs);
2371 
2372     // If this reference is in an Objective-C method, then we need to do
2373     // some special Objective-C lookup, too.
2374     if (IvarLookupFollowUp) {
2375       ExprResult E(LookupInObjCMethod(R, S, II, true));
2376       if (E.isInvalid())
2377         return ExprError();
2378 
2379       if (Expr *Ex = E.getAs<Expr>())
2380         return Ex;
2381     }
2382   }
2383 
2384   if (R.isAmbiguous())
2385     return ExprError();
2386 
2387   // This could be an implicitly declared function reference (legal in C90,
2388   // extension in C99, forbidden in C++).
2389   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2390     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2391     if (D) R.addDecl(D);
2392   }
2393 
2394   // Determine whether this name might be a candidate for
2395   // argument-dependent lookup.
2396   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2397 
2398   if (R.empty() && !ADL) {
2399     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2400       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2401                                                    TemplateKWLoc, TemplateArgs))
2402         return E;
2403     }
2404 
2405     // Don't diagnose an empty lookup for inline assembly.
2406     if (IsInlineAsmIdentifier)
2407       return ExprError();
2408 
2409     // If this name wasn't predeclared and if this is not a function
2410     // call, diagnose the problem.
2411     TypoExpr *TE = nullptr;
2412     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2413                                                        : nullptr);
2414     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2415     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2416            "Typo correction callback misconfigured");
2417     if (CCC) {
2418       // Make sure the callback knows what the typo being diagnosed is.
2419       CCC->setTypoName(II);
2420       if (SS.isValid())
2421         CCC->setTypoNNS(SS.getScopeRep());
2422     }
2423     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2424     // a template name, but we happen to have always already looked up the name
2425     // before we get here if it must be a template name.
2426     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2427                             None, &TE)) {
2428       if (TE && KeywordReplacement) {
2429         auto &State = getTypoExprState(TE);
2430         auto BestTC = State.Consumer->getNextCorrection();
2431         if (BestTC.isKeyword()) {
2432           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2433           if (State.DiagHandler)
2434             State.DiagHandler(BestTC);
2435           KeywordReplacement->startToken();
2436           KeywordReplacement->setKind(II->getTokenID());
2437           KeywordReplacement->setIdentifierInfo(II);
2438           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2439           // Clean up the state associated with the TypoExpr, since it has
2440           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2441           clearDelayedTypo(TE);
2442           // Signal that a correction to a keyword was performed by returning a
2443           // valid-but-null ExprResult.
2444           return (Expr*)nullptr;
2445         }
2446         State.Consumer->resetCorrectionStream();
2447       }
2448       return TE ? TE : ExprError();
2449     }
2450 
2451     assert(!R.empty() &&
2452            "DiagnoseEmptyLookup returned false but added no results");
2453 
2454     // If we found an Objective-C instance variable, let
2455     // LookupInObjCMethod build the appropriate expression to
2456     // reference the ivar.
2457     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2458       R.clear();
2459       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2460       // In a hopelessly buggy code, Objective-C instance variable
2461       // lookup fails and no expression will be built to reference it.
2462       if (!E.isInvalid() && !E.get())
2463         return ExprError();
2464       return E;
2465     }
2466   }
2467 
2468   // This is guaranteed from this point on.
2469   assert(!R.empty() || ADL);
2470 
2471   // Check whether this might be a C++ implicit instance member access.
2472   // C++ [class.mfct.non-static]p3:
2473   //   When an id-expression that is not part of a class member access
2474   //   syntax and not used to form a pointer to member is used in the
2475   //   body of a non-static member function of class X, if name lookup
2476   //   resolves the name in the id-expression to a non-static non-type
2477   //   member of some class C, the id-expression is transformed into a
2478   //   class member access expression using (*this) as the
2479   //   postfix-expression to the left of the . operator.
2480   //
2481   // But we don't actually need to do this for '&' operands if R
2482   // resolved to a function or overloaded function set, because the
2483   // expression is ill-formed if it actually works out to be a
2484   // non-static member function:
2485   //
2486   // C++ [expr.ref]p4:
2487   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2488   //   [t]he expression can be used only as the left-hand operand of a
2489   //   member function call.
2490   //
2491   // There are other safeguards against such uses, but it's important
2492   // to get this right here so that we don't end up making a
2493   // spuriously dependent expression if we're inside a dependent
2494   // instance method.
2495   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2496     bool MightBeImplicitMember;
2497     if (!IsAddressOfOperand)
2498       MightBeImplicitMember = true;
2499     else if (!SS.isEmpty())
2500       MightBeImplicitMember = false;
2501     else if (R.isOverloadedResult())
2502       MightBeImplicitMember = false;
2503     else if (R.isUnresolvableResult())
2504       MightBeImplicitMember = true;
2505     else
2506       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2507                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2508                               isa<MSPropertyDecl>(R.getFoundDecl());
2509 
2510     if (MightBeImplicitMember)
2511       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2512                                              R, TemplateArgs, S);
2513   }
2514 
2515   if (TemplateArgs || TemplateKWLoc.isValid()) {
2516 
2517     // In C++1y, if this is a variable template id, then check it
2518     // in BuildTemplateIdExpr().
2519     // The single lookup result must be a variable template declaration.
2520     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2521         Id.TemplateId->Kind == TNK_Var_template) {
2522       assert(R.getAsSingle<VarTemplateDecl>() &&
2523              "There should only be one declaration found.");
2524     }
2525 
2526     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2527   }
2528 
2529   return BuildDeclarationNameExpr(SS, R, ADL);
2530 }
2531 
2532 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2533 /// declaration name, generally during template instantiation.
2534 /// There's a large number of things which don't need to be done along
2535 /// this path.
2536 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2537     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2538     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2539   DeclContext *DC = computeDeclContext(SS, false);
2540   if (!DC)
2541     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2542                                      NameInfo, /*TemplateArgs=*/nullptr);
2543 
2544   if (RequireCompleteDeclContext(SS, DC))
2545     return ExprError();
2546 
2547   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2548   LookupQualifiedName(R, DC);
2549 
2550   if (R.isAmbiguous())
2551     return ExprError();
2552 
2553   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2554     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2555                                      NameInfo, /*TemplateArgs=*/nullptr);
2556 
2557   if (R.empty()) {
2558     Diag(NameInfo.getLoc(), diag::err_no_member)
2559       << NameInfo.getName() << DC << SS.getRange();
2560     return ExprError();
2561   }
2562 
2563   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2564     // Diagnose a missing typename if this resolved unambiguously to a type in
2565     // a dependent context.  If we can recover with a type, downgrade this to
2566     // a warning in Microsoft compatibility mode.
2567     unsigned DiagID = diag::err_typename_missing;
2568     if (RecoveryTSI && getLangOpts().MSVCCompat)
2569       DiagID = diag::ext_typename_missing;
2570     SourceLocation Loc = SS.getBeginLoc();
2571     auto D = Diag(Loc, DiagID);
2572     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2573       << SourceRange(Loc, NameInfo.getEndLoc());
2574 
2575     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2576     // context.
2577     if (!RecoveryTSI)
2578       return ExprError();
2579 
2580     // Only issue the fixit if we're prepared to recover.
2581     D << FixItHint::CreateInsertion(Loc, "typename ");
2582 
2583     // Recover by pretending this was an elaborated type.
2584     QualType Ty = Context.getTypeDeclType(TD);
2585     TypeLocBuilder TLB;
2586     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2587 
2588     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2589     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2590     QTL.setElaboratedKeywordLoc(SourceLocation());
2591     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2592 
2593     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2594 
2595     return ExprEmpty();
2596   }
2597 
2598   // Defend against this resolving to an implicit member access. We usually
2599   // won't get here if this might be a legitimate a class member (we end up in
2600   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2601   // a pointer-to-member or in an unevaluated context in C++11.
2602   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2603     return BuildPossibleImplicitMemberExpr(SS,
2604                                            /*TemplateKWLoc=*/SourceLocation(),
2605                                            R, /*TemplateArgs=*/nullptr, S);
2606 
2607   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2608 }
2609 
2610 /// The parser has read a name in, and Sema has detected that we're currently
2611 /// inside an ObjC method. Perform some additional checks and determine if we
2612 /// should form a reference to an ivar.
2613 ///
2614 /// Ideally, most of this would be done by lookup, but there's
2615 /// actually quite a lot of extra work involved.
2616 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2617                                         IdentifierInfo *II) {
2618   SourceLocation Loc = Lookup.getNameLoc();
2619   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2620 
2621   // Check for error condition which is already reported.
2622   if (!CurMethod)
2623     return DeclResult(true);
2624 
2625   // There are two cases to handle here.  1) scoped lookup could have failed,
2626   // in which case we should look for an ivar.  2) scoped lookup could have
2627   // found a decl, but that decl is outside the current instance method (i.e.
2628   // a global variable).  In these two cases, we do a lookup for an ivar with
2629   // this name, if the lookup sucedes, we replace it our current decl.
2630 
2631   // If we're in a class method, we don't normally want to look for
2632   // ivars.  But if we don't find anything else, and there's an
2633   // ivar, that's an error.
2634   bool IsClassMethod = CurMethod->isClassMethod();
2635 
2636   bool LookForIvars;
2637   if (Lookup.empty())
2638     LookForIvars = true;
2639   else if (IsClassMethod)
2640     LookForIvars = false;
2641   else
2642     LookForIvars = (Lookup.isSingleResult() &&
2643                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2644   ObjCInterfaceDecl *IFace = nullptr;
2645   if (LookForIvars) {
2646     IFace = CurMethod->getClassInterface();
2647     ObjCInterfaceDecl *ClassDeclared;
2648     ObjCIvarDecl *IV = nullptr;
2649     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2650       // Diagnose using an ivar in a class method.
2651       if (IsClassMethod) {
2652         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2653         return DeclResult(true);
2654       }
2655 
2656       // Diagnose the use of an ivar outside of the declaring class.
2657       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2658           !declaresSameEntity(ClassDeclared, IFace) &&
2659           !getLangOpts().DebuggerSupport)
2660         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2661 
2662       // Success.
2663       return IV;
2664     }
2665   } else if (CurMethod->isInstanceMethod()) {
2666     // We should warn if a local variable hides an ivar.
2667     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2668       ObjCInterfaceDecl *ClassDeclared;
2669       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2670         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2671             declaresSameEntity(IFace, ClassDeclared))
2672           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2673       }
2674     }
2675   } else if (Lookup.isSingleResult() &&
2676              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2677     // If accessing a stand-alone ivar in a class method, this is an error.
2678     if (const ObjCIvarDecl *IV =
2679             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2680       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2681       return DeclResult(true);
2682     }
2683   }
2684 
2685   // Didn't encounter an error, didn't find an ivar.
2686   return DeclResult(false);
2687 }
2688 
2689 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2690                                   ObjCIvarDecl *IV) {
2691   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2692   assert(CurMethod && CurMethod->isInstanceMethod() &&
2693          "should not reference ivar from this context");
2694 
2695   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2696   assert(IFace && "should not reference ivar from this context");
2697 
2698   // If we're referencing an invalid decl, just return this as a silent
2699   // error node.  The error diagnostic was already emitted on the decl.
2700   if (IV->isInvalidDecl())
2701     return ExprError();
2702 
2703   // Check if referencing a field with __attribute__((deprecated)).
2704   if (DiagnoseUseOfDecl(IV, Loc))
2705     return ExprError();
2706 
2707   // FIXME: This should use a new expr for a direct reference, don't
2708   // turn this into Self->ivar, just return a BareIVarExpr or something.
2709   IdentifierInfo &II = Context.Idents.get("self");
2710   UnqualifiedId SelfName;
2711   SelfName.setIdentifier(&II, SourceLocation());
2712   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2713   CXXScopeSpec SelfScopeSpec;
2714   SourceLocation TemplateKWLoc;
2715   ExprResult SelfExpr =
2716       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2717                         /*HasTrailingLParen=*/false,
2718                         /*IsAddressOfOperand=*/false);
2719   if (SelfExpr.isInvalid())
2720     return ExprError();
2721 
2722   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2723   if (SelfExpr.isInvalid())
2724     return ExprError();
2725 
2726   MarkAnyDeclReferenced(Loc, IV, true);
2727 
2728   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2729   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2730       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2731     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2732 
2733   ObjCIvarRefExpr *Result = new (Context)
2734       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2735                       IV->getLocation(), SelfExpr.get(), true, true);
2736 
2737   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2738     if (!isUnevaluatedContext() &&
2739         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2740       getCurFunction()->recordUseOfWeak(Result);
2741   }
2742   if (getLangOpts().ObjCAutoRefCount)
2743     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2744       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2745 
2746   return Result;
2747 }
2748 
2749 /// The parser has read a name in, and Sema has detected that we're currently
2750 /// inside an ObjC method. Perform some additional checks and determine if we
2751 /// should form a reference to an ivar. If so, build an expression referencing
2752 /// that ivar.
2753 ExprResult
2754 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2755                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2756   // FIXME: Integrate this lookup step into LookupParsedName.
2757   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2758   if (Ivar.isInvalid())
2759     return ExprError();
2760   if (Ivar.isUsable())
2761     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2762                             cast<ObjCIvarDecl>(Ivar.get()));
2763 
2764   if (Lookup.empty() && II && AllowBuiltinCreation)
2765     LookupBuiltin(Lookup);
2766 
2767   // Sentinel value saying that we didn't do anything special.
2768   return ExprResult(false);
2769 }
2770 
2771 /// Cast a base object to a member's actual type.
2772 ///
2773 /// Logically this happens in three phases:
2774 ///
2775 /// * First we cast from the base type to the naming class.
2776 ///   The naming class is the class into which we were looking
2777 ///   when we found the member;  it's the qualifier type if a
2778 ///   qualifier was provided, and otherwise it's the base type.
2779 ///
2780 /// * Next we cast from the naming class to the declaring class.
2781 ///   If the member we found was brought into a class's scope by
2782 ///   a using declaration, this is that class;  otherwise it's
2783 ///   the class declaring the member.
2784 ///
2785 /// * Finally we cast from the declaring class to the "true"
2786 ///   declaring class of the member.  This conversion does not
2787 ///   obey access control.
2788 ExprResult
2789 Sema::PerformObjectMemberConversion(Expr *From,
2790                                     NestedNameSpecifier *Qualifier,
2791                                     NamedDecl *FoundDecl,
2792                                     NamedDecl *Member) {
2793   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2794   if (!RD)
2795     return From;
2796 
2797   QualType DestRecordType;
2798   QualType DestType;
2799   QualType FromRecordType;
2800   QualType FromType = From->getType();
2801   bool PointerConversions = false;
2802   if (isa<FieldDecl>(Member)) {
2803     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2804     auto FromPtrType = FromType->getAs<PointerType>();
2805     DestRecordType = Context.getAddrSpaceQualType(
2806         DestRecordType, FromPtrType
2807                             ? FromType->getPointeeType().getAddressSpace()
2808                             : FromType.getAddressSpace());
2809 
2810     if (FromPtrType) {
2811       DestType = Context.getPointerType(DestRecordType);
2812       FromRecordType = FromPtrType->getPointeeType();
2813       PointerConversions = true;
2814     } else {
2815       DestType = DestRecordType;
2816       FromRecordType = FromType;
2817     }
2818   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2819     if (Method->isStatic())
2820       return From;
2821 
2822     DestType = Method->getThisType();
2823     DestRecordType = DestType->getPointeeType();
2824 
2825     if (FromType->getAs<PointerType>()) {
2826       FromRecordType = FromType->getPointeeType();
2827       PointerConversions = true;
2828     } else {
2829       FromRecordType = FromType;
2830       DestType = DestRecordType;
2831     }
2832 
2833     LangAS FromAS = FromRecordType.getAddressSpace();
2834     LangAS DestAS = DestRecordType.getAddressSpace();
2835     if (FromAS != DestAS) {
2836       QualType FromRecordTypeWithoutAS =
2837           Context.removeAddrSpaceQualType(FromRecordType);
2838       QualType FromTypeWithDestAS =
2839           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2840       if (PointerConversions)
2841         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2842       From = ImpCastExprToType(From, FromTypeWithDestAS,
2843                                CK_AddressSpaceConversion, From->getValueKind())
2844                  .get();
2845     }
2846   } else {
2847     // No conversion necessary.
2848     return From;
2849   }
2850 
2851   if (DestType->isDependentType() || FromType->isDependentType())
2852     return From;
2853 
2854   // If the unqualified types are the same, no conversion is necessary.
2855   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2856     return From;
2857 
2858   SourceRange FromRange = From->getSourceRange();
2859   SourceLocation FromLoc = FromRange.getBegin();
2860 
2861   ExprValueKind VK = From->getValueKind();
2862 
2863   // C++ [class.member.lookup]p8:
2864   //   [...] Ambiguities can often be resolved by qualifying a name with its
2865   //   class name.
2866   //
2867   // If the member was a qualified name and the qualified referred to a
2868   // specific base subobject type, we'll cast to that intermediate type
2869   // first and then to the object in which the member is declared. That allows
2870   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2871   //
2872   //   class Base { public: int x; };
2873   //   class Derived1 : public Base { };
2874   //   class Derived2 : public Base { };
2875   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2876   //
2877   //   void VeryDerived::f() {
2878   //     x = 17; // error: ambiguous base subobjects
2879   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2880   //   }
2881   if (Qualifier && Qualifier->getAsType()) {
2882     QualType QType = QualType(Qualifier->getAsType(), 0);
2883     assert(QType->isRecordType() && "lookup done with non-record type");
2884 
2885     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2886 
2887     // In C++98, the qualifier type doesn't actually have to be a base
2888     // type of the object type, in which case we just ignore it.
2889     // Otherwise build the appropriate casts.
2890     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2891       CXXCastPath BasePath;
2892       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2893                                        FromLoc, FromRange, &BasePath))
2894         return ExprError();
2895 
2896       if (PointerConversions)
2897         QType = Context.getPointerType(QType);
2898       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2899                                VK, &BasePath).get();
2900 
2901       FromType = QType;
2902       FromRecordType = QRecordType;
2903 
2904       // If the qualifier type was the same as the destination type,
2905       // we're done.
2906       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2907         return From;
2908     }
2909   }
2910 
2911   bool IgnoreAccess = false;
2912 
2913   // If we actually found the member through a using declaration, cast
2914   // down to the using declaration's type.
2915   //
2916   // Pointer equality is fine here because only one declaration of a
2917   // class ever has member declarations.
2918   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2919     assert(isa<UsingShadowDecl>(FoundDecl));
2920     QualType URecordType = Context.getTypeDeclType(
2921                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2922 
2923     // We only need to do this if the naming-class to declaring-class
2924     // conversion is non-trivial.
2925     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2926       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2927       CXXCastPath BasePath;
2928       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2929                                        FromLoc, FromRange, &BasePath))
2930         return ExprError();
2931 
2932       QualType UType = URecordType;
2933       if (PointerConversions)
2934         UType = Context.getPointerType(UType);
2935       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2936                                VK, &BasePath).get();
2937       FromType = UType;
2938       FromRecordType = URecordType;
2939     }
2940 
2941     // We don't do access control for the conversion from the
2942     // declaring class to the true declaring class.
2943     IgnoreAccess = true;
2944   }
2945 
2946   CXXCastPath BasePath;
2947   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2948                                    FromLoc, FromRange, &BasePath,
2949                                    IgnoreAccess))
2950     return ExprError();
2951 
2952   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2953                            VK, &BasePath);
2954 }
2955 
2956 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2957                                       const LookupResult &R,
2958                                       bool HasTrailingLParen) {
2959   // Only when used directly as the postfix-expression of a call.
2960   if (!HasTrailingLParen)
2961     return false;
2962 
2963   // Never if a scope specifier was provided.
2964   if (SS.isSet())
2965     return false;
2966 
2967   // Only in C++ or ObjC++.
2968   if (!getLangOpts().CPlusPlus)
2969     return false;
2970 
2971   // Turn off ADL when we find certain kinds of declarations during
2972   // normal lookup:
2973   for (NamedDecl *D : R) {
2974     // C++0x [basic.lookup.argdep]p3:
2975     //     -- a declaration of a class member
2976     // Since using decls preserve this property, we check this on the
2977     // original decl.
2978     if (D->isCXXClassMember())
2979       return false;
2980 
2981     // C++0x [basic.lookup.argdep]p3:
2982     //     -- a block-scope function declaration that is not a
2983     //        using-declaration
2984     // NOTE: we also trigger this for function templates (in fact, we
2985     // don't check the decl type at all, since all other decl types
2986     // turn off ADL anyway).
2987     if (isa<UsingShadowDecl>(D))
2988       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2989     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2990       return false;
2991 
2992     // C++0x [basic.lookup.argdep]p3:
2993     //     -- a declaration that is neither a function or a function
2994     //        template
2995     // And also for builtin functions.
2996     if (isa<FunctionDecl>(D)) {
2997       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2998 
2999       // But also builtin functions.
3000       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3001         return false;
3002     } else if (!isa<FunctionTemplateDecl>(D))
3003       return false;
3004   }
3005 
3006   return true;
3007 }
3008 
3009 
3010 /// Diagnoses obvious problems with the use of the given declaration
3011 /// as an expression.  This is only actually called for lookups that
3012 /// were not overloaded, and it doesn't promise that the declaration
3013 /// will in fact be used.
3014 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3015   if (D->isInvalidDecl())
3016     return true;
3017 
3018   if (isa<TypedefNameDecl>(D)) {
3019     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3020     return true;
3021   }
3022 
3023   if (isa<ObjCInterfaceDecl>(D)) {
3024     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3025     return true;
3026   }
3027 
3028   if (isa<NamespaceDecl>(D)) {
3029     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3030     return true;
3031   }
3032 
3033   return false;
3034 }
3035 
3036 // Certain multiversion types should be treated as overloaded even when there is
3037 // only one result.
3038 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3039   assert(R.isSingleResult() && "Expected only a single result");
3040   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3041   return FD &&
3042          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3043 }
3044 
3045 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3046                                           LookupResult &R, bool NeedsADL,
3047                                           bool AcceptInvalidDecl) {
3048   // If this is a single, fully-resolved result and we don't need ADL,
3049   // just build an ordinary singleton decl ref.
3050   if (!NeedsADL && R.isSingleResult() &&
3051       !R.getAsSingle<FunctionTemplateDecl>() &&
3052       !ShouldLookupResultBeMultiVersionOverload(R))
3053     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3054                                     R.getRepresentativeDecl(), nullptr,
3055                                     AcceptInvalidDecl);
3056 
3057   // We only need to check the declaration if there's exactly one
3058   // result, because in the overloaded case the results can only be
3059   // functions and function templates.
3060   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3061       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3062     return ExprError();
3063 
3064   // Otherwise, just build an unresolved lookup expression.  Suppress
3065   // any lookup-related diagnostics; we'll hash these out later, when
3066   // we've picked a target.
3067   R.suppressDiagnostics();
3068 
3069   UnresolvedLookupExpr *ULE
3070     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3071                                    SS.getWithLocInContext(Context),
3072                                    R.getLookupNameInfo(),
3073                                    NeedsADL, R.isOverloadedResult(),
3074                                    R.begin(), R.end());
3075 
3076   return ULE;
3077 }
3078 
3079 static void
3080 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3081                                    ValueDecl *var, DeclContext *DC);
3082 
3083 /// Complete semantic analysis for a reference to the given declaration.
3084 ExprResult Sema::BuildDeclarationNameExpr(
3085     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3086     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3087     bool AcceptInvalidDecl) {
3088   assert(D && "Cannot refer to a NULL declaration");
3089   assert(!isa<FunctionTemplateDecl>(D) &&
3090          "Cannot refer unambiguously to a function template");
3091 
3092   SourceLocation Loc = NameInfo.getLoc();
3093   if (CheckDeclInExpr(*this, Loc, D))
3094     return ExprError();
3095 
3096   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3097     // Specifically diagnose references to class templates that are missing
3098     // a template argument list.
3099     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3100     return ExprError();
3101   }
3102 
3103   // Make sure that we're referring to a value.
3104   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3105   if (!VD) {
3106     Diag(Loc, diag::err_ref_non_value)
3107       << D << SS.getRange();
3108     Diag(D->getLocation(), diag::note_declared_at);
3109     return ExprError();
3110   }
3111 
3112   // Check whether this declaration can be used. Note that we suppress
3113   // this check when we're going to perform argument-dependent lookup
3114   // on this function name, because this might not be the function
3115   // that overload resolution actually selects.
3116   if (DiagnoseUseOfDecl(VD, Loc))
3117     return ExprError();
3118 
3119   // Only create DeclRefExpr's for valid Decl's.
3120   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3121     return ExprError();
3122 
3123   // Handle members of anonymous structs and unions.  If we got here,
3124   // and the reference is to a class member indirect field, then this
3125   // must be the subject of a pointer-to-member expression.
3126   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3127     if (!indirectField->isCXXClassMember())
3128       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3129                                                       indirectField);
3130 
3131   {
3132     QualType type = VD->getType();
3133     if (type.isNull())
3134       return ExprError();
3135     ExprValueKind valueKind = VK_RValue;
3136 
3137     switch (D->getKind()) {
3138     // Ignore all the non-ValueDecl kinds.
3139 #define ABSTRACT_DECL(kind)
3140 #define VALUE(type, base)
3141 #define DECL(type, base) \
3142     case Decl::type:
3143 #include "clang/AST/DeclNodes.inc"
3144       llvm_unreachable("invalid value decl kind");
3145 
3146     // These shouldn't make it here.
3147     case Decl::ObjCAtDefsField:
3148       llvm_unreachable("forming non-member reference to ivar?");
3149 
3150     // Enum constants are always r-values and never references.
3151     // Unresolved using declarations are dependent.
3152     case Decl::EnumConstant:
3153     case Decl::UnresolvedUsingValue:
3154     case Decl::OMPDeclareReduction:
3155     case Decl::OMPDeclareMapper:
3156       valueKind = VK_RValue;
3157       break;
3158 
3159     // Fields and indirect fields that got here must be for
3160     // pointer-to-member expressions; we just call them l-values for
3161     // internal consistency, because this subexpression doesn't really
3162     // exist in the high-level semantics.
3163     case Decl::Field:
3164     case Decl::IndirectField:
3165     case Decl::ObjCIvar:
3166       assert(getLangOpts().CPlusPlus &&
3167              "building reference to field in C?");
3168 
3169       // These can't have reference type in well-formed programs, but
3170       // for internal consistency we do this anyway.
3171       type = type.getNonReferenceType();
3172       valueKind = VK_LValue;
3173       break;
3174 
3175     // Non-type template parameters are either l-values or r-values
3176     // depending on the type.
3177     case Decl::NonTypeTemplateParm: {
3178       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3179         type = reftype->getPointeeType();
3180         valueKind = VK_LValue; // even if the parameter is an r-value reference
3181         break;
3182       }
3183 
3184       // For non-references, we need to strip qualifiers just in case
3185       // the template parameter was declared as 'const int' or whatever.
3186       valueKind = VK_RValue;
3187       type = type.getUnqualifiedType();
3188       break;
3189     }
3190 
3191     case Decl::Var:
3192     case Decl::VarTemplateSpecialization:
3193     case Decl::VarTemplatePartialSpecialization:
3194     case Decl::Decomposition:
3195     case Decl::OMPCapturedExpr:
3196       // In C, "extern void blah;" is valid and is an r-value.
3197       if (!getLangOpts().CPlusPlus &&
3198           !type.hasQualifiers() &&
3199           type->isVoidType()) {
3200         valueKind = VK_RValue;
3201         break;
3202       }
3203       LLVM_FALLTHROUGH;
3204 
3205     case Decl::ImplicitParam:
3206     case Decl::ParmVar: {
3207       // These are always l-values.
3208       valueKind = VK_LValue;
3209       type = type.getNonReferenceType();
3210 
3211       // FIXME: Does the addition of const really only apply in
3212       // potentially-evaluated contexts? Since the variable isn't actually
3213       // captured in an unevaluated context, it seems that the answer is no.
3214       if (!isUnevaluatedContext()) {
3215         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3216         if (!CapturedType.isNull())
3217           type = CapturedType;
3218       }
3219 
3220       break;
3221     }
3222 
3223     case Decl::Binding: {
3224       // These are always lvalues.
3225       valueKind = VK_LValue;
3226       type = type.getNonReferenceType();
3227       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3228       // decides how that's supposed to work.
3229       auto *BD = cast<BindingDecl>(VD);
3230       if (BD->getDeclContext() != CurContext) {
3231         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3232         if (DD && DD->hasLocalStorage())
3233           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3234       }
3235       break;
3236     }
3237 
3238     case Decl::Function: {
3239       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3240         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3241           type = Context.BuiltinFnTy;
3242           valueKind = VK_RValue;
3243           break;
3244         }
3245       }
3246 
3247       const FunctionType *fty = type->castAs<FunctionType>();
3248 
3249       // If we're referring to a function with an __unknown_anytype
3250       // result type, make the entire expression __unknown_anytype.
3251       if (fty->getReturnType() == Context.UnknownAnyTy) {
3252         type = Context.UnknownAnyTy;
3253         valueKind = VK_RValue;
3254         break;
3255       }
3256 
3257       // Functions are l-values in C++.
3258       if (getLangOpts().CPlusPlus) {
3259         valueKind = VK_LValue;
3260         break;
3261       }
3262 
3263       // C99 DR 316 says that, if a function type comes from a
3264       // function definition (without a prototype), that type is only
3265       // used for checking compatibility. Therefore, when referencing
3266       // the function, we pretend that we don't have the full function
3267       // type.
3268       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3269           isa<FunctionProtoType>(fty))
3270         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3271                                               fty->getExtInfo());
3272 
3273       // Functions are r-values in C.
3274       valueKind = VK_RValue;
3275       break;
3276     }
3277 
3278     case Decl::CXXDeductionGuide:
3279       llvm_unreachable("building reference to deduction guide");
3280 
3281     case Decl::MSProperty:
3282     case Decl::MSGuid:
3283       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3284       // or duplicated between host and device?
3285       valueKind = VK_LValue;
3286       break;
3287 
3288     case Decl::CXXMethod:
3289       // If we're referring to a method with an __unknown_anytype
3290       // result type, make the entire expression __unknown_anytype.
3291       // This should only be possible with a type written directly.
3292       if (const FunctionProtoType *proto
3293             = dyn_cast<FunctionProtoType>(VD->getType()))
3294         if (proto->getReturnType() == Context.UnknownAnyTy) {
3295           type = Context.UnknownAnyTy;
3296           valueKind = VK_RValue;
3297           break;
3298         }
3299 
3300       // C++ methods are l-values if static, r-values if non-static.
3301       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3302         valueKind = VK_LValue;
3303         break;
3304       }
3305       LLVM_FALLTHROUGH;
3306 
3307     case Decl::CXXConversion:
3308     case Decl::CXXDestructor:
3309     case Decl::CXXConstructor:
3310       valueKind = VK_RValue;
3311       break;
3312     }
3313 
3314     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3315                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3316                             TemplateArgs);
3317   }
3318 }
3319 
3320 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3321                                     SmallString<32> &Target) {
3322   Target.resize(CharByteWidth * (Source.size() + 1));
3323   char *ResultPtr = &Target[0];
3324   const llvm::UTF8 *ErrorPtr;
3325   bool success =
3326       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3327   (void)success;
3328   assert(success);
3329   Target.resize(ResultPtr - &Target[0]);
3330 }
3331 
3332 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3333                                      PredefinedExpr::IdentKind IK) {
3334   // Pick the current block, lambda, captured statement or function.
3335   Decl *currentDecl = nullptr;
3336   if (const BlockScopeInfo *BSI = getCurBlock())
3337     currentDecl = BSI->TheDecl;
3338   else if (const LambdaScopeInfo *LSI = getCurLambda())
3339     currentDecl = LSI->CallOperator;
3340   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3341     currentDecl = CSI->TheCapturedDecl;
3342   else
3343     currentDecl = getCurFunctionOrMethodDecl();
3344 
3345   if (!currentDecl) {
3346     Diag(Loc, diag::ext_predef_outside_function);
3347     currentDecl = Context.getTranslationUnitDecl();
3348   }
3349 
3350   QualType ResTy;
3351   StringLiteral *SL = nullptr;
3352   if (cast<DeclContext>(currentDecl)->isDependentContext())
3353     ResTy = Context.DependentTy;
3354   else {
3355     // Pre-defined identifiers are of type char[x], where x is the length of
3356     // the string.
3357     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3358     unsigned Length = Str.length();
3359 
3360     llvm::APInt LengthI(32, Length + 1);
3361     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3362       ResTy =
3363           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3364       SmallString<32> RawChars;
3365       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3366                               Str, RawChars);
3367       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3368                                            ArrayType::Normal,
3369                                            /*IndexTypeQuals*/ 0);
3370       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3371                                  /*Pascal*/ false, ResTy, Loc);
3372     } else {
3373       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3374       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3375                                            ArrayType::Normal,
3376                                            /*IndexTypeQuals*/ 0);
3377       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3378                                  /*Pascal*/ false, ResTy, Loc);
3379     }
3380   }
3381 
3382   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3383 }
3384 
3385 static std::pair<QualType, StringLiteral *>
3386 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3387                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3388   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3389 
3390   if (OpType->isDependentType()) {
3391       Result.first = Context.DependentTy;
3392       return Result;
3393   }
3394 
3395   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3396   llvm::APInt Length(32, Str.length() + 1);
3397   Result.first =
3398       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3399   Result.first = Context.getConstantArrayType(
3400       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3401   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3402                                         /*Pascal*/ false, Result.first, OpLoc);
3403   return Result;
3404 }
3405 
3406 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3407                                        TypeSourceInfo *Operand) {
3408   QualType ResultTy;
3409   StringLiteral *SL;
3410   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3411       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3412 
3413   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3414                                 PredefinedExpr::UniqueStableNameType, SL,
3415                                 Operand);
3416 }
3417 
3418 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3419                                        Expr *E) {
3420   QualType ResultTy;
3421   StringLiteral *SL;
3422   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3423       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3424 
3425   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3426                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3427 }
3428 
3429 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3430                                            SourceLocation L, SourceLocation R,
3431                                            ParsedType Ty) {
3432   TypeSourceInfo *TInfo = nullptr;
3433   QualType T = GetTypeFromParser(Ty, &TInfo);
3434 
3435   if (T.isNull())
3436     return ExprError();
3437   if (!TInfo)
3438     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3439 
3440   return BuildUniqueStableName(OpLoc, TInfo);
3441 }
3442 
3443 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3444                                            SourceLocation L, SourceLocation R,
3445                                            Expr *E) {
3446   return BuildUniqueStableName(OpLoc, E);
3447 }
3448 
3449 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3450   PredefinedExpr::IdentKind IK;
3451 
3452   switch (Kind) {
3453   default: llvm_unreachable("Unknown simple primary expr!");
3454   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3455   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3456   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3457   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3458   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3459   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3460   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3461   }
3462 
3463   return BuildPredefinedExpr(Loc, IK);
3464 }
3465 
3466 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3467   SmallString<16> CharBuffer;
3468   bool Invalid = false;
3469   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3470   if (Invalid)
3471     return ExprError();
3472 
3473   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3474                             PP, Tok.getKind());
3475   if (Literal.hadError())
3476     return ExprError();
3477 
3478   QualType Ty;
3479   if (Literal.isWide())
3480     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3481   else if (Literal.isUTF8() && getLangOpts().Char8)
3482     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3483   else if (Literal.isUTF16())
3484     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3485   else if (Literal.isUTF32())
3486     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3487   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3488     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3489   else
3490     Ty = Context.CharTy;  // 'x' -> char in C++
3491 
3492   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3493   if (Literal.isWide())
3494     Kind = CharacterLiteral::Wide;
3495   else if (Literal.isUTF16())
3496     Kind = CharacterLiteral::UTF16;
3497   else if (Literal.isUTF32())
3498     Kind = CharacterLiteral::UTF32;
3499   else if (Literal.isUTF8())
3500     Kind = CharacterLiteral::UTF8;
3501 
3502   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3503                                              Tok.getLocation());
3504 
3505   if (Literal.getUDSuffix().empty())
3506     return Lit;
3507 
3508   // We're building a user-defined literal.
3509   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3510   SourceLocation UDSuffixLoc =
3511     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3512 
3513   // Make sure we're allowed user-defined literals here.
3514   if (!UDLScope)
3515     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3516 
3517   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3518   //   operator "" X (ch)
3519   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3520                                         Lit, Tok.getLocation());
3521 }
3522 
3523 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3524   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3525   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3526                                 Context.IntTy, Loc);
3527 }
3528 
3529 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3530                                   QualType Ty, SourceLocation Loc) {
3531   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3532 
3533   using llvm::APFloat;
3534   APFloat Val(Format);
3535 
3536   APFloat::opStatus result = Literal.GetFloatValue(Val);
3537 
3538   // Overflow is always an error, but underflow is only an error if
3539   // we underflowed to zero (APFloat reports denormals as underflow).
3540   if ((result & APFloat::opOverflow) ||
3541       ((result & APFloat::opUnderflow) && Val.isZero())) {
3542     unsigned diagnostic;
3543     SmallString<20> buffer;
3544     if (result & APFloat::opOverflow) {
3545       diagnostic = diag::warn_float_overflow;
3546       APFloat::getLargest(Format).toString(buffer);
3547     } else {
3548       diagnostic = diag::warn_float_underflow;
3549       APFloat::getSmallest(Format).toString(buffer);
3550     }
3551 
3552     S.Diag(Loc, diagnostic)
3553       << Ty
3554       << StringRef(buffer.data(), buffer.size());
3555   }
3556 
3557   bool isExact = (result == APFloat::opOK);
3558   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3559 }
3560 
3561 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3562   assert(E && "Invalid expression");
3563 
3564   if (E->isValueDependent())
3565     return false;
3566 
3567   QualType QT = E->getType();
3568   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3569     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3570     return true;
3571   }
3572 
3573   llvm::APSInt ValueAPS;
3574   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3575 
3576   if (R.isInvalid())
3577     return true;
3578 
3579   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3580   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3581     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3582         << ValueAPS.toString(10) << ValueIsPositive;
3583     return true;
3584   }
3585 
3586   return false;
3587 }
3588 
3589 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3590   // Fast path for a single digit (which is quite common).  A single digit
3591   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3592   if (Tok.getLength() == 1) {
3593     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3594     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3595   }
3596 
3597   SmallString<128> SpellingBuffer;
3598   // NumericLiteralParser wants to overread by one character.  Add padding to
3599   // the buffer in case the token is copied to the buffer.  If getSpelling()
3600   // returns a StringRef to the memory buffer, it should have a null char at
3601   // the EOF, so it is also safe.
3602   SpellingBuffer.resize(Tok.getLength() + 1);
3603 
3604   // Get the spelling of the token, which eliminates trigraphs, etc.
3605   bool Invalid = false;
3606   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3607   if (Invalid)
3608     return ExprError();
3609 
3610   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3611   if (Literal.hadError)
3612     return ExprError();
3613 
3614   if (Literal.hasUDSuffix()) {
3615     // We're building a user-defined literal.
3616     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3617     SourceLocation UDSuffixLoc =
3618       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3619 
3620     // Make sure we're allowed user-defined literals here.
3621     if (!UDLScope)
3622       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3623 
3624     QualType CookedTy;
3625     if (Literal.isFloatingLiteral()) {
3626       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3627       // long double, the literal is treated as a call of the form
3628       //   operator "" X (f L)
3629       CookedTy = Context.LongDoubleTy;
3630     } else {
3631       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3632       // unsigned long long, the literal is treated as a call of the form
3633       //   operator "" X (n ULL)
3634       CookedTy = Context.UnsignedLongLongTy;
3635     }
3636 
3637     DeclarationName OpName =
3638       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3639     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3640     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3641 
3642     SourceLocation TokLoc = Tok.getLocation();
3643 
3644     // Perform literal operator lookup to determine if we're building a raw
3645     // literal or a cooked one.
3646     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3647     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3648                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3649                                   /*AllowStringTemplate*/ false,
3650                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3651     case LOLR_ErrorNoDiagnostic:
3652       // Lookup failure for imaginary constants isn't fatal, there's still the
3653       // GNU extension producing _Complex types.
3654       break;
3655     case LOLR_Error:
3656       return ExprError();
3657     case LOLR_Cooked: {
3658       Expr *Lit;
3659       if (Literal.isFloatingLiteral()) {
3660         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3661       } else {
3662         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3663         if (Literal.GetIntegerValue(ResultVal))
3664           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3665               << /* Unsigned */ 1;
3666         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3667                                      Tok.getLocation());
3668       }
3669       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3670     }
3671 
3672     case LOLR_Raw: {
3673       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3674       // literal is treated as a call of the form
3675       //   operator "" X ("n")
3676       unsigned Length = Literal.getUDSuffixOffset();
3677       QualType StrTy = Context.getConstantArrayType(
3678           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3679           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3680       Expr *Lit = StringLiteral::Create(
3681           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3682           /*Pascal*/false, StrTy, &TokLoc, 1);
3683       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3684     }
3685 
3686     case LOLR_Template: {
3687       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3688       // template), L is treated as a call fo the form
3689       //   operator "" X <'c1', 'c2', ... 'ck'>()
3690       // where n is the source character sequence c1 c2 ... ck.
3691       TemplateArgumentListInfo ExplicitArgs;
3692       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3693       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3694       llvm::APSInt Value(CharBits, CharIsUnsigned);
3695       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3696         Value = TokSpelling[I];
3697         TemplateArgument Arg(Context, Value, Context.CharTy);
3698         TemplateArgumentLocInfo ArgInfo;
3699         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3700       }
3701       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3702                                       &ExplicitArgs);
3703     }
3704     case LOLR_StringTemplate:
3705       llvm_unreachable("unexpected literal operator lookup result");
3706     }
3707   }
3708 
3709   Expr *Res;
3710 
3711   if (Literal.isFixedPointLiteral()) {
3712     QualType Ty;
3713 
3714     if (Literal.isAccum) {
3715       if (Literal.isHalf) {
3716         Ty = Context.ShortAccumTy;
3717       } else if (Literal.isLong) {
3718         Ty = Context.LongAccumTy;
3719       } else {
3720         Ty = Context.AccumTy;
3721       }
3722     } else if (Literal.isFract) {
3723       if (Literal.isHalf) {
3724         Ty = Context.ShortFractTy;
3725       } else if (Literal.isLong) {
3726         Ty = Context.LongFractTy;
3727       } else {
3728         Ty = Context.FractTy;
3729       }
3730     }
3731 
3732     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3733 
3734     bool isSigned = !Literal.isUnsigned;
3735     unsigned scale = Context.getFixedPointScale(Ty);
3736     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3737 
3738     llvm::APInt Val(bit_width, 0, isSigned);
3739     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3740     bool ValIsZero = Val.isNullValue() && !Overflowed;
3741 
3742     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3743     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3744       // Clause 6.4.4 - The value of a constant shall be in the range of
3745       // representable values for its type, with exception for constants of a
3746       // fract type with a value of exactly 1; such a constant shall denote
3747       // the maximal value for the type.
3748       --Val;
3749     else if (Val.ugt(MaxVal) || Overflowed)
3750       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3751 
3752     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3753                                               Tok.getLocation(), scale);
3754   } else if (Literal.isFloatingLiteral()) {
3755     QualType Ty;
3756     if (Literal.isHalf){
3757       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3758         Ty = Context.HalfTy;
3759       else {
3760         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3761         return ExprError();
3762       }
3763     } else if (Literal.isFloat)
3764       Ty = Context.FloatTy;
3765     else if (Literal.isLong)
3766       Ty = Context.LongDoubleTy;
3767     else if (Literal.isFloat16)
3768       Ty = Context.Float16Ty;
3769     else if (Literal.isFloat128)
3770       Ty = Context.Float128Ty;
3771     else
3772       Ty = Context.DoubleTy;
3773 
3774     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3775 
3776     if (Ty == Context.DoubleTy) {
3777       if (getLangOpts().SinglePrecisionConstants) {
3778         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3779         if (BTy->getKind() != BuiltinType::Float) {
3780           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3781         }
3782       } else if (getLangOpts().OpenCL &&
3783                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3784         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3785         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3786         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3787       }
3788     }
3789   } else if (!Literal.isIntegerLiteral()) {
3790     return ExprError();
3791   } else {
3792     QualType Ty;
3793 
3794     // 'long long' is a C99 or C++11 feature.
3795     if (!getLangOpts().C99 && Literal.isLongLong) {
3796       if (getLangOpts().CPlusPlus)
3797         Diag(Tok.getLocation(),
3798              getLangOpts().CPlusPlus11 ?
3799              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3800       else
3801         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3802     }
3803 
3804     // Get the value in the widest-possible width.
3805     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3806     llvm::APInt ResultVal(MaxWidth, 0);
3807 
3808     if (Literal.GetIntegerValue(ResultVal)) {
3809       // If this value didn't fit into uintmax_t, error and force to ull.
3810       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3811           << /* Unsigned */ 1;
3812       Ty = Context.UnsignedLongLongTy;
3813       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3814              "long long is not intmax_t?");
3815     } else {
3816       // If this value fits into a ULL, try to figure out what else it fits into
3817       // according to the rules of C99 6.4.4.1p5.
3818 
3819       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3820       // be an unsigned int.
3821       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3822 
3823       // Check from smallest to largest, picking the smallest type we can.
3824       unsigned Width = 0;
3825 
3826       // Microsoft specific integer suffixes are explicitly sized.
3827       if (Literal.MicrosoftInteger) {
3828         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3829           Width = 8;
3830           Ty = Context.CharTy;
3831         } else {
3832           Width = Literal.MicrosoftInteger;
3833           Ty = Context.getIntTypeForBitwidth(Width,
3834                                              /*Signed=*/!Literal.isUnsigned);
3835         }
3836       }
3837 
3838       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3839         // Are int/unsigned possibilities?
3840         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3841 
3842         // Does it fit in a unsigned int?
3843         if (ResultVal.isIntN(IntSize)) {
3844           // Does it fit in a signed int?
3845           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3846             Ty = Context.IntTy;
3847           else if (AllowUnsigned)
3848             Ty = Context.UnsignedIntTy;
3849           Width = IntSize;
3850         }
3851       }
3852 
3853       // Are long/unsigned long possibilities?
3854       if (Ty.isNull() && !Literal.isLongLong) {
3855         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3856 
3857         // Does it fit in a unsigned long?
3858         if (ResultVal.isIntN(LongSize)) {
3859           // Does it fit in a signed long?
3860           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3861             Ty = Context.LongTy;
3862           else if (AllowUnsigned)
3863             Ty = Context.UnsignedLongTy;
3864           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3865           // is compatible.
3866           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3867             const unsigned LongLongSize =
3868                 Context.getTargetInfo().getLongLongWidth();
3869             Diag(Tok.getLocation(),
3870                  getLangOpts().CPlusPlus
3871                      ? Literal.isLong
3872                            ? diag::warn_old_implicitly_unsigned_long_cxx
3873                            : /*C++98 UB*/ diag::
3874                                  ext_old_implicitly_unsigned_long_cxx
3875                      : diag::warn_old_implicitly_unsigned_long)
3876                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3877                                             : /*will be ill-formed*/ 1);
3878             Ty = Context.UnsignedLongTy;
3879           }
3880           Width = LongSize;
3881         }
3882       }
3883 
3884       // Check long long if needed.
3885       if (Ty.isNull()) {
3886         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3887 
3888         // Does it fit in a unsigned long long?
3889         if (ResultVal.isIntN(LongLongSize)) {
3890           // Does it fit in a signed long long?
3891           // To be compatible with MSVC, hex integer literals ending with the
3892           // LL or i64 suffix are always signed in Microsoft mode.
3893           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3894               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3895             Ty = Context.LongLongTy;
3896           else if (AllowUnsigned)
3897             Ty = Context.UnsignedLongLongTy;
3898           Width = LongLongSize;
3899         }
3900       }
3901 
3902       // If we still couldn't decide a type, we probably have something that
3903       // does not fit in a signed long long, but has no U suffix.
3904       if (Ty.isNull()) {
3905         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3906         Ty = Context.UnsignedLongLongTy;
3907         Width = Context.getTargetInfo().getLongLongWidth();
3908       }
3909 
3910       if (ResultVal.getBitWidth() != Width)
3911         ResultVal = ResultVal.trunc(Width);
3912     }
3913     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3914   }
3915 
3916   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3917   if (Literal.isImaginary) {
3918     Res = new (Context) ImaginaryLiteral(Res,
3919                                         Context.getComplexType(Res->getType()));
3920 
3921     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3922   }
3923   return Res;
3924 }
3925 
3926 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3927   assert(E && "ActOnParenExpr() missing expr");
3928   return new (Context) ParenExpr(L, R, E);
3929 }
3930 
3931 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3932                                          SourceLocation Loc,
3933                                          SourceRange ArgRange) {
3934   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3935   // scalar or vector data type argument..."
3936   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3937   // type (C99 6.2.5p18) or void.
3938   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3939     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3940       << T << ArgRange;
3941     return true;
3942   }
3943 
3944   assert((T->isVoidType() || !T->isIncompleteType()) &&
3945          "Scalar types should always be complete");
3946   return false;
3947 }
3948 
3949 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3950                                            SourceLocation Loc,
3951                                            SourceRange ArgRange,
3952                                            UnaryExprOrTypeTrait TraitKind) {
3953   // Invalid types must be hard errors for SFINAE in C++.
3954   if (S.LangOpts.CPlusPlus)
3955     return true;
3956 
3957   // C99 6.5.3.4p1:
3958   if (T->isFunctionType() &&
3959       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3960        TraitKind == UETT_PreferredAlignOf)) {
3961     // sizeof(function)/alignof(function) is allowed as an extension.
3962     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3963       << TraitKind << ArgRange;
3964     return false;
3965   }
3966 
3967   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3968   // this is an error (OpenCL v1.1 s6.3.k)
3969   if (T->isVoidType()) {
3970     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3971                                         : diag::ext_sizeof_alignof_void_type;
3972     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3973     return false;
3974   }
3975 
3976   return true;
3977 }
3978 
3979 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3980                                              SourceLocation Loc,
3981                                              SourceRange ArgRange,
3982                                              UnaryExprOrTypeTrait TraitKind) {
3983   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3984   // runtime doesn't allow it.
3985   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3986     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3987       << T << (TraitKind == UETT_SizeOf)
3988       << ArgRange;
3989     return true;
3990   }
3991 
3992   return false;
3993 }
3994 
3995 /// Check whether E is a pointer from a decayed array type (the decayed
3996 /// pointer type is equal to T) and emit a warning if it is.
3997 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3998                                      Expr *E) {
3999   // Don't warn if the operation changed the type.
4000   if (T != E->getType())
4001     return;
4002 
4003   // Now look for array decays.
4004   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4005   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4006     return;
4007 
4008   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4009                                              << ICE->getType()
4010                                              << ICE->getSubExpr()->getType();
4011 }
4012 
4013 /// Check the constraints on expression operands to unary type expression
4014 /// and type traits.
4015 ///
4016 /// Completes any types necessary and validates the constraints on the operand
4017 /// expression. The logic mostly mirrors the type-based overload, but may modify
4018 /// the expression as it completes the type for that expression through template
4019 /// instantiation, etc.
4020 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4021                                             UnaryExprOrTypeTrait ExprKind) {
4022   QualType ExprTy = E->getType();
4023   assert(!ExprTy->isReferenceType());
4024 
4025   bool IsUnevaluatedOperand =
4026       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4027        ExprKind == UETT_PreferredAlignOf);
4028   if (IsUnevaluatedOperand) {
4029     ExprResult Result = CheckUnevaluatedOperand(E);
4030     if (Result.isInvalid())
4031       return true;
4032     E = Result.get();
4033   }
4034 
4035   if (ExprKind == UETT_VecStep)
4036     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4037                                         E->getSourceRange());
4038 
4039   // Whitelist some types as extensions
4040   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4041                                       E->getSourceRange(), ExprKind))
4042     return false;
4043 
4044   // 'alignof' applied to an expression only requires the base element type of
4045   // the expression to be complete. 'sizeof' requires the expression's type to
4046   // be complete (and will attempt to complete it if it's an array of unknown
4047   // bound).
4048   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4049     if (RequireCompleteSizedType(
4050             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4051             diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4052             E->getSourceRange()))
4053       return true;
4054   } else {
4055     if (RequireCompleteSizedExprType(
4056             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind,
4057             E->getSourceRange()))
4058       return true;
4059   }
4060 
4061   // Completing the expression's type may have changed it.
4062   ExprTy = E->getType();
4063   assert(!ExprTy->isReferenceType());
4064 
4065   if (ExprTy->isFunctionType()) {
4066     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4067       << ExprKind << E->getSourceRange();
4068     return true;
4069   }
4070 
4071   // The operand for sizeof and alignof is in an unevaluated expression context,
4072   // so side effects could result in unintended consequences.
4073   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4074       E->HasSideEffects(Context, false))
4075     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4076 
4077   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4078                                        E->getSourceRange(), ExprKind))
4079     return true;
4080 
4081   if (ExprKind == UETT_SizeOf) {
4082     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4083       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4084         QualType OType = PVD->getOriginalType();
4085         QualType Type = PVD->getType();
4086         if (Type->isPointerType() && OType->isArrayType()) {
4087           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4088             << Type << OType;
4089           Diag(PVD->getLocation(), diag::note_declared_at);
4090         }
4091       }
4092     }
4093 
4094     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4095     // decays into a pointer and returns an unintended result. This is most
4096     // likely a typo for "sizeof(array) op x".
4097     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4098       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4099                                BO->getLHS());
4100       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4101                                BO->getRHS());
4102     }
4103   }
4104 
4105   return false;
4106 }
4107 
4108 /// Check the constraints on operands to unary expression and type
4109 /// traits.
4110 ///
4111 /// This will complete any types necessary, and validate the various constraints
4112 /// on those operands.
4113 ///
4114 /// The UsualUnaryConversions() function is *not* called by this routine.
4115 /// C99 6.3.2.1p[2-4] all state:
4116 ///   Except when it is the operand of the sizeof operator ...
4117 ///
4118 /// C++ [expr.sizeof]p4
4119 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4120 ///   standard conversions are not applied to the operand of sizeof.
4121 ///
4122 /// This policy is followed for all of the unary trait expressions.
4123 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4124                                             SourceLocation OpLoc,
4125                                             SourceRange ExprRange,
4126                                             UnaryExprOrTypeTrait ExprKind) {
4127   if (ExprType->isDependentType())
4128     return false;
4129 
4130   // C++ [expr.sizeof]p2:
4131   //     When applied to a reference or a reference type, the result
4132   //     is the size of the referenced type.
4133   // C++11 [expr.alignof]p3:
4134   //     When alignof is applied to a reference type, the result
4135   //     shall be the alignment of the referenced type.
4136   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4137     ExprType = Ref->getPointeeType();
4138 
4139   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4140   //   When alignof or _Alignof is applied to an array type, the result
4141   //   is the alignment of the element type.
4142   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4143       ExprKind == UETT_OpenMPRequiredSimdAlign)
4144     ExprType = Context.getBaseElementType(ExprType);
4145 
4146   if (ExprKind == UETT_VecStep)
4147     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4148 
4149   // Whitelist some types as extensions
4150   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4151                                       ExprKind))
4152     return false;
4153 
4154   if (RequireCompleteSizedType(
4155           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4156           ExprKind, ExprRange))
4157     return true;
4158 
4159   if (ExprType->isFunctionType()) {
4160     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4161       << ExprKind << ExprRange;
4162     return true;
4163   }
4164 
4165   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4166                                        ExprKind))
4167     return true;
4168 
4169   return false;
4170 }
4171 
4172 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4173   // Cannot know anything else if the expression is dependent.
4174   if (E->isTypeDependent())
4175     return false;
4176 
4177   if (E->getObjectKind() == OK_BitField) {
4178     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4179        << 1 << E->getSourceRange();
4180     return true;
4181   }
4182 
4183   ValueDecl *D = nullptr;
4184   Expr *Inner = E->IgnoreParens();
4185   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4186     D = DRE->getDecl();
4187   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4188     D = ME->getMemberDecl();
4189   }
4190 
4191   // If it's a field, require the containing struct to have a
4192   // complete definition so that we can compute the layout.
4193   //
4194   // This can happen in C++11 onwards, either by naming the member
4195   // in a way that is not transformed into a member access expression
4196   // (in an unevaluated operand, for instance), or by naming the member
4197   // in a trailing-return-type.
4198   //
4199   // For the record, since __alignof__ on expressions is a GCC
4200   // extension, GCC seems to permit this but always gives the
4201   // nonsensical answer 0.
4202   //
4203   // We don't really need the layout here --- we could instead just
4204   // directly check for all the appropriate alignment-lowing
4205   // attributes --- but that would require duplicating a lot of
4206   // logic that just isn't worth duplicating for such a marginal
4207   // use-case.
4208   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4209     // Fast path this check, since we at least know the record has a
4210     // definition if we can find a member of it.
4211     if (!FD->getParent()->isCompleteDefinition()) {
4212       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4213         << E->getSourceRange();
4214       return true;
4215     }
4216 
4217     // Otherwise, if it's a field, and the field doesn't have
4218     // reference type, then it must have a complete type (or be a
4219     // flexible array member, which we explicitly want to
4220     // white-list anyway), which makes the following checks trivial.
4221     if (!FD->getType()->isReferenceType())
4222       return false;
4223   }
4224 
4225   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4226 }
4227 
4228 bool Sema::CheckVecStepExpr(Expr *E) {
4229   E = E->IgnoreParens();
4230 
4231   // Cannot know anything else if the expression is dependent.
4232   if (E->isTypeDependent())
4233     return false;
4234 
4235   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4236 }
4237 
4238 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4239                                         CapturingScopeInfo *CSI) {
4240   assert(T->isVariablyModifiedType());
4241   assert(CSI != nullptr);
4242 
4243   // We're going to walk down into the type and look for VLA expressions.
4244   do {
4245     const Type *Ty = T.getTypePtr();
4246     switch (Ty->getTypeClass()) {
4247 #define TYPE(Class, Base)
4248 #define ABSTRACT_TYPE(Class, Base)
4249 #define NON_CANONICAL_TYPE(Class, Base)
4250 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4251 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4252 #include "clang/AST/TypeNodes.inc"
4253       T = QualType();
4254       break;
4255     // These types are never variably-modified.
4256     case Type::Builtin:
4257     case Type::Complex:
4258     case Type::Vector:
4259     case Type::ExtVector:
4260     case Type::ConstantMatrix:
4261     case Type::Record:
4262     case Type::Enum:
4263     case Type::Elaborated:
4264     case Type::TemplateSpecialization:
4265     case Type::ObjCObject:
4266     case Type::ObjCInterface:
4267     case Type::ObjCObjectPointer:
4268     case Type::ObjCTypeParam:
4269     case Type::Pipe:
4270     case Type::ExtInt:
4271       llvm_unreachable("type class is never variably-modified!");
4272     case Type::Adjusted:
4273       T = cast<AdjustedType>(Ty)->getOriginalType();
4274       break;
4275     case Type::Decayed:
4276       T = cast<DecayedType>(Ty)->getPointeeType();
4277       break;
4278     case Type::Pointer:
4279       T = cast<PointerType>(Ty)->getPointeeType();
4280       break;
4281     case Type::BlockPointer:
4282       T = cast<BlockPointerType>(Ty)->getPointeeType();
4283       break;
4284     case Type::LValueReference:
4285     case Type::RValueReference:
4286       T = cast<ReferenceType>(Ty)->getPointeeType();
4287       break;
4288     case Type::MemberPointer:
4289       T = cast<MemberPointerType>(Ty)->getPointeeType();
4290       break;
4291     case Type::ConstantArray:
4292     case Type::IncompleteArray:
4293       // Losing element qualification here is fine.
4294       T = cast<ArrayType>(Ty)->getElementType();
4295       break;
4296     case Type::VariableArray: {
4297       // Losing element qualification here is fine.
4298       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4299 
4300       // Unknown size indication requires no size computation.
4301       // Otherwise, evaluate and record it.
4302       auto Size = VAT->getSizeExpr();
4303       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4304           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4305         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4306 
4307       T = VAT->getElementType();
4308       break;
4309     }
4310     case Type::FunctionProto:
4311     case Type::FunctionNoProto:
4312       T = cast<FunctionType>(Ty)->getReturnType();
4313       break;
4314     case Type::Paren:
4315     case Type::TypeOf:
4316     case Type::UnaryTransform:
4317     case Type::Attributed:
4318     case Type::SubstTemplateTypeParm:
4319     case Type::PackExpansion:
4320     case Type::MacroQualified:
4321       // Keep walking after single level desugaring.
4322       T = T.getSingleStepDesugaredType(Context);
4323       break;
4324     case Type::Typedef:
4325       T = cast<TypedefType>(Ty)->desugar();
4326       break;
4327     case Type::Decltype:
4328       T = cast<DecltypeType>(Ty)->desugar();
4329       break;
4330     case Type::Auto:
4331     case Type::DeducedTemplateSpecialization:
4332       T = cast<DeducedType>(Ty)->getDeducedType();
4333       break;
4334     case Type::TypeOfExpr:
4335       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4336       break;
4337     case Type::Atomic:
4338       T = cast<AtomicType>(Ty)->getValueType();
4339       break;
4340     }
4341   } while (!T.isNull() && T->isVariablyModifiedType());
4342 }
4343 
4344 /// Build a sizeof or alignof expression given a type operand.
4345 ExprResult
4346 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4347                                      SourceLocation OpLoc,
4348                                      UnaryExprOrTypeTrait ExprKind,
4349                                      SourceRange R) {
4350   if (!TInfo)
4351     return ExprError();
4352 
4353   QualType T = TInfo->getType();
4354 
4355   if (!T->isDependentType() &&
4356       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4357     return ExprError();
4358 
4359   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4360     if (auto *TT = T->getAs<TypedefType>()) {
4361       for (auto I = FunctionScopes.rbegin(),
4362                 E = std::prev(FunctionScopes.rend());
4363            I != E; ++I) {
4364         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4365         if (CSI == nullptr)
4366           break;
4367         DeclContext *DC = nullptr;
4368         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4369           DC = LSI->CallOperator;
4370         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4371           DC = CRSI->TheCapturedDecl;
4372         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4373           DC = BSI->TheDecl;
4374         if (DC) {
4375           if (DC->containsDecl(TT->getDecl()))
4376             break;
4377           captureVariablyModifiedType(Context, T, CSI);
4378         }
4379       }
4380     }
4381   }
4382 
4383   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4384   return new (Context) UnaryExprOrTypeTraitExpr(
4385       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4386 }
4387 
4388 /// Build a sizeof or alignof expression given an expression
4389 /// operand.
4390 ExprResult
4391 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4392                                      UnaryExprOrTypeTrait ExprKind) {
4393   ExprResult PE = CheckPlaceholderExpr(E);
4394   if (PE.isInvalid())
4395     return ExprError();
4396 
4397   E = PE.get();
4398 
4399   // Verify that the operand is valid.
4400   bool isInvalid = false;
4401   if (E->isTypeDependent()) {
4402     // Delay type-checking for type-dependent expressions.
4403   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4404     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4405   } else if (ExprKind == UETT_VecStep) {
4406     isInvalid = CheckVecStepExpr(E);
4407   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4408       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4409       isInvalid = true;
4410   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4411     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4412     isInvalid = true;
4413   } else {
4414     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4415   }
4416 
4417   if (isInvalid)
4418     return ExprError();
4419 
4420   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4421     PE = TransformToPotentiallyEvaluated(E);
4422     if (PE.isInvalid()) return ExprError();
4423     E = PE.get();
4424   }
4425 
4426   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4427   return new (Context) UnaryExprOrTypeTraitExpr(
4428       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4429 }
4430 
4431 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4432 /// expr and the same for @c alignof and @c __alignof
4433 /// Note that the ArgRange is invalid if isType is false.
4434 ExprResult
4435 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4436                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4437                                     void *TyOrEx, SourceRange ArgRange) {
4438   // If error parsing type, ignore.
4439   if (!TyOrEx) return ExprError();
4440 
4441   if (IsType) {
4442     TypeSourceInfo *TInfo;
4443     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4444     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4445   }
4446 
4447   Expr *ArgEx = (Expr *)TyOrEx;
4448   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4449   return Result;
4450 }
4451 
4452 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4453                                      bool IsReal) {
4454   if (V.get()->isTypeDependent())
4455     return S.Context.DependentTy;
4456 
4457   // _Real and _Imag are only l-values for normal l-values.
4458   if (V.get()->getObjectKind() != OK_Ordinary) {
4459     V = S.DefaultLvalueConversion(V.get());
4460     if (V.isInvalid())
4461       return QualType();
4462   }
4463 
4464   // These operators return the element type of a complex type.
4465   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4466     return CT->getElementType();
4467 
4468   // Otherwise they pass through real integer and floating point types here.
4469   if (V.get()->getType()->isArithmeticType())
4470     return V.get()->getType();
4471 
4472   // Test for placeholders.
4473   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4474   if (PR.isInvalid()) return QualType();
4475   if (PR.get() != V.get()) {
4476     V = PR;
4477     return CheckRealImagOperand(S, V, Loc, IsReal);
4478   }
4479 
4480   // Reject anything else.
4481   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4482     << (IsReal ? "__real" : "__imag");
4483   return QualType();
4484 }
4485 
4486 
4487 
4488 ExprResult
4489 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4490                           tok::TokenKind Kind, Expr *Input) {
4491   UnaryOperatorKind Opc;
4492   switch (Kind) {
4493   default: llvm_unreachable("Unknown unary op!");
4494   case tok::plusplus:   Opc = UO_PostInc; break;
4495   case tok::minusminus: Opc = UO_PostDec; break;
4496   }
4497 
4498   // Since this might is a postfix expression, get rid of ParenListExprs.
4499   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4500   if (Result.isInvalid()) return ExprError();
4501   Input = Result.get();
4502 
4503   return BuildUnaryOp(S, OpLoc, Opc, Input);
4504 }
4505 
4506 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4507 ///
4508 /// \return true on error
4509 static bool checkArithmeticOnObjCPointer(Sema &S,
4510                                          SourceLocation opLoc,
4511                                          Expr *op) {
4512   assert(op->getType()->isObjCObjectPointerType());
4513   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4514       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4515     return false;
4516 
4517   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4518     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4519     << op->getSourceRange();
4520   return true;
4521 }
4522 
4523 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4524   auto *BaseNoParens = Base->IgnoreParens();
4525   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4526     return MSProp->getPropertyDecl()->getType()->isArrayType();
4527   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4528 }
4529 
4530 ExprResult
4531 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4532                               Expr *idx, SourceLocation rbLoc) {
4533   if (base && !base->getType().isNull() &&
4534       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4535     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4536                                     /*Length=*/nullptr, rbLoc);
4537 
4538   // Since this might be a postfix expression, get rid of ParenListExprs.
4539   if (isa<ParenListExpr>(base)) {
4540     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4541     if (result.isInvalid()) return ExprError();
4542     base = result.get();
4543   }
4544 
4545   // A comma-expression as the index is deprecated in C++2a onwards.
4546   if (getLangOpts().CPlusPlus20 &&
4547       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4548        (isa<CXXOperatorCallExpr>(idx) &&
4549         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4550     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4551       << SourceRange(base->getBeginLoc(), rbLoc);
4552   }
4553 
4554   // Handle any non-overload placeholder types in the base and index
4555   // expressions.  We can't handle overloads here because the other
4556   // operand might be an overloadable type, in which case the overload
4557   // resolution for the operator overload should get the first crack
4558   // at the overload.
4559   bool IsMSPropertySubscript = false;
4560   if (base->getType()->isNonOverloadPlaceholderType()) {
4561     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4562     if (!IsMSPropertySubscript) {
4563       ExprResult result = CheckPlaceholderExpr(base);
4564       if (result.isInvalid())
4565         return ExprError();
4566       base = result.get();
4567     }
4568   }
4569   if (idx->getType()->isNonOverloadPlaceholderType()) {
4570     ExprResult result = CheckPlaceholderExpr(idx);
4571     if (result.isInvalid()) return ExprError();
4572     idx = result.get();
4573   }
4574 
4575   // Build an unanalyzed expression if either operand is type-dependent.
4576   if (getLangOpts().CPlusPlus &&
4577       (base->isTypeDependent() || idx->isTypeDependent())) {
4578     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4579                                             VK_LValue, OK_Ordinary, rbLoc);
4580   }
4581 
4582   // MSDN, property (C++)
4583   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4584   // This attribute can also be used in the declaration of an empty array in a
4585   // class or structure definition. For example:
4586   // __declspec(property(get=GetX, put=PutX)) int x[];
4587   // The above statement indicates that x[] can be used with one or more array
4588   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4589   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4590   if (IsMSPropertySubscript) {
4591     // Build MS property subscript expression if base is MS property reference
4592     // or MS property subscript.
4593     return new (Context) MSPropertySubscriptExpr(
4594         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4595   }
4596 
4597   // Use C++ overloaded-operator rules if either operand has record
4598   // type.  The spec says to do this if either type is *overloadable*,
4599   // but enum types can't declare subscript operators or conversion
4600   // operators, so there's nothing interesting for overload resolution
4601   // to do if there aren't any record types involved.
4602   //
4603   // ObjC pointers have their own subscripting logic that is not tied
4604   // to overload resolution and so should not take this path.
4605   if (getLangOpts().CPlusPlus &&
4606       (base->getType()->isRecordType() ||
4607        (!base->getType()->isObjCObjectPointerType() &&
4608         idx->getType()->isRecordType()))) {
4609     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4610   }
4611 
4612   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4613 
4614   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4615     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4616 
4617   return Res;
4618 }
4619 
4620 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4621   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4622   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4623 
4624   // For expressions like `&(*s).b`, the base is recorded and what should be
4625   // checked.
4626   const MemberExpr *Member = nullptr;
4627   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4628     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4629 
4630   LastRecord.PossibleDerefs.erase(StrippedExpr);
4631 }
4632 
4633 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4634   QualType ResultTy = E->getType();
4635   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4636 
4637   // Bail if the element is an array since it is not memory access.
4638   if (isa<ArrayType>(ResultTy))
4639     return;
4640 
4641   if (ResultTy->hasAttr(attr::NoDeref)) {
4642     LastRecord.PossibleDerefs.insert(E);
4643     return;
4644   }
4645 
4646   // Check if the base type is a pointer to a member access of a struct
4647   // marked with noderef.
4648   const Expr *Base = E->getBase();
4649   QualType BaseTy = Base->getType();
4650   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4651     // Not a pointer access
4652     return;
4653 
4654   const MemberExpr *Member = nullptr;
4655   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4656          Member->isArrow())
4657     Base = Member->getBase();
4658 
4659   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4660     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4661       LastRecord.PossibleDerefs.insert(E);
4662   }
4663 }
4664 
4665 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4666                                           Expr *LowerBound,
4667                                           SourceLocation ColonLoc, Expr *Length,
4668                                           SourceLocation RBLoc) {
4669   if (Base->getType()->isPlaceholderType() &&
4670       !Base->getType()->isSpecificPlaceholderType(
4671           BuiltinType::OMPArraySection)) {
4672     ExprResult Result = CheckPlaceholderExpr(Base);
4673     if (Result.isInvalid())
4674       return ExprError();
4675     Base = Result.get();
4676   }
4677   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4678     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4679     if (Result.isInvalid())
4680       return ExprError();
4681     Result = DefaultLvalueConversion(Result.get());
4682     if (Result.isInvalid())
4683       return ExprError();
4684     LowerBound = Result.get();
4685   }
4686   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4687     ExprResult Result = CheckPlaceholderExpr(Length);
4688     if (Result.isInvalid())
4689       return ExprError();
4690     Result = DefaultLvalueConversion(Result.get());
4691     if (Result.isInvalid())
4692       return ExprError();
4693     Length = Result.get();
4694   }
4695 
4696   // Build an unanalyzed expression if either operand is type-dependent.
4697   if (Base->isTypeDependent() ||
4698       (LowerBound &&
4699        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4700       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4701     return new (Context)
4702         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4703                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4704   }
4705 
4706   // Perform default conversions.
4707   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4708   QualType ResultTy;
4709   if (OriginalTy->isAnyPointerType()) {
4710     ResultTy = OriginalTy->getPointeeType();
4711   } else if (OriginalTy->isArrayType()) {
4712     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4713   } else {
4714     return ExprError(
4715         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4716         << Base->getSourceRange());
4717   }
4718   // C99 6.5.2.1p1
4719   if (LowerBound) {
4720     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4721                                                       LowerBound);
4722     if (Res.isInvalid())
4723       return ExprError(Diag(LowerBound->getExprLoc(),
4724                             diag::err_omp_typecheck_section_not_integer)
4725                        << 0 << LowerBound->getSourceRange());
4726     LowerBound = Res.get();
4727 
4728     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4729         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4730       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4731           << 0 << LowerBound->getSourceRange();
4732   }
4733   if (Length) {
4734     auto Res =
4735         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4736     if (Res.isInvalid())
4737       return ExprError(Diag(Length->getExprLoc(),
4738                             diag::err_omp_typecheck_section_not_integer)
4739                        << 1 << Length->getSourceRange());
4740     Length = Res.get();
4741 
4742     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4743         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4744       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4745           << 1 << Length->getSourceRange();
4746   }
4747 
4748   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4749   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4750   // type. Note that functions are not objects, and that (in C99 parlance)
4751   // incomplete types are not object types.
4752   if (ResultTy->isFunctionType()) {
4753     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4754         << ResultTy << Base->getSourceRange();
4755     return ExprError();
4756   }
4757 
4758   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4759                           diag::err_omp_section_incomplete_type, Base))
4760     return ExprError();
4761 
4762   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4763     Expr::EvalResult Result;
4764     if (LowerBound->EvaluateAsInt(Result, Context)) {
4765       // OpenMP 4.5, [2.4 Array Sections]
4766       // The array section must be a subset of the original array.
4767       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4768       if (LowerBoundValue.isNegative()) {
4769         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4770             << LowerBound->getSourceRange();
4771         return ExprError();
4772       }
4773     }
4774   }
4775 
4776   if (Length) {
4777     Expr::EvalResult Result;
4778     if (Length->EvaluateAsInt(Result, Context)) {
4779       // OpenMP 4.5, [2.4 Array Sections]
4780       // The length must evaluate to non-negative integers.
4781       llvm::APSInt LengthValue = Result.Val.getInt();
4782       if (LengthValue.isNegative()) {
4783         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4784             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4785             << Length->getSourceRange();
4786         return ExprError();
4787       }
4788     }
4789   } else if (ColonLoc.isValid() &&
4790              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4791                                       !OriginalTy->isVariableArrayType()))) {
4792     // OpenMP 4.5, [2.4 Array Sections]
4793     // When the size of the array dimension is not known, the length must be
4794     // specified explicitly.
4795     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4796         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4797     return ExprError();
4798   }
4799 
4800   if (!Base->getType()->isSpecificPlaceholderType(
4801           BuiltinType::OMPArraySection)) {
4802     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4803     if (Result.isInvalid())
4804       return ExprError();
4805     Base = Result.get();
4806   }
4807   return new (Context)
4808       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4809                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4810 }
4811 
4812 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4813                                           SourceLocation RParenLoc,
4814                                           ArrayRef<Expr *> Dims,
4815                                           ArrayRef<SourceRange> Brackets) {
4816   if (Base->getType()->isPlaceholderType()) {
4817     ExprResult Result = CheckPlaceholderExpr(Base);
4818     if (Result.isInvalid())
4819       return ExprError();
4820     Result = DefaultLvalueConversion(Result.get());
4821     if (Result.isInvalid())
4822       return ExprError();
4823     Base = Result.get();
4824   }
4825   QualType BaseTy = Base->getType();
4826   // Delay analysis of the types/expressions if instantiation/specialization is
4827   // required.
4828   if (!BaseTy->isPointerType() && Base->isTypeDependent())
4829     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
4830                                        LParenLoc, RParenLoc, Dims, Brackets);
4831   if (!BaseTy->isPointerType() ||
4832       (!Base->isTypeDependent() &&
4833        BaseTy->getPointeeType()->isIncompleteType()))
4834     return ExprError(Diag(Base->getExprLoc(),
4835                           diag::err_omp_non_pointer_type_array_shaping_base)
4836                      << Base->getSourceRange());
4837 
4838   SmallVector<Expr *, 4> NewDims;
4839   bool ErrorFound = false;
4840   for (Expr *Dim : Dims) {
4841     if (Dim->getType()->isPlaceholderType()) {
4842       ExprResult Result = CheckPlaceholderExpr(Dim);
4843       if (Result.isInvalid()) {
4844         ErrorFound = true;
4845         continue;
4846       }
4847       Result = DefaultLvalueConversion(Result.get());
4848       if (Result.isInvalid()) {
4849         ErrorFound = true;
4850         continue;
4851       }
4852       Dim = Result.get();
4853     }
4854     if (!Dim->isTypeDependent()) {
4855       ExprResult Result =
4856           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
4857       if (Result.isInvalid()) {
4858         ErrorFound = true;
4859         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
4860             << Dim->getSourceRange();
4861         continue;
4862       }
4863       Dim = Result.get();
4864       Expr::EvalResult EvResult;
4865       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
4866         // OpenMP 5.0, [2.1.4 Array Shaping]
4867         // Each si is an integral type expression that must evaluate to a
4868         // positive integer.
4869         llvm::APSInt Value = EvResult.Val.getInt();
4870         if (!Value.isStrictlyPositive()) {
4871           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
4872               << Value.toString(/*Radix=*/10, /*Signed=*/true)
4873               << Dim->getSourceRange();
4874           ErrorFound = true;
4875           continue;
4876         }
4877       }
4878     }
4879     NewDims.push_back(Dim);
4880   }
4881   if (ErrorFound)
4882     return ExprError();
4883   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
4884                                      LParenLoc, RParenLoc, NewDims, Brackets);
4885 }
4886 
4887 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
4888                                       SourceLocation LLoc, SourceLocation RLoc,
4889                                       ArrayRef<OMPIteratorData> Data) {
4890   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
4891   bool IsCorrect = true;
4892   for (const OMPIteratorData &D : Data) {
4893     TypeSourceInfo *TInfo = nullptr;
4894     SourceLocation StartLoc;
4895     QualType DeclTy;
4896     if (!D.Type.getAsOpaquePtr()) {
4897       // OpenMP 5.0, 2.1.6 Iterators
4898       // In an iterator-specifier, if the iterator-type is not specified then
4899       // the type of that iterator is of int type.
4900       DeclTy = Context.IntTy;
4901       StartLoc = D.DeclIdentLoc;
4902     } else {
4903       DeclTy = GetTypeFromParser(D.Type, &TInfo);
4904       StartLoc = TInfo->getTypeLoc().getBeginLoc();
4905     }
4906 
4907     bool IsDeclTyDependent = DeclTy->isDependentType() ||
4908                              DeclTy->containsUnexpandedParameterPack() ||
4909                              DeclTy->isInstantiationDependentType();
4910     if (!IsDeclTyDependent) {
4911       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
4912         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4913         // The iterator-type must be an integral or pointer type.
4914         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4915             << DeclTy;
4916         IsCorrect = false;
4917         continue;
4918       }
4919       if (DeclTy.isConstant(Context)) {
4920         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
4921         // The iterator-type must not be const qualified.
4922         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
4923             << DeclTy;
4924         IsCorrect = false;
4925         continue;
4926       }
4927     }
4928 
4929     // Iterator declaration.
4930     assert(D.DeclIdent && "Identifier expected.");
4931     // Always try to create iterator declarator to avoid extra error messages
4932     // about unknown declarations use.
4933     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
4934                                D.DeclIdent, DeclTy, TInfo, SC_None);
4935     VD->setImplicit();
4936     if (S) {
4937       // Check for conflicting previous declaration.
4938       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
4939       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4940                             ForVisibleRedeclaration);
4941       Previous.suppressDiagnostics();
4942       LookupName(Previous, S);
4943 
4944       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
4945                            /*AllowInlineNamespace=*/false);
4946       if (!Previous.empty()) {
4947         NamedDecl *Old = Previous.getRepresentativeDecl();
4948         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
4949         Diag(Old->getLocation(), diag::note_previous_definition);
4950       } else {
4951         PushOnScopeChains(VD, S);
4952       }
4953     } else {
4954       CurContext->addDecl(VD);
4955     }
4956     Expr *Begin = D.Range.Begin;
4957     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
4958       ExprResult BeginRes =
4959           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
4960       Begin = BeginRes.get();
4961     }
4962     Expr *End = D.Range.End;
4963     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
4964       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
4965       End = EndRes.get();
4966     }
4967     Expr *Step = D.Range.Step;
4968     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
4969       if (!Step->getType()->isIntegralType(Context)) {
4970         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
4971             << Step << Step->getSourceRange();
4972         IsCorrect = false;
4973         continue;
4974       }
4975       llvm::APSInt Result;
4976       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
4977       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
4978       // If the step expression of a range-specification equals zero, the
4979       // behavior is unspecified.
4980       if (IsConstant && Result.isNullValue()) {
4981         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
4982             << Step << Step->getSourceRange();
4983         IsCorrect = false;
4984         continue;
4985       }
4986     }
4987     if (!Begin || !End || !IsCorrect) {
4988       IsCorrect = false;
4989       continue;
4990     }
4991     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
4992     IDElem.IteratorDecl = VD;
4993     IDElem.AssignmentLoc = D.AssignLoc;
4994     IDElem.Range.Begin = Begin;
4995     IDElem.Range.End = End;
4996     IDElem.Range.Step = Step;
4997     IDElem.ColonLoc = D.ColonLoc;
4998     IDElem.SecondColonLoc = D.SecColonLoc;
4999   }
5000   if (!IsCorrect) {
5001     // Invalidate all created iterator declarations if error is found.
5002     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5003       if (Decl *ID = D.IteratorDecl)
5004         ID->setInvalidDecl();
5005     }
5006     return ExprError();
5007   }
5008   SmallVector<OMPIteratorHelperData, 4> Helpers;
5009   if (!CurContext->isDependentContext()) {
5010     // Build number of ityeration for each iteration range.
5011     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5012     // ((Begini-Stepi-1-Endi) / -Stepi);
5013     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5014       // (Endi - Begini)
5015       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5016                                           D.Range.Begin);
5017       if(!Res.isUsable()) {
5018         IsCorrect = false;
5019         continue;
5020       }
5021       ExprResult St, St1;
5022       if (D.Range.Step) {
5023         St = D.Range.Step;
5024         // (Endi - Begini) + Stepi
5025         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5026         if (!Res.isUsable()) {
5027           IsCorrect = false;
5028           continue;
5029         }
5030         // (Endi - Begini) + Stepi - 1
5031         Res =
5032             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5033                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5034         if (!Res.isUsable()) {
5035           IsCorrect = false;
5036           continue;
5037         }
5038         // ((Endi - Begini) + Stepi - 1) / Stepi
5039         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5040         if (!Res.isUsable()) {
5041           IsCorrect = false;
5042           continue;
5043         }
5044         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5045         // (Begini - Endi)
5046         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5047                                              D.Range.Begin, D.Range.End);
5048         if (!Res1.isUsable()) {
5049           IsCorrect = false;
5050           continue;
5051         }
5052         // (Begini - Endi) - Stepi
5053         Res1 =
5054             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5055         if (!Res1.isUsable()) {
5056           IsCorrect = false;
5057           continue;
5058         }
5059         // (Begini - Endi) - Stepi - 1
5060         Res1 =
5061             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5062                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5063         if (!Res1.isUsable()) {
5064           IsCorrect = false;
5065           continue;
5066         }
5067         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5068         Res1 =
5069             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5070         if (!Res1.isUsable()) {
5071           IsCorrect = false;
5072           continue;
5073         }
5074         // Stepi > 0.
5075         ExprResult CmpRes =
5076             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5077                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5078         if (!CmpRes.isUsable()) {
5079           IsCorrect = false;
5080           continue;
5081         }
5082         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5083                                  Res.get(), Res1.get());
5084         if (!Res.isUsable()) {
5085           IsCorrect = false;
5086           continue;
5087         }
5088       }
5089       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5090       if (!Res.isUsable()) {
5091         IsCorrect = false;
5092         continue;
5093       }
5094 
5095       // Build counter update.
5096       // Build counter.
5097       auto *CounterVD =
5098           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5099                           D.IteratorDecl->getBeginLoc(), nullptr,
5100                           Res.get()->getType(), nullptr, SC_None);
5101       CounterVD->setImplicit();
5102       ExprResult RefRes =
5103           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5104                            D.IteratorDecl->getBeginLoc());
5105       // Build counter update.
5106       // I = Begini + counter * Stepi;
5107       ExprResult UpdateRes;
5108       if (D.Range.Step) {
5109         UpdateRes = CreateBuiltinBinOp(
5110             D.AssignmentLoc, BO_Mul,
5111             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5112       } else {
5113         UpdateRes = DefaultLvalueConversion(RefRes.get());
5114       }
5115       if (!UpdateRes.isUsable()) {
5116         IsCorrect = false;
5117         continue;
5118       }
5119       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5120                                      UpdateRes.get());
5121       if (!UpdateRes.isUsable()) {
5122         IsCorrect = false;
5123         continue;
5124       }
5125       ExprResult VDRes =
5126           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5127                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5128                            D.IteratorDecl->getBeginLoc());
5129       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5130                                      UpdateRes.get());
5131       if (!UpdateRes.isUsable()) {
5132         IsCorrect = false;
5133         continue;
5134       }
5135       UpdateRes =
5136           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5137       if (!UpdateRes.isUsable()) {
5138         IsCorrect = false;
5139         continue;
5140       }
5141       ExprResult CounterUpdateRes =
5142           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5143       if (!CounterUpdateRes.isUsable()) {
5144         IsCorrect = false;
5145         continue;
5146       }
5147       CounterUpdateRes =
5148           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5149       if (!CounterUpdateRes.isUsable()) {
5150         IsCorrect = false;
5151         continue;
5152       }
5153       OMPIteratorHelperData &HD = Helpers.emplace_back();
5154       HD.CounterVD = CounterVD;
5155       HD.Upper = Res.get();
5156       HD.Update = UpdateRes.get();
5157       HD.CounterUpdate = CounterUpdateRes.get();
5158     }
5159   } else {
5160     Helpers.assign(ID.size(), {});
5161   }
5162   if (!IsCorrect) {
5163     // Invalidate all created iterator declarations if error is found.
5164     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5165       if (Decl *ID = D.IteratorDecl)
5166         ID->setInvalidDecl();
5167     }
5168     return ExprError();
5169   }
5170   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5171                                  LLoc, RLoc, ID, Helpers);
5172 }
5173 
5174 ExprResult
5175 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5176                                       Expr *Idx, SourceLocation RLoc) {
5177   Expr *LHSExp = Base;
5178   Expr *RHSExp = Idx;
5179 
5180   ExprValueKind VK = VK_LValue;
5181   ExprObjectKind OK = OK_Ordinary;
5182 
5183   // Per C++ core issue 1213, the result is an xvalue if either operand is
5184   // a non-lvalue array, and an lvalue otherwise.
5185   if (getLangOpts().CPlusPlus11) {
5186     for (auto *Op : {LHSExp, RHSExp}) {
5187       Op = Op->IgnoreImplicit();
5188       if (Op->getType()->isArrayType() && !Op->isLValue())
5189         VK = VK_XValue;
5190     }
5191   }
5192 
5193   // Perform default conversions.
5194   if (!LHSExp->getType()->getAs<VectorType>()) {
5195     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5196     if (Result.isInvalid())
5197       return ExprError();
5198     LHSExp = Result.get();
5199   }
5200   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5201   if (Result.isInvalid())
5202     return ExprError();
5203   RHSExp = Result.get();
5204 
5205   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5206 
5207   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5208   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5209   // in the subscript position. As a result, we need to derive the array base
5210   // and index from the expression types.
5211   Expr *BaseExpr, *IndexExpr;
5212   QualType ResultType;
5213   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5214     BaseExpr = LHSExp;
5215     IndexExpr = RHSExp;
5216     ResultType = Context.DependentTy;
5217   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5218     BaseExpr = LHSExp;
5219     IndexExpr = RHSExp;
5220     ResultType = PTy->getPointeeType();
5221   } else if (const ObjCObjectPointerType *PTy =
5222                LHSTy->getAs<ObjCObjectPointerType>()) {
5223     BaseExpr = LHSExp;
5224     IndexExpr = RHSExp;
5225 
5226     // Use custom logic if this should be the pseudo-object subscript
5227     // expression.
5228     if (!LangOpts.isSubscriptPointerArithmetic())
5229       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5230                                           nullptr);
5231 
5232     ResultType = PTy->getPointeeType();
5233   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5234      // Handle the uncommon case of "123[Ptr]".
5235     BaseExpr = RHSExp;
5236     IndexExpr = LHSExp;
5237     ResultType = PTy->getPointeeType();
5238   } else if (const ObjCObjectPointerType *PTy =
5239                RHSTy->getAs<ObjCObjectPointerType>()) {
5240      // Handle the uncommon case of "123[Ptr]".
5241     BaseExpr = RHSExp;
5242     IndexExpr = LHSExp;
5243     ResultType = PTy->getPointeeType();
5244     if (!LangOpts.isSubscriptPointerArithmetic()) {
5245       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5246         << ResultType << BaseExpr->getSourceRange();
5247       return ExprError();
5248     }
5249   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5250     BaseExpr = LHSExp;    // vectors: V[123]
5251     IndexExpr = RHSExp;
5252     // We apply C++ DR1213 to vector subscripting too.
5253     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5254       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5255       if (Materialized.isInvalid())
5256         return ExprError();
5257       LHSExp = Materialized.get();
5258     }
5259     VK = LHSExp->getValueKind();
5260     if (VK != VK_RValue)
5261       OK = OK_VectorComponent;
5262 
5263     ResultType = VTy->getElementType();
5264     QualType BaseType = BaseExpr->getType();
5265     Qualifiers BaseQuals = BaseType.getQualifiers();
5266     Qualifiers MemberQuals = ResultType.getQualifiers();
5267     Qualifiers Combined = BaseQuals + MemberQuals;
5268     if (Combined != MemberQuals)
5269       ResultType = Context.getQualifiedType(ResultType, Combined);
5270   } else if (LHSTy->isArrayType()) {
5271     // If we see an array that wasn't promoted by
5272     // DefaultFunctionArrayLvalueConversion, it must be an array that
5273     // wasn't promoted because of the C90 rule that doesn't
5274     // allow promoting non-lvalue arrays.  Warn, then
5275     // force the promotion here.
5276     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5277         << LHSExp->getSourceRange();
5278     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5279                                CK_ArrayToPointerDecay).get();
5280     LHSTy = LHSExp->getType();
5281 
5282     BaseExpr = LHSExp;
5283     IndexExpr = RHSExp;
5284     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5285   } else if (RHSTy->isArrayType()) {
5286     // Same as previous, except for 123[f().a] case
5287     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5288         << RHSExp->getSourceRange();
5289     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5290                                CK_ArrayToPointerDecay).get();
5291     RHSTy = RHSExp->getType();
5292 
5293     BaseExpr = RHSExp;
5294     IndexExpr = LHSExp;
5295     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5296   } else {
5297     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5298        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5299   }
5300   // C99 6.5.2.1p1
5301   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5302     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5303                      << IndexExpr->getSourceRange());
5304 
5305   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5306        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5307          && !IndexExpr->isTypeDependent())
5308     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5309 
5310   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5311   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5312   // type. Note that Functions are not objects, and that (in C99 parlance)
5313   // incomplete types are not object types.
5314   if (ResultType->isFunctionType()) {
5315     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5316         << ResultType << BaseExpr->getSourceRange();
5317     return ExprError();
5318   }
5319 
5320   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5321     // GNU extension: subscripting on pointer to void
5322     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5323       << BaseExpr->getSourceRange();
5324 
5325     // C forbids expressions of unqualified void type from being l-values.
5326     // See IsCForbiddenLValueType.
5327     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5328   } else if (!ResultType->isDependentType() &&
5329              RequireCompleteSizedType(
5330                  LLoc, ResultType,
5331                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5332     return ExprError();
5333 
5334   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5335          !ResultType.isCForbiddenLValueType());
5336 
5337   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5338       FunctionScopes.size() > 1) {
5339     if (auto *TT =
5340             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5341       for (auto I = FunctionScopes.rbegin(),
5342                 E = std::prev(FunctionScopes.rend());
5343            I != E; ++I) {
5344         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5345         if (CSI == nullptr)
5346           break;
5347         DeclContext *DC = nullptr;
5348         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5349           DC = LSI->CallOperator;
5350         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5351           DC = CRSI->TheCapturedDecl;
5352         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5353           DC = BSI->TheDecl;
5354         if (DC) {
5355           if (DC->containsDecl(TT->getDecl()))
5356             break;
5357           captureVariablyModifiedType(
5358               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5359         }
5360       }
5361     }
5362   }
5363 
5364   return new (Context)
5365       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5366 }
5367 
5368 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5369                                   ParmVarDecl *Param) {
5370   if (Param->hasUnparsedDefaultArg()) {
5371     Diag(CallLoc,
5372          diag::err_use_of_default_argument_to_function_declared_later) <<
5373       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5374     Diag(UnparsedDefaultArgLocs[Param],
5375          diag::note_default_argument_declared_here);
5376     return true;
5377   }
5378 
5379   if (Param->hasUninstantiatedDefaultArg()) {
5380     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
5381 
5382     EnterExpressionEvaluationContext EvalContext(
5383         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5384 
5385     // Instantiate the expression.
5386     //
5387     // FIXME: Pass in a correct Pattern argument, otherwise
5388     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
5389     //
5390     // template<typename T>
5391     // struct A {
5392     //   static int FooImpl();
5393     //
5394     //   template<typename Tp>
5395     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
5396     //   // template argument list [[T], [Tp]], should be [[Tp]].
5397     //   friend A<Tp> Foo(int a);
5398     // };
5399     //
5400     // template<typename T>
5401     // A<T> Foo(int a = A<T>::FooImpl());
5402     MultiLevelTemplateArgumentList MutiLevelArgList
5403       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
5404 
5405     InstantiatingTemplate Inst(*this, CallLoc, Param,
5406                                MutiLevelArgList.getInnermost());
5407     if (Inst.isInvalid())
5408       return true;
5409     if (Inst.isAlreadyInstantiating()) {
5410       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5411       Param->setInvalidDecl();
5412       return true;
5413     }
5414 
5415     ExprResult Result;
5416     {
5417       // C++ [dcl.fct.default]p5:
5418       //   The names in the [default argument] expression are bound, and
5419       //   the semantic constraints are checked, at the point where the
5420       //   default argument expression appears.
5421       ContextRAII SavedContext(*this, FD);
5422       LocalInstantiationScope Local(*this);
5423       runWithSufficientStackSpace(CallLoc, [&] {
5424         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
5425                                   /*DirectInit*/false);
5426       });
5427     }
5428     if (Result.isInvalid())
5429       return true;
5430 
5431     // Check the expression as an initializer for the parameter.
5432     InitializedEntity Entity
5433       = InitializedEntity::InitializeParameter(Context, Param);
5434     InitializationKind Kind = InitializationKind::CreateCopy(
5435         Param->getLocation(),
5436         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
5437     Expr *ResultE = Result.getAs<Expr>();
5438 
5439     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
5440     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
5441     if (Result.isInvalid())
5442       return true;
5443 
5444     Result =
5445         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5446                             /*DiscardedValue*/ false);
5447     if (Result.isInvalid())
5448       return true;
5449 
5450     // Remember the instantiated default argument.
5451     Param->setDefaultArg(Result.getAs<Expr>());
5452     if (ASTMutationListener *L = getASTMutationListener()) {
5453       L->DefaultArgumentInstantiated(Param);
5454     }
5455   }
5456 
5457   // If the default argument expression is not set yet, we are building it now.
5458   if (!Param->hasInit()) {
5459     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5460     Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5461     Param->setInvalidDecl();
5462     return true;
5463   }
5464 
5465   // If the default expression creates temporaries, we need to
5466   // push them to the current stack of expression temporaries so they'll
5467   // be properly destroyed.
5468   // FIXME: We should really be rebuilding the default argument with new
5469   // bound temporaries; see the comment in PR5810.
5470   // We don't need to do that with block decls, though, because
5471   // blocks in default argument expression can never capture anything.
5472   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5473     // Set the "needs cleanups" bit regardless of whether there are
5474     // any explicit objects.
5475     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5476 
5477     // Append all the objects to the cleanup list.  Right now, this
5478     // should always be a no-op, because blocks in default argument
5479     // expressions should never be able to capture anything.
5480     assert(!Init->getNumObjects() &&
5481            "default argument expression has capturing blocks?");
5482   }
5483 
5484   // We already type-checked the argument, so we know it works.
5485   // Just mark all of the declarations in this potentially-evaluated expression
5486   // as being "referenced".
5487   EnterExpressionEvaluationContext EvalContext(
5488       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5489   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5490                                    /*SkipLocalVariables=*/true);
5491   return false;
5492 }
5493 
5494 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5495                                         FunctionDecl *FD, ParmVarDecl *Param) {
5496   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5497     return ExprError();
5498   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5499 }
5500 
5501 Sema::VariadicCallType
5502 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5503                           Expr *Fn) {
5504   if (Proto && Proto->isVariadic()) {
5505     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5506       return VariadicConstructor;
5507     else if (Fn && Fn->getType()->isBlockPointerType())
5508       return VariadicBlock;
5509     else if (FDecl) {
5510       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5511         if (Method->isInstance())
5512           return VariadicMethod;
5513     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5514       return VariadicMethod;
5515     return VariadicFunction;
5516   }
5517   return VariadicDoesNotApply;
5518 }
5519 
5520 namespace {
5521 class FunctionCallCCC final : public FunctionCallFilterCCC {
5522 public:
5523   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5524                   unsigned NumArgs, MemberExpr *ME)
5525       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5526         FunctionName(FuncName) {}
5527 
5528   bool ValidateCandidate(const TypoCorrection &candidate) override {
5529     if (!candidate.getCorrectionSpecifier() ||
5530         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5531       return false;
5532     }
5533 
5534     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5535   }
5536 
5537   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5538     return std::make_unique<FunctionCallCCC>(*this);
5539   }
5540 
5541 private:
5542   const IdentifierInfo *const FunctionName;
5543 };
5544 }
5545 
5546 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5547                                                FunctionDecl *FDecl,
5548                                                ArrayRef<Expr *> Args) {
5549   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5550   DeclarationName FuncName = FDecl->getDeclName();
5551   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5552 
5553   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5554   if (TypoCorrection Corrected = S.CorrectTypo(
5555           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5556           S.getScopeForContext(S.CurContext), nullptr, CCC,
5557           Sema::CTK_ErrorRecovery)) {
5558     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5559       if (Corrected.isOverloaded()) {
5560         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5561         OverloadCandidateSet::iterator Best;
5562         for (NamedDecl *CD : Corrected) {
5563           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5564             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5565                                    OCS);
5566         }
5567         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5568         case OR_Success:
5569           ND = Best->FoundDecl;
5570           Corrected.setCorrectionDecl(ND);
5571           break;
5572         default:
5573           break;
5574         }
5575       }
5576       ND = ND->getUnderlyingDecl();
5577       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5578         return Corrected;
5579     }
5580   }
5581   return TypoCorrection();
5582 }
5583 
5584 /// ConvertArgumentsForCall - Converts the arguments specified in
5585 /// Args/NumArgs to the parameter types of the function FDecl with
5586 /// function prototype Proto. Call is the call expression itself, and
5587 /// Fn is the function expression. For a C++ member function, this
5588 /// routine does not attempt to convert the object argument. Returns
5589 /// true if the call is ill-formed.
5590 bool
5591 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5592                               FunctionDecl *FDecl,
5593                               const FunctionProtoType *Proto,
5594                               ArrayRef<Expr *> Args,
5595                               SourceLocation RParenLoc,
5596                               bool IsExecConfig) {
5597   // Bail out early if calling a builtin with custom typechecking.
5598   if (FDecl)
5599     if (unsigned ID = FDecl->getBuiltinID())
5600       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5601         return false;
5602 
5603   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5604   // assignment, to the types of the corresponding parameter, ...
5605   unsigned NumParams = Proto->getNumParams();
5606   bool Invalid = false;
5607   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5608   unsigned FnKind = Fn->getType()->isBlockPointerType()
5609                        ? 1 /* block */
5610                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5611                                        : 0 /* function */);
5612 
5613   // If too few arguments are available (and we don't have default
5614   // arguments for the remaining parameters), don't make the call.
5615   if (Args.size() < NumParams) {
5616     if (Args.size() < MinArgs) {
5617       TypoCorrection TC;
5618       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5619         unsigned diag_id =
5620             MinArgs == NumParams && !Proto->isVariadic()
5621                 ? diag::err_typecheck_call_too_few_args_suggest
5622                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5623         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5624                                         << static_cast<unsigned>(Args.size())
5625                                         << TC.getCorrectionRange());
5626       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5627         Diag(RParenLoc,
5628              MinArgs == NumParams && !Proto->isVariadic()
5629                  ? diag::err_typecheck_call_too_few_args_one
5630                  : diag::err_typecheck_call_too_few_args_at_least_one)
5631             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5632       else
5633         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5634                             ? diag::err_typecheck_call_too_few_args
5635                             : diag::err_typecheck_call_too_few_args_at_least)
5636             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5637             << Fn->getSourceRange();
5638 
5639       // Emit the location of the prototype.
5640       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5641         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5642 
5643       return true;
5644     }
5645     // We reserve space for the default arguments when we create
5646     // the call expression, before calling ConvertArgumentsForCall.
5647     assert((Call->getNumArgs() == NumParams) &&
5648            "We should have reserved space for the default arguments before!");
5649   }
5650 
5651   // If too many are passed and not variadic, error on the extras and drop
5652   // them.
5653   if (Args.size() > NumParams) {
5654     if (!Proto->isVariadic()) {
5655       TypoCorrection TC;
5656       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5657         unsigned diag_id =
5658             MinArgs == NumParams && !Proto->isVariadic()
5659                 ? diag::err_typecheck_call_too_many_args_suggest
5660                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5661         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5662                                         << static_cast<unsigned>(Args.size())
5663                                         << TC.getCorrectionRange());
5664       } else if (NumParams == 1 && FDecl &&
5665                  FDecl->getParamDecl(0)->getDeclName())
5666         Diag(Args[NumParams]->getBeginLoc(),
5667              MinArgs == NumParams
5668                  ? diag::err_typecheck_call_too_many_args_one
5669                  : diag::err_typecheck_call_too_many_args_at_most_one)
5670             << FnKind << FDecl->getParamDecl(0)
5671             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5672             << SourceRange(Args[NumParams]->getBeginLoc(),
5673                            Args.back()->getEndLoc());
5674       else
5675         Diag(Args[NumParams]->getBeginLoc(),
5676              MinArgs == NumParams
5677                  ? diag::err_typecheck_call_too_many_args
5678                  : diag::err_typecheck_call_too_many_args_at_most)
5679             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5680             << Fn->getSourceRange()
5681             << SourceRange(Args[NumParams]->getBeginLoc(),
5682                            Args.back()->getEndLoc());
5683 
5684       // Emit the location of the prototype.
5685       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5686         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5687 
5688       // This deletes the extra arguments.
5689       Call->shrinkNumArgs(NumParams);
5690       return true;
5691     }
5692   }
5693   SmallVector<Expr *, 8> AllArgs;
5694   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5695 
5696   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5697                                    AllArgs, CallType);
5698   if (Invalid)
5699     return true;
5700   unsigned TotalNumArgs = AllArgs.size();
5701   for (unsigned i = 0; i < TotalNumArgs; ++i)
5702     Call->setArg(i, AllArgs[i]);
5703 
5704   return false;
5705 }
5706 
5707 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5708                                   const FunctionProtoType *Proto,
5709                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5710                                   SmallVectorImpl<Expr *> &AllArgs,
5711                                   VariadicCallType CallType, bool AllowExplicit,
5712                                   bool IsListInitialization) {
5713   unsigned NumParams = Proto->getNumParams();
5714   bool Invalid = false;
5715   size_t ArgIx = 0;
5716   // Continue to check argument types (even if we have too few/many args).
5717   for (unsigned i = FirstParam; i < NumParams; i++) {
5718     QualType ProtoArgType = Proto->getParamType(i);
5719 
5720     Expr *Arg;
5721     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5722     if (ArgIx < Args.size()) {
5723       Arg = Args[ArgIx++];
5724 
5725       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5726                               diag::err_call_incomplete_argument, Arg))
5727         return true;
5728 
5729       // Strip the unbridged-cast placeholder expression off, if applicable.
5730       bool CFAudited = false;
5731       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5732           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5733           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5734         Arg = stripARCUnbridgedCast(Arg);
5735       else if (getLangOpts().ObjCAutoRefCount &&
5736                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5737                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5738         CFAudited = true;
5739 
5740       if (Proto->getExtParameterInfo(i).isNoEscape())
5741         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5742           BE->getBlockDecl()->setDoesNotEscape();
5743 
5744       InitializedEntity Entity =
5745           Param ? InitializedEntity::InitializeParameter(Context, Param,
5746                                                          ProtoArgType)
5747                 : InitializedEntity::InitializeParameter(
5748                       Context, ProtoArgType, Proto->isParamConsumed(i));
5749 
5750       // Remember that parameter belongs to a CF audited API.
5751       if (CFAudited)
5752         Entity.setParameterCFAudited();
5753 
5754       ExprResult ArgE = PerformCopyInitialization(
5755           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5756       if (ArgE.isInvalid())
5757         return true;
5758 
5759       Arg = ArgE.getAs<Expr>();
5760     } else {
5761       assert(Param && "can't use default arguments without a known callee");
5762 
5763       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5764       if (ArgExpr.isInvalid())
5765         return true;
5766 
5767       Arg = ArgExpr.getAs<Expr>();
5768     }
5769 
5770     // Check for array bounds violations for each argument to the call. This
5771     // check only triggers warnings when the argument isn't a more complex Expr
5772     // with its own checking, such as a BinaryOperator.
5773     CheckArrayAccess(Arg);
5774 
5775     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5776     CheckStaticArrayArgument(CallLoc, Param, Arg);
5777 
5778     AllArgs.push_back(Arg);
5779   }
5780 
5781   // If this is a variadic call, handle args passed through "...".
5782   if (CallType != VariadicDoesNotApply) {
5783     // Assume that extern "C" functions with variadic arguments that
5784     // return __unknown_anytype aren't *really* variadic.
5785     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5786         FDecl->isExternC()) {
5787       for (Expr *A : Args.slice(ArgIx)) {
5788         QualType paramType; // ignored
5789         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5790         Invalid |= arg.isInvalid();
5791         AllArgs.push_back(arg.get());
5792       }
5793 
5794     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5795     } else {
5796       for (Expr *A : Args.slice(ArgIx)) {
5797         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5798         Invalid |= Arg.isInvalid();
5799         // Copy blocks to the heap.
5800         if (A->getType()->isBlockPointerType())
5801           maybeExtendBlockObject(Arg);
5802         AllArgs.push_back(Arg.get());
5803       }
5804     }
5805 
5806     // Check for array bounds violations.
5807     for (Expr *A : Args.slice(ArgIx))
5808       CheckArrayAccess(A);
5809   }
5810   return Invalid;
5811 }
5812 
5813 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5814   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5815   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5816     TL = DTL.getOriginalLoc();
5817   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5818     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5819       << ATL.getLocalSourceRange();
5820 }
5821 
5822 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5823 /// array parameter, check that it is non-null, and that if it is formed by
5824 /// array-to-pointer decay, the underlying array is sufficiently large.
5825 ///
5826 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5827 /// array type derivation, then for each call to the function, the value of the
5828 /// corresponding actual argument shall provide access to the first element of
5829 /// an array with at least as many elements as specified by the size expression.
5830 void
5831 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5832                                ParmVarDecl *Param,
5833                                const Expr *ArgExpr) {
5834   // Static array parameters are not supported in C++.
5835   if (!Param || getLangOpts().CPlusPlus)
5836     return;
5837 
5838   QualType OrigTy = Param->getOriginalType();
5839 
5840   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5841   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5842     return;
5843 
5844   if (ArgExpr->isNullPointerConstant(Context,
5845                                      Expr::NPC_NeverValueDependent)) {
5846     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5847     DiagnoseCalleeStaticArrayParam(*this, Param);
5848     return;
5849   }
5850 
5851   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5852   if (!CAT)
5853     return;
5854 
5855   const ConstantArrayType *ArgCAT =
5856     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5857   if (!ArgCAT)
5858     return;
5859 
5860   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5861                                              ArgCAT->getElementType())) {
5862     if (ArgCAT->getSize().ult(CAT->getSize())) {
5863       Diag(CallLoc, diag::warn_static_array_too_small)
5864           << ArgExpr->getSourceRange()
5865           << (unsigned)ArgCAT->getSize().getZExtValue()
5866           << (unsigned)CAT->getSize().getZExtValue() << 0;
5867       DiagnoseCalleeStaticArrayParam(*this, Param);
5868     }
5869     return;
5870   }
5871 
5872   Optional<CharUnits> ArgSize =
5873       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5874   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5875   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5876     Diag(CallLoc, diag::warn_static_array_too_small)
5877         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5878         << (unsigned)ParmSize->getQuantity() << 1;
5879     DiagnoseCalleeStaticArrayParam(*this, Param);
5880   }
5881 }
5882 
5883 /// Given a function expression of unknown-any type, try to rebuild it
5884 /// to have a function type.
5885 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5886 
5887 /// Is the given type a placeholder that we need to lower out
5888 /// immediately during argument processing?
5889 static bool isPlaceholderToRemoveAsArg(QualType type) {
5890   // Placeholders are never sugared.
5891   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5892   if (!placeholder) return false;
5893 
5894   switch (placeholder->getKind()) {
5895   // Ignore all the non-placeholder types.
5896 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5897   case BuiltinType::Id:
5898 #include "clang/Basic/OpenCLImageTypes.def"
5899 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5900   case BuiltinType::Id:
5901 #include "clang/Basic/OpenCLExtensionTypes.def"
5902   // In practice we'll never use this, since all SVE types are sugared
5903   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5904 #define SVE_TYPE(Name, Id, SingletonId) \
5905   case BuiltinType::Id:
5906 #include "clang/Basic/AArch64SVEACLETypes.def"
5907 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5908 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5909 #include "clang/AST/BuiltinTypes.def"
5910     return false;
5911 
5912   // We cannot lower out overload sets; they might validly be resolved
5913   // by the call machinery.
5914   case BuiltinType::Overload:
5915     return false;
5916 
5917   // Unbridged casts in ARC can be handled in some call positions and
5918   // should be left in place.
5919   case BuiltinType::ARCUnbridgedCast:
5920     return false;
5921 
5922   // Pseudo-objects should be converted as soon as possible.
5923   case BuiltinType::PseudoObject:
5924     return true;
5925 
5926   // The debugger mode could theoretically but currently does not try
5927   // to resolve unknown-typed arguments based on known parameter types.
5928   case BuiltinType::UnknownAny:
5929     return true;
5930 
5931   // These are always invalid as call arguments and should be reported.
5932   case BuiltinType::BoundMember:
5933   case BuiltinType::BuiltinFn:
5934   case BuiltinType::OMPArraySection:
5935   case BuiltinType::OMPArrayShaping:
5936   case BuiltinType::OMPIterator:
5937     return true;
5938 
5939   }
5940   llvm_unreachable("bad builtin type kind");
5941 }
5942 
5943 /// Check an argument list for placeholders that we won't try to
5944 /// handle later.
5945 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5946   // Apply this processing to all the arguments at once instead of
5947   // dying at the first failure.
5948   bool hasInvalid = false;
5949   for (size_t i = 0, e = args.size(); i != e; i++) {
5950     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5951       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5952       if (result.isInvalid()) hasInvalid = true;
5953       else args[i] = result.get();
5954     } else if (hasInvalid) {
5955       (void)S.CorrectDelayedTyposInExpr(args[i]);
5956     }
5957   }
5958   return hasInvalid;
5959 }
5960 
5961 /// If a builtin function has a pointer argument with no explicit address
5962 /// space, then it should be able to accept a pointer to any address
5963 /// space as input.  In order to do this, we need to replace the
5964 /// standard builtin declaration with one that uses the same address space
5965 /// as the call.
5966 ///
5967 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5968 ///                  it does not contain any pointer arguments without
5969 ///                  an address space qualifer.  Otherwise the rewritten
5970 ///                  FunctionDecl is returned.
5971 /// TODO: Handle pointer return types.
5972 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5973                                                 FunctionDecl *FDecl,
5974                                                 MultiExprArg ArgExprs) {
5975 
5976   QualType DeclType = FDecl->getType();
5977   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5978 
5979   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5980       ArgExprs.size() < FT->getNumParams())
5981     return nullptr;
5982 
5983   bool NeedsNewDecl = false;
5984   unsigned i = 0;
5985   SmallVector<QualType, 8> OverloadParams;
5986 
5987   for (QualType ParamType : FT->param_types()) {
5988 
5989     // Convert array arguments to pointer to simplify type lookup.
5990     ExprResult ArgRes =
5991         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5992     if (ArgRes.isInvalid())
5993       return nullptr;
5994     Expr *Arg = ArgRes.get();
5995     QualType ArgType = Arg->getType();
5996     if (!ParamType->isPointerType() ||
5997         ParamType.hasAddressSpace() ||
5998         !ArgType->isPointerType() ||
5999         !ArgType->getPointeeType().hasAddressSpace()) {
6000       OverloadParams.push_back(ParamType);
6001       continue;
6002     }
6003 
6004     QualType PointeeType = ParamType->getPointeeType();
6005     if (PointeeType.hasAddressSpace())
6006       continue;
6007 
6008     NeedsNewDecl = true;
6009     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6010 
6011     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6012     OverloadParams.push_back(Context.getPointerType(PointeeType));
6013   }
6014 
6015   if (!NeedsNewDecl)
6016     return nullptr;
6017 
6018   FunctionProtoType::ExtProtoInfo EPI;
6019   EPI.Variadic = FT->isVariadic();
6020   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6021                                                 OverloadParams, EPI);
6022   DeclContext *Parent = FDecl->getParent();
6023   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6024                                                     FDecl->getLocation(),
6025                                                     FDecl->getLocation(),
6026                                                     FDecl->getIdentifier(),
6027                                                     OverloadTy,
6028                                                     /*TInfo=*/nullptr,
6029                                                     SC_Extern, false,
6030                                                     /*hasPrototype=*/true);
6031   SmallVector<ParmVarDecl*, 16> Params;
6032   FT = cast<FunctionProtoType>(OverloadTy);
6033   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6034     QualType ParamType = FT->getParamType(i);
6035     ParmVarDecl *Parm =
6036         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6037                                 SourceLocation(), nullptr, ParamType,
6038                                 /*TInfo=*/nullptr, SC_None, nullptr);
6039     Parm->setScopeInfo(0, i);
6040     Params.push_back(Parm);
6041   }
6042   OverloadDecl->setParams(Params);
6043   return OverloadDecl;
6044 }
6045 
6046 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6047                                     FunctionDecl *Callee,
6048                                     MultiExprArg ArgExprs) {
6049   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6050   // similar attributes) really don't like it when functions are called with an
6051   // invalid number of args.
6052   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6053                          /*PartialOverloading=*/false) &&
6054       !Callee->isVariadic())
6055     return;
6056   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6057     return;
6058 
6059   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
6060     S.Diag(Fn->getBeginLoc(),
6061            isa<CXXMethodDecl>(Callee)
6062                ? diag::err_ovl_no_viable_member_function_in_call
6063                : diag::err_ovl_no_viable_function_in_call)
6064         << Callee << Callee->getSourceRange();
6065     S.Diag(Callee->getLocation(),
6066            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6067         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6068     return;
6069   }
6070 }
6071 
6072 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6073     const UnresolvedMemberExpr *const UME, Sema &S) {
6074 
6075   const auto GetFunctionLevelDCIfCXXClass =
6076       [](Sema &S) -> const CXXRecordDecl * {
6077     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6078     if (!DC || !DC->getParent())
6079       return nullptr;
6080 
6081     // If the call to some member function was made from within a member
6082     // function body 'M' return return 'M's parent.
6083     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6084       return MD->getParent()->getCanonicalDecl();
6085     // else the call was made from within a default member initializer of a
6086     // class, so return the class.
6087     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6088       return RD->getCanonicalDecl();
6089     return nullptr;
6090   };
6091   // If our DeclContext is neither a member function nor a class (in the
6092   // case of a lambda in a default member initializer), we can't have an
6093   // enclosing 'this'.
6094 
6095   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6096   if (!CurParentClass)
6097     return false;
6098 
6099   // The naming class for implicit member functions call is the class in which
6100   // name lookup starts.
6101   const CXXRecordDecl *const NamingClass =
6102       UME->getNamingClass()->getCanonicalDecl();
6103   assert(NamingClass && "Must have naming class even for implicit access");
6104 
6105   // If the unresolved member functions were found in a 'naming class' that is
6106   // related (either the same or derived from) to the class that contains the
6107   // member function that itself contained the implicit member access.
6108 
6109   return CurParentClass == NamingClass ||
6110          CurParentClass->isDerivedFrom(NamingClass);
6111 }
6112 
6113 static void
6114 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6115     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6116 
6117   if (!UME)
6118     return;
6119 
6120   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6121   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6122   // already been captured, or if this is an implicit member function call (if
6123   // it isn't, an attempt to capture 'this' should already have been made).
6124   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6125       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6126     return;
6127 
6128   // Check if the naming class in which the unresolved members were found is
6129   // related (same as or is a base of) to the enclosing class.
6130 
6131   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6132     return;
6133 
6134 
6135   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6136   // If the enclosing function is not dependent, then this lambda is
6137   // capture ready, so if we can capture this, do so.
6138   if (!EnclosingFunctionCtx->isDependentContext()) {
6139     // If the current lambda and all enclosing lambdas can capture 'this' -
6140     // then go ahead and capture 'this' (since our unresolved overload set
6141     // contains at least one non-static member function).
6142     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6143       S.CheckCXXThisCapture(CallLoc);
6144   } else if (S.CurContext->isDependentContext()) {
6145     // ... since this is an implicit member reference, that might potentially
6146     // involve a 'this' capture, mark 'this' for potential capture in
6147     // enclosing lambdas.
6148     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6149       CurLSI->addPotentialThisCapture(CallLoc);
6150   }
6151 }
6152 
6153 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6154                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6155                                Expr *ExecConfig) {
6156   ExprResult Call =
6157       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6158   if (Call.isInvalid())
6159     return Call;
6160 
6161   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6162   // language modes.
6163   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6164     if (ULE->hasExplicitTemplateArgs() &&
6165         ULE->decls_begin() == ULE->decls_end()) {
6166       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6167                                  ? diag::warn_cxx17_compat_adl_only_template_id
6168                                  : diag::ext_adl_only_template_id)
6169           << ULE->getName();
6170     }
6171   }
6172 
6173   if (LangOpts.OpenMP)
6174     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6175                            ExecConfig);
6176 
6177   return Call;
6178 }
6179 
6180 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6181 /// This provides the location of the left/right parens and a list of comma
6182 /// locations.
6183 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6184                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6185                                Expr *ExecConfig, bool IsExecConfig) {
6186   // Since this might be a postfix expression, get rid of ParenListExprs.
6187   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6188   if (Result.isInvalid()) return ExprError();
6189   Fn = Result.get();
6190 
6191   if (checkArgsForPlaceholders(*this, ArgExprs))
6192     return ExprError();
6193 
6194   if (getLangOpts().CPlusPlus) {
6195     // If this is a pseudo-destructor expression, build the call immediately.
6196     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6197       if (!ArgExprs.empty()) {
6198         // Pseudo-destructor calls should not have any arguments.
6199         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6200             << FixItHint::CreateRemoval(
6201                    SourceRange(ArgExprs.front()->getBeginLoc(),
6202                                ArgExprs.back()->getEndLoc()));
6203       }
6204 
6205       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6206                               VK_RValue, RParenLoc);
6207     }
6208     if (Fn->getType() == Context.PseudoObjectTy) {
6209       ExprResult result = CheckPlaceholderExpr(Fn);
6210       if (result.isInvalid()) return ExprError();
6211       Fn = result.get();
6212     }
6213 
6214     // Determine whether this is a dependent call inside a C++ template,
6215     // in which case we won't do any semantic analysis now.
6216     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6217       if (ExecConfig) {
6218         return CUDAKernelCallExpr::Create(
6219             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6220             Context.DependentTy, VK_RValue, RParenLoc);
6221       } else {
6222 
6223         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6224             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6225             Fn->getBeginLoc());
6226 
6227         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6228                                 VK_RValue, RParenLoc);
6229       }
6230     }
6231 
6232     // Determine whether this is a call to an object (C++ [over.call.object]).
6233     if (Fn->getType()->isRecordType())
6234       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6235                                           RParenLoc);
6236 
6237     if (Fn->getType() == Context.UnknownAnyTy) {
6238       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6239       if (result.isInvalid()) return ExprError();
6240       Fn = result.get();
6241     }
6242 
6243     if (Fn->getType() == Context.BoundMemberTy) {
6244       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6245                                        RParenLoc);
6246     }
6247   }
6248 
6249   // Check for overloaded calls.  This can happen even in C due to extensions.
6250   if (Fn->getType() == Context.OverloadTy) {
6251     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6252 
6253     // We aren't supposed to apply this logic if there's an '&' involved.
6254     if (!find.HasFormOfMemberPointer) {
6255       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6256         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6257                                 VK_RValue, RParenLoc);
6258       OverloadExpr *ovl = find.Expression;
6259       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6260         return BuildOverloadedCallExpr(
6261             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6262             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6263       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6264                                        RParenLoc);
6265     }
6266   }
6267 
6268   // If we're directly calling a function, get the appropriate declaration.
6269   if (Fn->getType() == Context.UnknownAnyTy) {
6270     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6271     if (result.isInvalid()) return ExprError();
6272     Fn = result.get();
6273   }
6274 
6275   Expr *NakedFn = Fn->IgnoreParens();
6276 
6277   bool CallingNDeclIndirectly = false;
6278   NamedDecl *NDecl = nullptr;
6279   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6280     if (UnOp->getOpcode() == UO_AddrOf) {
6281       CallingNDeclIndirectly = true;
6282       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6283     }
6284   }
6285 
6286   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6287     NDecl = DRE->getDecl();
6288 
6289     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6290     if (FDecl && FDecl->getBuiltinID()) {
6291       // Rewrite the function decl for this builtin by replacing parameters
6292       // with no explicit address space with the address space of the arguments
6293       // in ArgExprs.
6294       if ((FDecl =
6295                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6296         NDecl = FDecl;
6297         Fn = DeclRefExpr::Create(
6298             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6299             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6300             nullptr, DRE->isNonOdrUse());
6301       }
6302     }
6303   } else if (isa<MemberExpr>(NakedFn))
6304     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6305 
6306   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6307     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6308                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6309       return ExprError();
6310 
6311     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6312       return ExprError();
6313 
6314     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6315   }
6316 
6317   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6318                                ExecConfig, IsExecConfig);
6319 }
6320 
6321 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6322 ///
6323 /// __builtin_astype( value, dst type )
6324 ///
6325 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6326                                  SourceLocation BuiltinLoc,
6327                                  SourceLocation RParenLoc) {
6328   ExprValueKind VK = VK_RValue;
6329   ExprObjectKind OK = OK_Ordinary;
6330   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6331   QualType SrcTy = E->getType();
6332   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6333     return ExprError(Diag(BuiltinLoc,
6334                           diag::err_invalid_astype_of_different_size)
6335                      << DstTy
6336                      << SrcTy
6337                      << E->getSourceRange());
6338   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6339 }
6340 
6341 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6342 /// provided arguments.
6343 ///
6344 /// __builtin_convertvector( value, dst type )
6345 ///
6346 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6347                                         SourceLocation BuiltinLoc,
6348                                         SourceLocation RParenLoc) {
6349   TypeSourceInfo *TInfo;
6350   GetTypeFromParser(ParsedDestTy, &TInfo);
6351   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6352 }
6353 
6354 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6355 /// i.e. an expression not of \p OverloadTy.  The expression should
6356 /// unary-convert to an expression of function-pointer or
6357 /// block-pointer type.
6358 ///
6359 /// \param NDecl the declaration being called, if available
6360 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6361                                        SourceLocation LParenLoc,
6362                                        ArrayRef<Expr *> Args,
6363                                        SourceLocation RParenLoc, Expr *Config,
6364                                        bool IsExecConfig, ADLCallKind UsesADL) {
6365   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6366   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6367 
6368   // Functions with 'interrupt' attribute cannot be called directly.
6369   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6370     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6371     return ExprError();
6372   }
6373 
6374   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6375   // so there's some risk when calling out to non-interrupt handler functions
6376   // that the callee might not preserve them. This is easy to diagnose here,
6377   // but can be very challenging to debug.
6378   if (auto *Caller = getCurFunctionDecl())
6379     if (Caller->hasAttr<ARMInterruptAttr>()) {
6380       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6381       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6382         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6383     }
6384 
6385   // Promote the function operand.
6386   // We special-case function promotion here because we only allow promoting
6387   // builtin functions to function pointers in the callee of a call.
6388   ExprResult Result;
6389   QualType ResultTy;
6390   if (BuiltinID &&
6391       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6392     // Extract the return type from the (builtin) function pointer type.
6393     // FIXME Several builtins still have setType in
6394     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6395     // Builtins.def to ensure they are correct before removing setType calls.
6396     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6397     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6398     ResultTy = FDecl->getCallResultType();
6399   } else {
6400     Result = CallExprUnaryConversions(Fn);
6401     ResultTy = Context.BoolTy;
6402   }
6403   if (Result.isInvalid())
6404     return ExprError();
6405   Fn = Result.get();
6406 
6407   // Check for a valid function type, but only if it is not a builtin which
6408   // requires custom type checking. These will be handled by
6409   // CheckBuiltinFunctionCall below just after creation of the call expression.
6410   const FunctionType *FuncT = nullptr;
6411   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6412   retry:
6413     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6414       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6415       // have type pointer to function".
6416       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6417       if (!FuncT)
6418         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6419                          << Fn->getType() << Fn->getSourceRange());
6420     } else if (const BlockPointerType *BPT =
6421                    Fn->getType()->getAs<BlockPointerType>()) {
6422       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6423     } else {
6424       // Handle calls to expressions of unknown-any type.
6425       if (Fn->getType() == Context.UnknownAnyTy) {
6426         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6427         if (rewrite.isInvalid())
6428           return ExprError();
6429         Fn = rewrite.get();
6430         goto retry;
6431       }
6432 
6433       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6434                        << Fn->getType() << Fn->getSourceRange());
6435     }
6436   }
6437 
6438   // Get the number of parameters in the function prototype, if any.
6439   // We will allocate space for max(Args.size(), NumParams) arguments
6440   // in the call expression.
6441   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6442   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6443 
6444   CallExpr *TheCall;
6445   if (Config) {
6446     assert(UsesADL == ADLCallKind::NotADL &&
6447            "CUDAKernelCallExpr should not use ADL");
6448     TheCall =
6449         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6450                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6451   } else {
6452     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6453                                RParenLoc, NumParams, UsesADL);
6454   }
6455 
6456   if (!getLangOpts().CPlusPlus) {
6457     // Forget about the nulled arguments since typo correction
6458     // do not handle them well.
6459     TheCall->shrinkNumArgs(Args.size());
6460     // C cannot always handle TypoExpr nodes in builtin calls and direct
6461     // function calls as their argument checking don't necessarily handle
6462     // dependent types properly, so make sure any TypoExprs have been
6463     // dealt with.
6464     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6465     if (!Result.isUsable()) return ExprError();
6466     CallExpr *TheOldCall = TheCall;
6467     TheCall = dyn_cast<CallExpr>(Result.get());
6468     bool CorrectedTypos = TheCall != TheOldCall;
6469     if (!TheCall) return Result;
6470     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6471 
6472     // A new call expression node was created if some typos were corrected.
6473     // However it may not have been constructed with enough storage. In this
6474     // case, rebuild the node with enough storage. The waste of space is
6475     // immaterial since this only happens when some typos were corrected.
6476     if (CorrectedTypos && Args.size() < NumParams) {
6477       if (Config)
6478         TheCall = CUDAKernelCallExpr::Create(
6479             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6480             RParenLoc, NumParams);
6481       else
6482         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6483                                    RParenLoc, NumParams, UsesADL);
6484     }
6485     // We can now handle the nulled arguments for the default arguments.
6486     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6487   }
6488 
6489   // Bail out early if calling a builtin with custom type checking.
6490   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6491     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6492 
6493   if (getLangOpts().CUDA) {
6494     if (Config) {
6495       // CUDA: Kernel calls must be to global functions
6496       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6497         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6498             << FDecl << Fn->getSourceRange());
6499 
6500       // CUDA: Kernel function must have 'void' return type
6501       if (!FuncT->getReturnType()->isVoidType() &&
6502           !FuncT->getReturnType()->getAs<AutoType>() &&
6503           !FuncT->getReturnType()->isInstantiationDependentType())
6504         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6505             << Fn->getType() << Fn->getSourceRange());
6506     } else {
6507       // CUDA: Calls to global functions must be configured
6508       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6509         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6510             << FDecl << Fn->getSourceRange());
6511     }
6512   }
6513 
6514   // Check for a valid return type
6515   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6516                           FDecl))
6517     return ExprError();
6518 
6519   // We know the result type of the call, set it.
6520   TheCall->setType(FuncT->getCallResultType(Context));
6521   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6522 
6523   if (Proto) {
6524     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6525                                 IsExecConfig))
6526       return ExprError();
6527   } else {
6528     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6529 
6530     if (FDecl) {
6531       // Check if we have too few/too many template arguments, based
6532       // on our knowledge of the function definition.
6533       const FunctionDecl *Def = nullptr;
6534       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6535         Proto = Def->getType()->getAs<FunctionProtoType>();
6536        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6537           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6538           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6539       }
6540 
6541       // If the function we're calling isn't a function prototype, but we have
6542       // a function prototype from a prior declaratiom, use that prototype.
6543       if (!FDecl->hasPrototype())
6544         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6545     }
6546 
6547     // Promote the arguments (C99 6.5.2.2p6).
6548     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6549       Expr *Arg = Args[i];
6550 
6551       if (Proto && i < Proto->getNumParams()) {
6552         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6553             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6554         ExprResult ArgE =
6555             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6556         if (ArgE.isInvalid())
6557           return true;
6558 
6559         Arg = ArgE.getAs<Expr>();
6560 
6561       } else {
6562         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6563 
6564         if (ArgE.isInvalid())
6565           return true;
6566 
6567         Arg = ArgE.getAs<Expr>();
6568       }
6569 
6570       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6571                               diag::err_call_incomplete_argument, Arg))
6572         return ExprError();
6573 
6574       TheCall->setArg(i, Arg);
6575     }
6576   }
6577 
6578   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6579     if (!Method->isStatic())
6580       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6581         << Fn->getSourceRange());
6582 
6583   // Check for sentinels
6584   if (NDecl)
6585     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6586 
6587   // Warn for unions passing across security boundary (CMSE).
6588   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6589     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6590       if (const auto *RT =
6591               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6592         if (RT->getDecl()->isOrContainsUnion())
6593           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6594               << 0 << i;
6595       }
6596     }
6597   }
6598 
6599   // Do special checking on direct calls to functions.
6600   if (FDecl) {
6601     if (CheckFunctionCall(FDecl, TheCall, Proto))
6602       return ExprError();
6603 
6604     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6605 
6606     if (BuiltinID)
6607       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6608   } else if (NDecl) {
6609     if (CheckPointerCall(NDecl, TheCall, Proto))
6610       return ExprError();
6611   } else {
6612     if (CheckOtherCall(TheCall, Proto))
6613       return ExprError();
6614   }
6615 
6616   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6617 }
6618 
6619 ExprResult
6620 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6621                            SourceLocation RParenLoc, Expr *InitExpr) {
6622   assert(Ty && "ActOnCompoundLiteral(): missing type");
6623   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6624 
6625   TypeSourceInfo *TInfo;
6626   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6627   if (!TInfo)
6628     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6629 
6630   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6631 }
6632 
6633 ExprResult
6634 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6635                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6636   QualType literalType = TInfo->getType();
6637 
6638   if (literalType->isArrayType()) {
6639     if (RequireCompleteSizedType(
6640             LParenLoc, Context.getBaseElementType(literalType),
6641             diag::err_array_incomplete_or_sizeless_type,
6642             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6643       return ExprError();
6644     if (literalType->isVariableArrayType())
6645       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6646         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6647   } else if (!literalType->isDependentType() &&
6648              RequireCompleteType(LParenLoc, literalType,
6649                diag::err_typecheck_decl_incomplete_type,
6650                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6651     return ExprError();
6652 
6653   InitializedEntity Entity
6654     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6655   InitializationKind Kind
6656     = InitializationKind::CreateCStyleCast(LParenLoc,
6657                                            SourceRange(LParenLoc, RParenLoc),
6658                                            /*InitList=*/true);
6659   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6660   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6661                                       &literalType);
6662   if (Result.isInvalid())
6663     return ExprError();
6664   LiteralExpr = Result.get();
6665 
6666   bool isFileScope = !CurContext->isFunctionOrMethod();
6667 
6668   // In C, compound literals are l-values for some reason.
6669   // For GCC compatibility, in C++, file-scope array compound literals with
6670   // constant initializers are also l-values, and compound literals are
6671   // otherwise prvalues.
6672   //
6673   // (GCC also treats C++ list-initialized file-scope array prvalues with
6674   // constant initializers as l-values, but that's non-conforming, so we don't
6675   // follow it there.)
6676   //
6677   // FIXME: It would be better to handle the lvalue cases as materializing and
6678   // lifetime-extending a temporary object, but our materialized temporaries
6679   // representation only supports lifetime extension from a variable, not "out
6680   // of thin air".
6681   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6682   // is bound to the result of applying array-to-pointer decay to the compound
6683   // literal.
6684   // FIXME: GCC supports compound literals of reference type, which should
6685   // obviously have a value kind derived from the kind of reference involved.
6686   ExprValueKind VK =
6687       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6688           ? VK_RValue
6689           : VK_LValue;
6690 
6691   if (isFileScope)
6692     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6693       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6694         Expr *Init = ILE->getInit(i);
6695         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6696       }
6697 
6698   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6699                                               VK, LiteralExpr, isFileScope);
6700   if (isFileScope) {
6701     if (!LiteralExpr->isTypeDependent() &&
6702         !LiteralExpr->isValueDependent() &&
6703         !literalType->isDependentType()) // C99 6.5.2.5p3
6704       if (CheckForConstantInitializer(LiteralExpr, literalType))
6705         return ExprError();
6706   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6707              literalType.getAddressSpace() != LangAS::Default) {
6708     // Embedded-C extensions to C99 6.5.2.5:
6709     //   "If the compound literal occurs inside the body of a function, the
6710     //   type name shall not be qualified by an address-space qualifier."
6711     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6712       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6713     return ExprError();
6714   }
6715 
6716   if (!isFileScope && !getLangOpts().CPlusPlus) {
6717     // Compound literals that have automatic storage duration are destroyed at
6718     // the end of the scope in C; in C++, they're just temporaries.
6719 
6720     // Emit diagnostics if it is or contains a C union type that is non-trivial
6721     // to destruct.
6722     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6723       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6724                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6725 
6726     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6727     if (literalType.isDestructedType()) {
6728       Cleanup.setExprNeedsCleanups(true);
6729       ExprCleanupObjects.push_back(E);
6730       getCurFunction()->setHasBranchProtectedScope();
6731     }
6732   }
6733 
6734   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6735       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6736     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6737                                        E->getInitializer()->getExprLoc());
6738 
6739   return MaybeBindToTemporary(E);
6740 }
6741 
6742 ExprResult
6743 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6744                     SourceLocation RBraceLoc) {
6745   // Only produce each kind of designated initialization diagnostic once.
6746   SourceLocation FirstDesignator;
6747   bool DiagnosedArrayDesignator = false;
6748   bool DiagnosedNestedDesignator = false;
6749   bool DiagnosedMixedDesignator = false;
6750 
6751   // Check that any designated initializers are syntactically valid in the
6752   // current language mode.
6753   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6754     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6755       if (FirstDesignator.isInvalid())
6756         FirstDesignator = DIE->getBeginLoc();
6757 
6758       if (!getLangOpts().CPlusPlus)
6759         break;
6760 
6761       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6762         DiagnosedNestedDesignator = true;
6763         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6764           << DIE->getDesignatorsSourceRange();
6765       }
6766 
6767       for (auto &Desig : DIE->designators()) {
6768         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6769           DiagnosedArrayDesignator = true;
6770           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6771             << Desig.getSourceRange();
6772         }
6773       }
6774 
6775       if (!DiagnosedMixedDesignator &&
6776           !isa<DesignatedInitExpr>(InitArgList[0])) {
6777         DiagnosedMixedDesignator = true;
6778         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6779           << DIE->getSourceRange();
6780         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6781           << InitArgList[0]->getSourceRange();
6782       }
6783     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6784                isa<DesignatedInitExpr>(InitArgList[0])) {
6785       DiagnosedMixedDesignator = true;
6786       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6787       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6788         << DIE->getSourceRange();
6789       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6790         << InitArgList[I]->getSourceRange();
6791     }
6792   }
6793 
6794   if (FirstDesignator.isValid()) {
6795     // Only diagnose designated initiaization as a C++20 extension if we didn't
6796     // already diagnose use of (non-C++20) C99 designator syntax.
6797     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6798         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6799       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6800                                 ? diag::warn_cxx17_compat_designated_init
6801                                 : diag::ext_cxx_designated_init);
6802     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6803       Diag(FirstDesignator, diag::ext_designated_init);
6804     }
6805   }
6806 
6807   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6808 }
6809 
6810 ExprResult
6811 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6812                     SourceLocation RBraceLoc) {
6813   // Semantic analysis for initializers is done by ActOnDeclarator() and
6814   // CheckInitializer() - it requires knowledge of the object being initialized.
6815 
6816   // Immediately handle non-overload placeholders.  Overloads can be
6817   // resolved contextually, but everything else here can't.
6818   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6819     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6820       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6821 
6822       // Ignore failures; dropping the entire initializer list because
6823       // of one failure would be terrible for indexing/etc.
6824       if (result.isInvalid()) continue;
6825 
6826       InitArgList[I] = result.get();
6827     }
6828   }
6829 
6830   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6831                                                RBraceLoc);
6832   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6833   return E;
6834 }
6835 
6836 /// Do an explicit extend of the given block pointer if we're in ARC.
6837 void Sema::maybeExtendBlockObject(ExprResult &E) {
6838   assert(E.get()->getType()->isBlockPointerType());
6839   assert(E.get()->isRValue());
6840 
6841   // Only do this in an r-value context.
6842   if (!getLangOpts().ObjCAutoRefCount) return;
6843 
6844   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6845                                CK_ARCExtendBlockObject, E.get(),
6846                                /*base path*/ nullptr, VK_RValue);
6847   Cleanup.setExprNeedsCleanups(true);
6848 }
6849 
6850 /// Prepare a conversion of the given expression to an ObjC object
6851 /// pointer type.
6852 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6853   QualType type = E.get()->getType();
6854   if (type->isObjCObjectPointerType()) {
6855     return CK_BitCast;
6856   } else if (type->isBlockPointerType()) {
6857     maybeExtendBlockObject(E);
6858     return CK_BlockPointerToObjCPointerCast;
6859   } else {
6860     assert(type->isPointerType());
6861     return CK_CPointerToObjCPointerCast;
6862   }
6863 }
6864 
6865 /// Prepares for a scalar cast, performing all the necessary stages
6866 /// except the final cast and returning the kind required.
6867 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6868   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6869   // Also, callers should have filtered out the invalid cases with
6870   // pointers.  Everything else should be possible.
6871 
6872   QualType SrcTy = Src.get()->getType();
6873   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6874     return CK_NoOp;
6875 
6876   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6877   case Type::STK_MemberPointer:
6878     llvm_unreachable("member pointer type in C");
6879 
6880   case Type::STK_CPointer:
6881   case Type::STK_BlockPointer:
6882   case Type::STK_ObjCObjectPointer:
6883     switch (DestTy->getScalarTypeKind()) {
6884     case Type::STK_CPointer: {
6885       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6886       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6887       if (SrcAS != DestAS)
6888         return CK_AddressSpaceConversion;
6889       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6890         return CK_NoOp;
6891       return CK_BitCast;
6892     }
6893     case Type::STK_BlockPointer:
6894       return (SrcKind == Type::STK_BlockPointer
6895                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6896     case Type::STK_ObjCObjectPointer:
6897       if (SrcKind == Type::STK_ObjCObjectPointer)
6898         return CK_BitCast;
6899       if (SrcKind == Type::STK_CPointer)
6900         return CK_CPointerToObjCPointerCast;
6901       maybeExtendBlockObject(Src);
6902       return CK_BlockPointerToObjCPointerCast;
6903     case Type::STK_Bool:
6904       return CK_PointerToBoolean;
6905     case Type::STK_Integral:
6906       return CK_PointerToIntegral;
6907     case Type::STK_Floating:
6908     case Type::STK_FloatingComplex:
6909     case Type::STK_IntegralComplex:
6910     case Type::STK_MemberPointer:
6911     case Type::STK_FixedPoint:
6912       llvm_unreachable("illegal cast from pointer");
6913     }
6914     llvm_unreachable("Should have returned before this");
6915 
6916   case Type::STK_FixedPoint:
6917     switch (DestTy->getScalarTypeKind()) {
6918     case Type::STK_FixedPoint:
6919       return CK_FixedPointCast;
6920     case Type::STK_Bool:
6921       return CK_FixedPointToBoolean;
6922     case Type::STK_Integral:
6923       return CK_FixedPointToIntegral;
6924     case Type::STK_Floating:
6925     case Type::STK_IntegralComplex:
6926     case Type::STK_FloatingComplex:
6927       Diag(Src.get()->getExprLoc(),
6928            diag::err_unimplemented_conversion_with_fixed_point_type)
6929           << DestTy;
6930       return CK_IntegralCast;
6931     case Type::STK_CPointer:
6932     case Type::STK_ObjCObjectPointer:
6933     case Type::STK_BlockPointer:
6934     case Type::STK_MemberPointer:
6935       llvm_unreachable("illegal cast to pointer type");
6936     }
6937     llvm_unreachable("Should have returned before this");
6938 
6939   case Type::STK_Bool: // casting from bool is like casting from an integer
6940   case Type::STK_Integral:
6941     switch (DestTy->getScalarTypeKind()) {
6942     case Type::STK_CPointer:
6943     case Type::STK_ObjCObjectPointer:
6944     case Type::STK_BlockPointer:
6945       if (Src.get()->isNullPointerConstant(Context,
6946                                            Expr::NPC_ValueDependentIsNull))
6947         return CK_NullToPointer;
6948       return CK_IntegralToPointer;
6949     case Type::STK_Bool:
6950       return CK_IntegralToBoolean;
6951     case Type::STK_Integral:
6952       return CK_IntegralCast;
6953     case Type::STK_Floating:
6954       return CK_IntegralToFloating;
6955     case Type::STK_IntegralComplex:
6956       Src = ImpCastExprToType(Src.get(),
6957                       DestTy->castAs<ComplexType>()->getElementType(),
6958                       CK_IntegralCast);
6959       return CK_IntegralRealToComplex;
6960     case Type::STK_FloatingComplex:
6961       Src = ImpCastExprToType(Src.get(),
6962                       DestTy->castAs<ComplexType>()->getElementType(),
6963                       CK_IntegralToFloating);
6964       return CK_FloatingRealToComplex;
6965     case Type::STK_MemberPointer:
6966       llvm_unreachable("member pointer type in C");
6967     case Type::STK_FixedPoint:
6968       return CK_IntegralToFixedPoint;
6969     }
6970     llvm_unreachable("Should have returned before this");
6971 
6972   case Type::STK_Floating:
6973     switch (DestTy->getScalarTypeKind()) {
6974     case Type::STK_Floating:
6975       return CK_FloatingCast;
6976     case Type::STK_Bool:
6977       return CK_FloatingToBoolean;
6978     case Type::STK_Integral:
6979       return CK_FloatingToIntegral;
6980     case Type::STK_FloatingComplex:
6981       Src = ImpCastExprToType(Src.get(),
6982                               DestTy->castAs<ComplexType>()->getElementType(),
6983                               CK_FloatingCast);
6984       return CK_FloatingRealToComplex;
6985     case Type::STK_IntegralComplex:
6986       Src = ImpCastExprToType(Src.get(),
6987                               DestTy->castAs<ComplexType>()->getElementType(),
6988                               CK_FloatingToIntegral);
6989       return CK_IntegralRealToComplex;
6990     case Type::STK_CPointer:
6991     case Type::STK_ObjCObjectPointer:
6992     case Type::STK_BlockPointer:
6993       llvm_unreachable("valid float->pointer cast?");
6994     case Type::STK_MemberPointer:
6995       llvm_unreachable("member pointer type in C");
6996     case Type::STK_FixedPoint:
6997       Diag(Src.get()->getExprLoc(),
6998            diag::err_unimplemented_conversion_with_fixed_point_type)
6999           << SrcTy;
7000       return CK_IntegralCast;
7001     }
7002     llvm_unreachable("Should have returned before this");
7003 
7004   case Type::STK_FloatingComplex:
7005     switch (DestTy->getScalarTypeKind()) {
7006     case Type::STK_FloatingComplex:
7007       return CK_FloatingComplexCast;
7008     case Type::STK_IntegralComplex:
7009       return CK_FloatingComplexToIntegralComplex;
7010     case Type::STK_Floating: {
7011       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7012       if (Context.hasSameType(ET, DestTy))
7013         return CK_FloatingComplexToReal;
7014       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7015       return CK_FloatingCast;
7016     }
7017     case Type::STK_Bool:
7018       return CK_FloatingComplexToBoolean;
7019     case Type::STK_Integral:
7020       Src = ImpCastExprToType(Src.get(),
7021                               SrcTy->castAs<ComplexType>()->getElementType(),
7022                               CK_FloatingComplexToReal);
7023       return CK_FloatingToIntegral;
7024     case Type::STK_CPointer:
7025     case Type::STK_ObjCObjectPointer:
7026     case Type::STK_BlockPointer:
7027       llvm_unreachable("valid complex float->pointer cast?");
7028     case Type::STK_MemberPointer:
7029       llvm_unreachable("member pointer type in C");
7030     case Type::STK_FixedPoint:
7031       Diag(Src.get()->getExprLoc(),
7032            diag::err_unimplemented_conversion_with_fixed_point_type)
7033           << SrcTy;
7034       return CK_IntegralCast;
7035     }
7036     llvm_unreachable("Should have returned before this");
7037 
7038   case Type::STK_IntegralComplex:
7039     switch (DestTy->getScalarTypeKind()) {
7040     case Type::STK_FloatingComplex:
7041       return CK_IntegralComplexToFloatingComplex;
7042     case Type::STK_IntegralComplex:
7043       return CK_IntegralComplexCast;
7044     case Type::STK_Integral: {
7045       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7046       if (Context.hasSameType(ET, DestTy))
7047         return CK_IntegralComplexToReal;
7048       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7049       return CK_IntegralCast;
7050     }
7051     case Type::STK_Bool:
7052       return CK_IntegralComplexToBoolean;
7053     case Type::STK_Floating:
7054       Src = ImpCastExprToType(Src.get(),
7055                               SrcTy->castAs<ComplexType>()->getElementType(),
7056                               CK_IntegralComplexToReal);
7057       return CK_IntegralToFloating;
7058     case Type::STK_CPointer:
7059     case Type::STK_ObjCObjectPointer:
7060     case Type::STK_BlockPointer:
7061       llvm_unreachable("valid complex int->pointer cast?");
7062     case Type::STK_MemberPointer:
7063       llvm_unreachable("member pointer type in C");
7064     case Type::STK_FixedPoint:
7065       Diag(Src.get()->getExprLoc(),
7066            diag::err_unimplemented_conversion_with_fixed_point_type)
7067           << SrcTy;
7068       return CK_IntegralCast;
7069     }
7070     llvm_unreachable("Should have returned before this");
7071   }
7072 
7073   llvm_unreachable("Unhandled scalar cast");
7074 }
7075 
7076 static bool breakDownVectorType(QualType type, uint64_t &len,
7077                                 QualType &eltType) {
7078   // Vectors are simple.
7079   if (const VectorType *vecType = type->getAs<VectorType>()) {
7080     len = vecType->getNumElements();
7081     eltType = vecType->getElementType();
7082     assert(eltType->isScalarType());
7083     return true;
7084   }
7085 
7086   // We allow lax conversion to and from non-vector types, but only if
7087   // they're real types (i.e. non-complex, non-pointer scalar types).
7088   if (!type->isRealType()) return false;
7089 
7090   len = 1;
7091   eltType = type;
7092   return true;
7093 }
7094 
7095 /// Are the two types lax-compatible vector types?  That is, given
7096 /// that one of them is a vector, do they have equal storage sizes,
7097 /// where the storage size is the number of elements times the element
7098 /// size?
7099 ///
7100 /// This will also return false if either of the types is neither a
7101 /// vector nor a real type.
7102 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7103   assert(destTy->isVectorType() || srcTy->isVectorType());
7104 
7105   // Disallow lax conversions between scalars and ExtVectors (these
7106   // conversions are allowed for other vector types because common headers
7107   // depend on them).  Most scalar OP ExtVector cases are handled by the
7108   // splat path anyway, which does what we want (convert, not bitcast).
7109   // What this rules out for ExtVectors is crazy things like char4*float.
7110   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7111   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7112 
7113   uint64_t srcLen, destLen;
7114   QualType srcEltTy, destEltTy;
7115   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7116   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7117 
7118   // ASTContext::getTypeSize will return the size rounded up to a
7119   // power of 2, so instead of using that, we need to use the raw
7120   // element size multiplied by the element count.
7121   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7122   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7123 
7124   return (srcLen * srcEltSize == destLen * destEltSize);
7125 }
7126 
7127 /// Is this a legal conversion between two types, one of which is
7128 /// known to be a vector type?
7129 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7130   assert(destTy->isVectorType() || srcTy->isVectorType());
7131 
7132   switch (Context.getLangOpts().getLaxVectorConversions()) {
7133   case LangOptions::LaxVectorConversionKind::None:
7134     return false;
7135 
7136   case LangOptions::LaxVectorConversionKind::Integer:
7137     if (!srcTy->isIntegralOrEnumerationType()) {
7138       auto *Vec = srcTy->getAs<VectorType>();
7139       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7140         return false;
7141     }
7142     if (!destTy->isIntegralOrEnumerationType()) {
7143       auto *Vec = destTy->getAs<VectorType>();
7144       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7145         return false;
7146     }
7147     // OK, integer (vector) -> integer (vector) bitcast.
7148     break;
7149 
7150     case LangOptions::LaxVectorConversionKind::All:
7151     break;
7152   }
7153 
7154   return areLaxCompatibleVectorTypes(srcTy, destTy);
7155 }
7156 
7157 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7158                            CastKind &Kind) {
7159   assert(VectorTy->isVectorType() && "Not a vector type!");
7160 
7161   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7162     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7163       return Diag(R.getBegin(),
7164                   Ty->isVectorType() ?
7165                   diag::err_invalid_conversion_between_vectors :
7166                   diag::err_invalid_conversion_between_vector_and_integer)
7167         << VectorTy << Ty << R;
7168   } else
7169     return Diag(R.getBegin(),
7170                 diag::err_invalid_conversion_between_vector_and_scalar)
7171       << VectorTy << Ty << R;
7172 
7173   Kind = CK_BitCast;
7174   return false;
7175 }
7176 
7177 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7178   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7179 
7180   if (DestElemTy == SplattedExpr->getType())
7181     return SplattedExpr;
7182 
7183   assert(DestElemTy->isFloatingType() ||
7184          DestElemTy->isIntegralOrEnumerationType());
7185 
7186   CastKind CK;
7187   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7188     // OpenCL requires that we convert `true` boolean expressions to -1, but
7189     // only when splatting vectors.
7190     if (DestElemTy->isFloatingType()) {
7191       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7192       // in two steps: boolean to signed integral, then to floating.
7193       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7194                                                  CK_BooleanToSignedIntegral);
7195       SplattedExpr = CastExprRes.get();
7196       CK = CK_IntegralToFloating;
7197     } else {
7198       CK = CK_BooleanToSignedIntegral;
7199     }
7200   } else {
7201     ExprResult CastExprRes = SplattedExpr;
7202     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7203     if (CastExprRes.isInvalid())
7204       return ExprError();
7205     SplattedExpr = CastExprRes.get();
7206   }
7207   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7208 }
7209 
7210 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7211                                     Expr *CastExpr, CastKind &Kind) {
7212   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7213 
7214   QualType SrcTy = CastExpr->getType();
7215 
7216   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7217   // an ExtVectorType.
7218   // In OpenCL, casts between vectors of different types are not allowed.
7219   // (See OpenCL 6.2).
7220   if (SrcTy->isVectorType()) {
7221     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7222         (getLangOpts().OpenCL &&
7223          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7224       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7225         << DestTy << SrcTy << R;
7226       return ExprError();
7227     }
7228     Kind = CK_BitCast;
7229     return CastExpr;
7230   }
7231 
7232   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7233   // conversion will take place first from scalar to elt type, and then
7234   // splat from elt type to vector.
7235   if (SrcTy->isPointerType())
7236     return Diag(R.getBegin(),
7237                 diag::err_invalid_conversion_between_vector_and_scalar)
7238       << DestTy << SrcTy << R;
7239 
7240   Kind = CK_VectorSplat;
7241   return prepareVectorSplat(DestTy, CastExpr);
7242 }
7243 
7244 ExprResult
7245 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7246                     Declarator &D, ParsedType &Ty,
7247                     SourceLocation RParenLoc, Expr *CastExpr) {
7248   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7249          "ActOnCastExpr(): missing type or expr");
7250 
7251   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7252   if (D.isInvalidType())
7253     return ExprError();
7254 
7255   if (getLangOpts().CPlusPlus) {
7256     // Check that there are no default arguments (C++ only).
7257     CheckExtraCXXDefaultArguments(D);
7258   } else {
7259     // Make sure any TypoExprs have been dealt with.
7260     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7261     if (!Res.isUsable())
7262       return ExprError();
7263     CastExpr = Res.get();
7264   }
7265 
7266   checkUnusedDeclAttributes(D);
7267 
7268   QualType castType = castTInfo->getType();
7269   Ty = CreateParsedType(castType, castTInfo);
7270 
7271   bool isVectorLiteral = false;
7272 
7273   // Check for an altivec or OpenCL literal,
7274   // i.e. all the elements are integer constants.
7275   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7276   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7277   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7278        && castType->isVectorType() && (PE || PLE)) {
7279     if (PLE && PLE->getNumExprs() == 0) {
7280       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7281       return ExprError();
7282     }
7283     if (PE || PLE->getNumExprs() == 1) {
7284       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7285       if (!E->getType()->isVectorType())
7286         isVectorLiteral = true;
7287     }
7288     else
7289       isVectorLiteral = true;
7290   }
7291 
7292   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7293   // then handle it as such.
7294   if (isVectorLiteral)
7295     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7296 
7297   // If the Expr being casted is a ParenListExpr, handle it specially.
7298   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7299   // sequence of BinOp comma operators.
7300   if (isa<ParenListExpr>(CastExpr)) {
7301     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7302     if (Result.isInvalid()) return ExprError();
7303     CastExpr = Result.get();
7304   }
7305 
7306   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7307       !getSourceManager().isInSystemMacro(LParenLoc))
7308     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7309 
7310   CheckTollFreeBridgeCast(castType, CastExpr);
7311 
7312   CheckObjCBridgeRelatedCast(castType, CastExpr);
7313 
7314   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7315 
7316   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7317 }
7318 
7319 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7320                                     SourceLocation RParenLoc, Expr *E,
7321                                     TypeSourceInfo *TInfo) {
7322   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7323          "Expected paren or paren list expression");
7324 
7325   Expr **exprs;
7326   unsigned numExprs;
7327   Expr *subExpr;
7328   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7329   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7330     LiteralLParenLoc = PE->getLParenLoc();
7331     LiteralRParenLoc = PE->getRParenLoc();
7332     exprs = PE->getExprs();
7333     numExprs = PE->getNumExprs();
7334   } else { // isa<ParenExpr> by assertion at function entrance
7335     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7336     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7337     subExpr = cast<ParenExpr>(E)->getSubExpr();
7338     exprs = &subExpr;
7339     numExprs = 1;
7340   }
7341 
7342   QualType Ty = TInfo->getType();
7343   assert(Ty->isVectorType() && "Expected vector type");
7344 
7345   SmallVector<Expr *, 8> initExprs;
7346   const VectorType *VTy = Ty->castAs<VectorType>();
7347   unsigned numElems = VTy->getNumElements();
7348 
7349   // '(...)' form of vector initialization in AltiVec: the number of
7350   // initializers must be one or must match the size of the vector.
7351   // If a single value is specified in the initializer then it will be
7352   // replicated to all the components of the vector
7353   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7354     // The number of initializers must be one or must match the size of the
7355     // vector. If a single value is specified in the initializer then it will
7356     // be replicated to all the components of the vector
7357     if (numExprs == 1) {
7358       QualType ElemTy = VTy->getElementType();
7359       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7360       if (Literal.isInvalid())
7361         return ExprError();
7362       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7363                                   PrepareScalarCast(Literal, ElemTy));
7364       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7365     }
7366     else if (numExprs < numElems) {
7367       Diag(E->getExprLoc(),
7368            diag::err_incorrect_number_of_vector_initializers);
7369       return ExprError();
7370     }
7371     else
7372       initExprs.append(exprs, exprs + numExprs);
7373   }
7374   else {
7375     // For OpenCL, when the number of initializers is a single value,
7376     // it will be replicated to all components of the vector.
7377     if (getLangOpts().OpenCL &&
7378         VTy->getVectorKind() == VectorType::GenericVector &&
7379         numExprs == 1) {
7380         QualType ElemTy = VTy->getElementType();
7381         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7382         if (Literal.isInvalid())
7383           return ExprError();
7384         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7385                                     PrepareScalarCast(Literal, ElemTy));
7386         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7387     }
7388 
7389     initExprs.append(exprs, exprs + numExprs);
7390   }
7391   // FIXME: This means that pretty-printing the final AST will produce curly
7392   // braces instead of the original commas.
7393   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7394                                                    initExprs, LiteralRParenLoc);
7395   initE->setType(Ty);
7396   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7397 }
7398 
7399 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7400 /// the ParenListExpr into a sequence of comma binary operators.
7401 ExprResult
7402 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7403   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7404   if (!E)
7405     return OrigExpr;
7406 
7407   ExprResult Result(E->getExpr(0));
7408 
7409   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7410     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7411                         E->getExpr(i));
7412 
7413   if (Result.isInvalid()) return ExprError();
7414 
7415   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7416 }
7417 
7418 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7419                                     SourceLocation R,
7420                                     MultiExprArg Val) {
7421   return ParenListExpr::Create(Context, L, Val, R);
7422 }
7423 
7424 /// Emit a specialized diagnostic when one expression is a null pointer
7425 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7426 /// emitted.
7427 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7428                                       SourceLocation QuestionLoc) {
7429   Expr *NullExpr = LHSExpr;
7430   Expr *NonPointerExpr = RHSExpr;
7431   Expr::NullPointerConstantKind NullKind =
7432       NullExpr->isNullPointerConstant(Context,
7433                                       Expr::NPC_ValueDependentIsNotNull);
7434 
7435   if (NullKind == Expr::NPCK_NotNull) {
7436     NullExpr = RHSExpr;
7437     NonPointerExpr = LHSExpr;
7438     NullKind =
7439         NullExpr->isNullPointerConstant(Context,
7440                                         Expr::NPC_ValueDependentIsNotNull);
7441   }
7442 
7443   if (NullKind == Expr::NPCK_NotNull)
7444     return false;
7445 
7446   if (NullKind == Expr::NPCK_ZeroExpression)
7447     return false;
7448 
7449   if (NullKind == Expr::NPCK_ZeroLiteral) {
7450     // In this case, check to make sure that we got here from a "NULL"
7451     // string in the source code.
7452     NullExpr = NullExpr->IgnoreParenImpCasts();
7453     SourceLocation loc = NullExpr->getExprLoc();
7454     if (!findMacroSpelling(loc, "NULL"))
7455       return false;
7456   }
7457 
7458   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7459   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7460       << NonPointerExpr->getType() << DiagType
7461       << NonPointerExpr->getSourceRange();
7462   return true;
7463 }
7464 
7465 /// Return false if the condition expression is valid, true otherwise.
7466 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7467   QualType CondTy = Cond->getType();
7468 
7469   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7470   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7471     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7472       << CondTy << Cond->getSourceRange();
7473     return true;
7474   }
7475 
7476   // C99 6.5.15p2
7477   if (CondTy->isScalarType()) return false;
7478 
7479   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7480     << CondTy << Cond->getSourceRange();
7481   return true;
7482 }
7483 
7484 /// Handle when one or both operands are void type.
7485 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7486                                          ExprResult &RHS) {
7487     Expr *LHSExpr = LHS.get();
7488     Expr *RHSExpr = RHS.get();
7489 
7490     if (!LHSExpr->getType()->isVoidType())
7491       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7492           << RHSExpr->getSourceRange();
7493     if (!RHSExpr->getType()->isVoidType())
7494       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7495           << LHSExpr->getSourceRange();
7496     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7497     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7498     return S.Context.VoidTy;
7499 }
7500 
7501 /// Return false if the NullExpr can be promoted to PointerTy,
7502 /// true otherwise.
7503 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7504                                         QualType PointerTy) {
7505   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7506       !NullExpr.get()->isNullPointerConstant(S.Context,
7507                                             Expr::NPC_ValueDependentIsNull))
7508     return true;
7509 
7510   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7511   return false;
7512 }
7513 
7514 /// Checks compatibility between two pointers and return the resulting
7515 /// type.
7516 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7517                                                      ExprResult &RHS,
7518                                                      SourceLocation Loc) {
7519   QualType LHSTy = LHS.get()->getType();
7520   QualType RHSTy = RHS.get()->getType();
7521 
7522   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7523     // Two identical pointers types are always compatible.
7524     return LHSTy;
7525   }
7526 
7527   QualType lhptee, rhptee;
7528 
7529   // Get the pointee types.
7530   bool IsBlockPointer = false;
7531   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7532     lhptee = LHSBTy->getPointeeType();
7533     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7534     IsBlockPointer = true;
7535   } else {
7536     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7537     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7538   }
7539 
7540   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7541   // differently qualified versions of compatible types, the result type is
7542   // a pointer to an appropriately qualified version of the composite
7543   // type.
7544 
7545   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7546   // clause doesn't make sense for our extensions. E.g. address space 2 should
7547   // be incompatible with address space 3: they may live on different devices or
7548   // anything.
7549   Qualifiers lhQual = lhptee.getQualifiers();
7550   Qualifiers rhQual = rhptee.getQualifiers();
7551 
7552   LangAS ResultAddrSpace = LangAS::Default;
7553   LangAS LAddrSpace = lhQual.getAddressSpace();
7554   LangAS RAddrSpace = rhQual.getAddressSpace();
7555 
7556   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7557   // spaces is disallowed.
7558   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7559     ResultAddrSpace = LAddrSpace;
7560   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7561     ResultAddrSpace = RAddrSpace;
7562   else {
7563     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7564         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7565         << RHS.get()->getSourceRange();
7566     return QualType();
7567   }
7568 
7569   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7570   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7571   lhQual.removeCVRQualifiers();
7572   rhQual.removeCVRQualifiers();
7573 
7574   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7575   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7576   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7577   // qual types are compatible iff
7578   //  * corresponded types are compatible
7579   //  * CVR qualifiers are equal
7580   //  * address spaces are equal
7581   // Thus for conditional operator we merge CVR and address space unqualified
7582   // pointees and if there is a composite type we return a pointer to it with
7583   // merged qualifiers.
7584   LHSCastKind =
7585       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7586   RHSCastKind =
7587       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7588   lhQual.removeAddressSpace();
7589   rhQual.removeAddressSpace();
7590 
7591   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7592   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7593 
7594   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7595 
7596   if (CompositeTy.isNull()) {
7597     // In this situation, we assume void* type. No especially good
7598     // reason, but this is what gcc does, and we do have to pick
7599     // to get a consistent AST.
7600     QualType incompatTy;
7601     incompatTy = S.Context.getPointerType(
7602         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7603     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7604     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7605 
7606     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7607     // for casts between types with incompatible address space qualifiers.
7608     // For the following code the compiler produces casts between global and
7609     // local address spaces of the corresponded innermost pointees:
7610     // local int *global *a;
7611     // global int *global *b;
7612     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7613     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7614         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7615         << RHS.get()->getSourceRange();
7616 
7617     return incompatTy;
7618   }
7619 
7620   // The pointer types are compatible.
7621   // In case of OpenCL ResultTy should have the address space qualifier
7622   // which is a superset of address spaces of both the 2nd and the 3rd
7623   // operands of the conditional operator.
7624   QualType ResultTy = [&, ResultAddrSpace]() {
7625     if (S.getLangOpts().OpenCL) {
7626       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7627       CompositeQuals.setAddressSpace(ResultAddrSpace);
7628       return S.Context
7629           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7630           .withCVRQualifiers(MergedCVRQual);
7631     }
7632     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7633   }();
7634   if (IsBlockPointer)
7635     ResultTy = S.Context.getBlockPointerType(ResultTy);
7636   else
7637     ResultTy = S.Context.getPointerType(ResultTy);
7638 
7639   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7640   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7641   return ResultTy;
7642 }
7643 
7644 /// Return the resulting type when the operands are both block pointers.
7645 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7646                                                           ExprResult &LHS,
7647                                                           ExprResult &RHS,
7648                                                           SourceLocation Loc) {
7649   QualType LHSTy = LHS.get()->getType();
7650   QualType RHSTy = RHS.get()->getType();
7651 
7652   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7653     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7654       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7655       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7656       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7657       return destType;
7658     }
7659     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7660       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7661       << RHS.get()->getSourceRange();
7662     return QualType();
7663   }
7664 
7665   // We have 2 block pointer types.
7666   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7667 }
7668 
7669 /// Return the resulting type when the operands are both pointers.
7670 static QualType
7671 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7672                                             ExprResult &RHS,
7673                                             SourceLocation Loc) {
7674   // get the pointer types
7675   QualType LHSTy = LHS.get()->getType();
7676   QualType RHSTy = RHS.get()->getType();
7677 
7678   // get the "pointed to" types
7679   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7680   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7681 
7682   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7683   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7684     // Figure out necessary qualifiers (C99 6.5.15p6)
7685     QualType destPointee
7686       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7687     QualType destType = S.Context.getPointerType(destPointee);
7688     // Add qualifiers if necessary.
7689     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7690     // Promote to void*.
7691     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7692     return destType;
7693   }
7694   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7695     QualType destPointee
7696       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7697     QualType destType = S.Context.getPointerType(destPointee);
7698     // Add qualifiers if necessary.
7699     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7700     // Promote to void*.
7701     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7702     return destType;
7703   }
7704 
7705   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7706 }
7707 
7708 /// Return false if the first expression is not an integer and the second
7709 /// expression is not a pointer, true otherwise.
7710 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7711                                         Expr* PointerExpr, SourceLocation Loc,
7712                                         bool IsIntFirstExpr) {
7713   if (!PointerExpr->getType()->isPointerType() ||
7714       !Int.get()->getType()->isIntegerType())
7715     return false;
7716 
7717   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7718   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7719 
7720   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7721     << Expr1->getType() << Expr2->getType()
7722     << Expr1->getSourceRange() << Expr2->getSourceRange();
7723   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7724                             CK_IntegralToPointer);
7725   return true;
7726 }
7727 
7728 /// Simple conversion between integer and floating point types.
7729 ///
7730 /// Used when handling the OpenCL conditional operator where the
7731 /// condition is a vector while the other operands are scalar.
7732 ///
7733 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7734 /// types are either integer or floating type. Between the two
7735 /// operands, the type with the higher rank is defined as the "result
7736 /// type". The other operand needs to be promoted to the same type. No
7737 /// other type promotion is allowed. We cannot use
7738 /// UsualArithmeticConversions() for this purpose, since it always
7739 /// promotes promotable types.
7740 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7741                                             ExprResult &RHS,
7742                                             SourceLocation QuestionLoc) {
7743   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7744   if (LHS.isInvalid())
7745     return QualType();
7746   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7747   if (RHS.isInvalid())
7748     return QualType();
7749 
7750   // For conversion purposes, we ignore any qualifiers.
7751   // For example, "const float" and "float" are equivalent.
7752   QualType LHSType =
7753     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7754   QualType RHSType =
7755     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7756 
7757   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7758     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7759       << LHSType << LHS.get()->getSourceRange();
7760     return QualType();
7761   }
7762 
7763   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7764     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7765       << RHSType << RHS.get()->getSourceRange();
7766     return QualType();
7767   }
7768 
7769   // If both types are identical, no conversion is needed.
7770   if (LHSType == RHSType)
7771     return LHSType;
7772 
7773   // Now handle "real" floating types (i.e. float, double, long double).
7774   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7775     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7776                                  /*IsCompAssign = */ false);
7777 
7778   // Finally, we have two differing integer types.
7779   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7780   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7781 }
7782 
7783 /// Convert scalar operands to a vector that matches the
7784 ///        condition in length.
7785 ///
7786 /// Used when handling the OpenCL conditional operator where the
7787 /// condition is a vector while the other operands are scalar.
7788 ///
7789 /// We first compute the "result type" for the scalar operands
7790 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7791 /// into a vector of that type where the length matches the condition
7792 /// vector type. s6.11.6 requires that the element types of the result
7793 /// and the condition must have the same number of bits.
7794 static QualType
7795 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7796                               QualType CondTy, SourceLocation QuestionLoc) {
7797   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7798   if (ResTy.isNull()) return QualType();
7799 
7800   const VectorType *CV = CondTy->getAs<VectorType>();
7801   assert(CV);
7802 
7803   // Determine the vector result type
7804   unsigned NumElements = CV->getNumElements();
7805   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7806 
7807   // Ensure that all types have the same number of bits
7808   if (S.Context.getTypeSize(CV->getElementType())
7809       != S.Context.getTypeSize(ResTy)) {
7810     // Since VectorTy is created internally, it does not pretty print
7811     // with an OpenCL name. Instead, we just print a description.
7812     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7813     SmallString<64> Str;
7814     llvm::raw_svector_ostream OS(Str);
7815     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7816     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7817       << CondTy << OS.str();
7818     return QualType();
7819   }
7820 
7821   // Convert operands to the vector result type
7822   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7823   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7824 
7825   return VectorTy;
7826 }
7827 
7828 /// Return false if this is a valid OpenCL condition vector
7829 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7830                                        SourceLocation QuestionLoc) {
7831   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7832   // integral type.
7833   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7834   assert(CondTy);
7835   QualType EleTy = CondTy->getElementType();
7836   if (EleTy->isIntegerType()) return false;
7837 
7838   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7839     << Cond->getType() << Cond->getSourceRange();
7840   return true;
7841 }
7842 
7843 /// Return false if the vector condition type and the vector
7844 ///        result type are compatible.
7845 ///
7846 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7847 /// number of elements, and their element types have the same number
7848 /// of bits.
7849 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7850                               SourceLocation QuestionLoc) {
7851   const VectorType *CV = CondTy->getAs<VectorType>();
7852   const VectorType *RV = VecResTy->getAs<VectorType>();
7853   assert(CV && RV);
7854 
7855   if (CV->getNumElements() != RV->getNumElements()) {
7856     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7857       << CondTy << VecResTy;
7858     return true;
7859   }
7860 
7861   QualType CVE = CV->getElementType();
7862   QualType RVE = RV->getElementType();
7863 
7864   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7865     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7866       << CondTy << VecResTy;
7867     return true;
7868   }
7869 
7870   return false;
7871 }
7872 
7873 /// Return the resulting type for the conditional operator in
7874 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7875 ///        s6.3.i) when the condition is a vector type.
7876 static QualType
7877 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7878                              ExprResult &LHS, ExprResult &RHS,
7879                              SourceLocation QuestionLoc) {
7880   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7881   if (Cond.isInvalid())
7882     return QualType();
7883   QualType CondTy = Cond.get()->getType();
7884 
7885   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7886     return QualType();
7887 
7888   // If either operand is a vector then find the vector type of the
7889   // result as specified in OpenCL v1.1 s6.3.i.
7890   if (LHS.get()->getType()->isVectorType() ||
7891       RHS.get()->getType()->isVectorType()) {
7892     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7893                                               /*isCompAssign*/false,
7894                                               /*AllowBothBool*/true,
7895                                               /*AllowBoolConversions*/false);
7896     if (VecResTy.isNull()) return QualType();
7897     // The result type must match the condition type as specified in
7898     // OpenCL v1.1 s6.11.6.
7899     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7900       return QualType();
7901     return VecResTy;
7902   }
7903 
7904   // Both operands are scalar.
7905   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7906 }
7907 
7908 /// Return true if the Expr is block type
7909 static bool checkBlockType(Sema &S, const Expr *E) {
7910   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7911     QualType Ty = CE->getCallee()->getType();
7912     if (Ty->isBlockPointerType()) {
7913       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7914       return true;
7915     }
7916   }
7917   return false;
7918 }
7919 
7920 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7921 /// In that case, LHS = cond.
7922 /// C99 6.5.15
7923 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7924                                         ExprResult &RHS, ExprValueKind &VK,
7925                                         ExprObjectKind &OK,
7926                                         SourceLocation QuestionLoc) {
7927 
7928   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7929   if (!LHSResult.isUsable()) return QualType();
7930   LHS = LHSResult;
7931 
7932   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7933   if (!RHSResult.isUsable()) return QualType();
7934   RHS = RHSResult;
7935 
7936   // C++ is sufficiently different to merit its own checker.
7937   if (getLangOpts().CPlusPlus)
7938     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7939 
7940   VK = VK_RValue;
7941   OK = OK_Ordinary;
7942 
7943   // The OpenCL operator with a vector condition is sufficiently
7944   // different to merit its own checker.
7945   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7946     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7947 
7948   // First, check the condition.
7949   Cond = UsualUnaryConversions(Cond.get());
7950   if (Cond.isInvalid())
7951     return QualType();
7952   if (checkCondition(*this, Cond.get(), QuestionLoc))
7953     return QualType();
7954 
7955   // Now check the two expressions.
7956   if (LHS.get()->getType()->isVectorType() ||
7957       RHS.get()->getType()->isVectorType())
7958     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7959                                /*AllowBothBool*/true,
7960                                /*AllowBoolConversions*/false);
7961 
7962   QualType ResTy =
7963       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7964   if (LHS.isInvalid() || RHS.isInvalid())
7965     return QualType();
7966 
7967   QualType LHSTy = LHS.get()->getType();
7968   QualType RHSTy = RHS.get()->getType();
7969 
7970   // Diagnose attempts to convert between __float128 and long double where
7971   // such conversions currently can't be handled.
7972   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7973     Diag(QuestionLoc,
7974          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7975       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7976     return QualType();
7977   }
7978 
7979   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7980   // selection operator (?:).
7981   if (getLangOpts().OpenCL &&
7982       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7983     return QualType();
7984   }
7985 
7986   // If both operands have arithmetic type, do the usual arithmetic conversions
7987   // to find a common type: C99 6.5.15p3,5.
7988   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7989     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7990     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7991 
7992     return ResTy;
7993   }
7994 
7995   // If both operands are the same structure or union type, the result is that
7996   // type.
7997   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7998     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7999       if (LHSRT->getDecl() == RHSRT->getDecl())
8000         // "If both the operands have structure or union type, the result has
8001         // that type."  This implies that CV qualifiers are dropped.
8002         return LHSTy.getUnqualifiedType();
8003     // FIXME: Type of conditional expression must be complete in C mode.
8004   }
8005 
8006   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8007   // The following || allows only one side to be void (a GCC-ism).
8008   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8009     return checkConditionalVoidType(*this, LHS, RHS);
8010   }
8011 
8012   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8013   // the type of the other operand."
8014   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8015   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8016 
8017   // All objective-c pointer type analysis is done here.
8018   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8019                                                         QuestionLoc);
8020   if (LHS.isInvalid() || RHS.isInvalid())
8021     return QualType();
8022   if (!compositeType.isNull())
8023     return compositeType;
8024 
8025 
8026   // Handle block pointer types.
8027   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8028     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8029                                                      QuestionLoc);
8030 
8031   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8032   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8033     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8034                                                        QuestionLoc);
8035 
8036   // GCC compatibility: soften pointer/integer mismatch.  Note that
8037   // null pointers have been filtered out by this point.
8038   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8039       /*IsIntFirstExpr=*/true))
8040     return RHSTy;
8041   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8042       /*IsIntFirstExpr=*/false))
8043     return LHSTy;
8044 
8045   // Allow ?: operations in which both operands have the same
8046   // built-in sizeless type.
8047   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8048     return LHSTy;
8049 
8050   // Emit a better diagnostic if one of the expressions is a null pointer
8051   // constant and the other is not a pointer type. In this case, the user most
8052   // likely forgot to take the address of the other expression.
8053   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8054     return QualType();
8055 
8056   // Otherwise, the operands are not compatible.
8057   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8058     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8059     << RHS.get()->getSourceRange();
8060   return QualType();
8061 }
8062 
8063 /// FindCompositeObjCPointerType - Helper method to find composite type of
8064 /// two objective-c pointer types of the two input expressions.
8065 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8066                                             SourceLocation QuestionLoc) {
8067   QualType LHSTy = LHS.get()->getType();
8068   QualType RHSTy = RHS.get()->getType();
8069 
8070   // Handle things like Class and struct objc_class*.  Here we case the result
8071   // to the pseudo-builtin, because that will be implicitly cast back to the
8072   // redefinition type if an attempt is made to access its fields.
8073   if (LHSTy->isObjCClassType() &&
8074       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8075     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8076     return LHSTy;
8077   }
8078   if (RHSTy->isObjCClassType() &&
8079       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8080     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8081     return RHSTy;
8082   }
8083   // And the same for struct objc_object* / id
8084   if (LHSTy->isObjCIdType() &&
8085       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8086     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8087     return LHSTy;
8088   }
8089   if (RHSTy->isObjCIdType() &&
8090       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8091     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8092     return RHSTy;
8093   }
8094   // And the same for struct objc_selector* / SEL
8095   if (Context.isObjCSelType(LHSTy) &&
8096       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8097     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8098     return LHSTy;
8099   }
8100   if (Context.isObjCSelType(RHSTy) &&
8101       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8102     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8103     return RHSTy;
8104   }
8105   // Check constraints for Objective-C object pointers types.
8106   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8107 
8108     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8109       // Two identical object pointer types are always compatible.
8110       return LHSTy;
8111     }
8112     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8113     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8114     QualType compositeType = LHSTy;
8115 
8116     // If both operands are interfaces and either operand can be
8117     // assigned to the other, use that type as the composite
8118     // type. This allows
8119     //   xxx ? (A*) a : (B*) b
8120     // where B is a subclass of A.
8121     //
8122     // Additionally, as for assignment, if either type is 'id'
8123     // allow silent coercion. Finally, if the types are
8124     // incompatible then make sure to use 'id' as the composite
8125     // type so the result is acceptable for sending messages to.
8126 
8127     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8128     // It could return the composite type.
8129     if (!(compositeType =
8130           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8131       // Nothing more to do.
8132     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8133       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8134     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8135       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8136     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8137                 RHSOPT->isObjCQualifiedIdType()) &&
8138                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8139                                                          true)) {
8140       // Need to handle "id<xx>" explicitly.
8141       // GCC allows qualified id and any Objective-C type to devolve to
8142       // id. Currently localizing to here until clear this should be
8143       // part of ObjCQualifiedIdTypesAreCompatible.
8144       compositeType = Context.getObjCIdType();
8145     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8146       compositeType = Context.getObjCIdType();
8147     } else {
8148       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8149       << LHSTy << RHSTy
8150       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8151       QualType incompatTy = Context.getObjCIdType();
8152       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8153       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8154       return incompatTy;
8155     }
8156     // The object pointer types are compatible.
8157     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8158     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8159     return compositeType;
8160   }
8161   // Check Objective-C object pointer types and 'void *'
8162   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8163     if (getLangOpts().ObjCAutoRefCount) {
8164       // ARC forbids the implicit conversion of object pointers to 'void *',
8165       // so these types are not compatible.
8166       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8167           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8168       LHS = RHS = true;
8169       return QualType();
8170     }
8171     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8172     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8173     QualType destPointee
8174     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8175     QualType destType = Context.getPointerType(destPointee);
8176     // Add qualifiers if necessary.
8177     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8178     // Promote to void*.
8179     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8180     return destType;
8181   }
8182   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8183     if (getLangOpts().ObjCAutoRefCount) {
8184       // ARC forbids the implicit conversion of object pointers to 'void *',
8185       // so these types are not compatible.
8186       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8187           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8188       LHS = RHS = true;
8189       return QualType();
8190     }
8191     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8192     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8193     QualType destPointee
8194     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8195     QualType destType = Context.getPointerType(destPointee);
8196     // Add qualifiers if necessary.
8197     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8198     // Promote to void*.
8199     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8200     return destType;
8201   }
8202   return QualType();
8203 }
8204 
8205 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8206 /// ParenRange in parentheses.
8207 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8208                                const PartialDiagnostic &Note,
8209                                SourceRange ParenRange) {
8210   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8211   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8212       EndLoc.isValid()) {
8213     Self.Diag(Loc, Note)
8214       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8215       << FixItHint::CreateInsertion(EndLoc, ")");
8216   } else {
8217     // We can't display the parentheses, so just show the bare note.
8218     Self.Diag(Loc, Note) << ParenRange;
8219   }
8220 }
8221 
8222 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8223   return BinaryOperator::isAdditiveOp(Opc) ||
8224          BinaryOperator::isMultiplicativeOp(Opc) ||
8225          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8226   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8227   // not any of the logical operators.  Bitwise-xor is commonly used as a
8228   // logical-xor because there is no logical-xor operator.  The logical
8229   // operators, including uses of xor, have a high false positive rate for
8230   // precedence warnings.
8231 }
8232 
8233 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8234 /// expression, either using a built-in or overloaded operator,
8235 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8236 /// expression.
8237 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8238                                    Expr **RHSExprs) {
8239   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8240   E = E->IgnoreImpCasts();
8241   E = E->IgnoreConversionOperator();
8242   E = E->IgnoreImpCasts();
8243   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8244     E = MTE->getSubExpr();
8245     E = E->IgnoreImpCasts();
8246   }
8247 
8248   // Built-in binary operator.
8249   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8250     if (IsArithmeticOp(OP->getOpcode())) {
8251       *Opcode = OP->getOpcode();
8252       *RHSExprs = OP->getRHS();
8253       return true;
8254     }
8255   }
8256 
8257   // Overloaded operator.
8258   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8259     if (Call->getNumArgs() != 2)
8260       return false;
8261 
8262     // Make sure this is really a binary operator that is safe to pass into
8263     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8264     OverloadedOperatorKind OO = Call->getOperator();
8265     if (OO < OO_Plus || OO > OO_Arrow ||
8266         OO == OO_PlusPlus || OO == OO_MinusMinus)
8267       return false;
8268 
8269     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8270     if (IsArithmeticOp(OpKind)) {
8271       *Opcode = OpKind;
8272       *RHSExprs = Call->getArg(1);
8273       return true;
8274     }
8275   }
8276 
8277   return false;
8278 }
8279 
8280 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8281 /// or is a logical expression such as (x==y) which has int type, but is
8282 /// commonly interpreted as boolean.
8283 static bool ExprLooksBoolean(Expr *E) {
8284   E = E->IgnoreParenImpCasts();
8285 
8286   if (E->getType()->isBooleanType())
8287     return true;
8288   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8289     return OP->isComparisonOp() || OP->isLogicalOp();
8290   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8291     return OP->getOpcode() == UO_LNot;
8292   if (E->getType()->isPointerType())
8293     return true;
8294   // FIXME: What about overloaded operator calls returning "unspecified boolean
8295   // type"s (commonly pointer-to-members)?
8296 
8297   return false;
8298 }
8299 
8300 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8301 /// and binary operator are mixed in a way that suggests the programmer assumed
8302 /// the conditional operator has higher precedence, for example:
8303 /// "int x = a + someBinaryCondition ? 1 : 2".
8304 static void DiagnoseConditionalPrecedence(Sema &Self,
8305                                           SourceLocation OpLoc,
8306                                           Expr *Condition,
8307                                           Expr *LHSExpr,
8308                                           Expr *RHSExpr) {
8309   BinaryOperatorKind CondOpcode;
8310   Expr *CondRHS;
8311 
8312   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8313     return;
8314   if (!ExprLooksBoolean(CondRHS))
8315     return;
8316 
8317   // The condition is an arithmetic binary expression, with a right-
8318   // hand side that looks boolean, so warn.
8319 
8320   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8321                         ? diag::warn_precedence_bitwise_conditional
8322                         : diag::warn_precedence_conditional;
8323 
8324   Self.Diag(OpLoc, DiagID)
8325       << Condition->getSourceRange()
8326       << BinaryOperator::getOpcodeStr(CondOpcode);
8327 
8328   SuggestParentheses(
8329       Self, OpLoc,
8330       Self.PDiag(diag::note_precedence_silence)
8331           << BinaryOperator::getOpcodeStr(CondOpcode),
8332       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8333 
8334   SuggestParentheses(Self, OpLoc,
8335                      Self.PDiag(diag::note_precedence_conditional_first),
8336                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8337 }
8338 
8339 /// Compute the nullability of a conditional expression.
8340 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8341                                               QualType LHSTy, QualType RHSTy,
8342                                               ASTContext &Ctx) {
8343   if (!ResTy->isAnyPointerType())
8344     return ResTy;
8345 
8346   auto GetNullability = [&Ctx](QualType Ty) {
8347     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8348     if (Kind)
8349       return *Kind;
8350     return NullabilityKind::Unspecified;
8351   };
8352 
8353   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8354   NullabilityKind MergedKind;
8355 
8356   // Compute nullability of a binary conditional expression.
8357   if (IsBin) {
8358     if (LHSKind == NullabilityKind::NonNull)
8359       MergedKind = NullabilityKind::NonNull;
8360     else
8361       MergedKind = RHSKind;
8362   // Compute nullability of a normal conditional expression.
8363   } else {
8364     if (LHSKind == NullabilityKind::Nullable ||
8365         RHSKind == NullabilityKind::Nullable)
8366       MergedKind = NullabilityKind::Nullable;
8367     else if (LHSKind == NullabilityKind::NonNull)
8368       MergedKind = RHSKind;
8369     else if (RHSKind == NullabilityKind::NonNull)
8370       MergedKind = LHSKind;
8371     else
8372       MergedKind = NullabilityKind::Unspecified;
8373   }
8374 
8375   // Return if ResTy already has the correct nullability.
8376   if (GetNullability(ResTy) == MergedKind)
8377     return ResTy;
8378 
8379   // Strip all nullability from ResTy.
8380   while (ResTy->getNullability(Ctx))
8381     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8382 
8383   // Create a new AttributedType with the new nullability kind.
8384   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8385   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8386 }
8387 
8388 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8389 /// in the case of a the GNU conditional expr extension.
8390 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8391                                     SourceLocation ColonLoc,
8392                                     Expr *CondExpr, Expr *LHSExpr,
8393                                     Expr *RHSExpr) {
8394   if (!getLangOpts().CPlusPlus) {
8395     // C cannot handle TypoExpr nodes in the condition because it
8396     // doesn't handle dependent types properly, so make sure any TypoExprs have
8397     // been dealt with before checking the operands.
8398     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8399     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8400     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8401 
8402     if (!CondResult.isUsable())
8403       return ExprError();
8404 
8405     if (LHSExpr) {
8406       if (!LHSResult.isUsable())
8407         return ExprError();
8408     }
8409 
8410     if (!RHSResult.isUsable())
8411       return ExprError();
8412 
8413     CondExpr = CondResult.get();
8414     LHSExpr = LHSResult.get();
8415     RHSExpr = RHSResult.get();
8416   }
8417 
8418   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8419   // was the condition.
8420   OpaqueValueExpr *opaqueValue = nullptr;
8421   Expr *commonExpr = nullptr;
8422   if (!LHSExpr) {
8423     commonExpr = CondExpr;
8424     // Lower out placeholder types first.  This is important so that we don't
8425     // try to capture a placeholder. This happens in few cases in C++; such
8426     // as Objective-C++'s dictionary subscripting syntax.
8427     if (commonExpr->hasPlaceholderType()) {
8428       ExprResult result = CheckPlaceholderExpr(commonExpr);
8429       if (!result.isUsable()) return ExprError();
8430       commonExpr = result.get();
8431     }
8432     // We usually want to apply unary conversions *before* saving, except
8433     // in the special case of a C++ l-value conditional.
8434     if (!(getLangOpts().CPlusPlus
8435           && !commonExpr->isTypeDependent()
8436           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8437           && commonExpr->isGLValue()
8438           && commonExpr->isOrdinaryOrBitFieldObject()
8439           && RHSExpr->isOrdinaryOrBitFieldObject()
8440           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8441       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8442       if (commonRes.isInvalid())
8443         return ExprError();
8444       commonExpr = commonRes.get();
8445     }
8446 
8447     // If the common expression is a class or array prvalue, materialize it
8448     // so that we can safely refer to it multiple times.
8449     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8450                                    commonExpr->getType()->isArrayType())) {
8451       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8452       if (MatExpr.isInvalid())
8453         return ExprError();
8454       commonExpr = MatExpr.get();
8455     }
8456 
8457     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8458                                                 commonExpr->getType(),
8459                                                 commonExpr->getValueKind(),
8460                                                 commonExpr->getObjectKind(),
8461                                                 commonExpr);
8462     LHSExpr = CondExpr = opaqueValue;
8463   }
8464 
8465   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8466   ExprValueKind VK = VK_RValue;
8467   ExprObjectKind OK = OK_Ordinary;
8468   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8469   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8470                                              VK, OK, QuestionLoc);
8471   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8472       RHS.isInvalid())
8473     return ExprError();
8474 
8475   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8476                                 RHS.get());
8477 
8478   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8479 
8480   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8481                                          Context);
8482 
8483   if (!commonExpr)
8484     return new (Context)
8485         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8486                             RHS.get(), result, VK, OK);
8487 
8488   return new (Context) BinaryConditionalOperator(
8489       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8490       ColonLoc, result, VK, OK);
8491 }
8492 
8493 // Check if we have a conversion between incompatible cmse function pointer
8494 // types, that is, a conversion between a function pointer with the
8495 // cmse_nonsecure_call attribute and one without.
8496 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8497                                           QualType ToType) {
8498   if (const auto *ToFn =
8499           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8500     if (const auto *FromFn =
8501             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8502       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8503       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8504 
8505       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8506     }
8507   }
8508   return false;
8509 }
8510 
8511 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8512 // being closely modeled after the C99 spec:-). The odd characteristic of this
8513 // routine is it effectively iqnores the qualifiers on the top level pointee.
8514 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8515 // FIXME: add a couple examples in this comment.
8516 static Sema::AssignConvertType
8517 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8518   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8519   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8520 
8521   // get the "pointed to" type (ignoring qualifiers at the top level)
8522   const Type *lhptee, *rhptee;
8523   Qualifiers lhq, rhq;
8524   std::tie(lhptee, lhq) =
8525       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8526   std::tie(rhptee, rhq) =
8527       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8528 
8529   Sema::AssignConvertType ConvTy = Sema::Compatible;
8530 
8531   // C99 6.5.16.1p1: This following citation is common to constraints
8532   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8533   // qualifiers of the type *pointed to* by the right;
8534 
8535   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8536   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8537       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8538     // Ignore lifetime for further calculation.
8539     lhq.removeObjCLifetime();
8540     rhq.removeObjCLifetime();
8541   }
8542 
8543   if (!lhq.compatiblyIncludes(rhq)) {
8544     // Treat address-space mismatches as fatal.
8545     if (!lhq.isAddressSpaceSupersetOf(rhq))
8546       return Sema::IncompatiblePointerDiscardsQualifiers;
8547 
8548     // It's okay to add or remove GC or lifetime qualifiers when converting to
8549     // and from void*.
8550     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8551                         .compatiblyIncludes(
8552                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8553              && (lhptee->isVoidType() || rhptee->isVoidType()))
8554       ; // keep old
8555 
8556     // Treat lifetime mismatches as fatal.
8557     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8558       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8559 
8560     // For GCC/MS compatibility, other qualifier mismatches are treated
8561     // as still compatible in C.
8562     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8563   }
8564 
8565   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8566   // incomplete type and the other is a pointer to a qualified or unqualified
8567   // version of void...
8568   if (lhptee->isVoidType()) {
8569     if (rhptee->isIncompleteOrObjectType())
8570       return ConvTy;
8571 
8572     // As an extension, we allow cast to/from void* to function pointer.
8573     assert(rhptee->isFunctionType());
8574     return Sema::FunctionVoidPointer;
8575   }
8576 
8577   if (rhptee->isVoidType()) {
8578     if (lhptee->isIncompleteOrObjectType())
8579       return ConvTy;
8580 
8581     // As an extension, we allow cast to/from void* to function pointer.
8582     assert(lhptee->isFunctionType());
8583     return Sema::FunctionVoidPointer;
8584   }
8585 
8586   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8587   // unqualified versions of compatible types, ...
8588   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8589   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8590     // Check if the pointee types are compatible ignoring the sign.
8591     // We explicitly check for char so that we catch "char" vs
8592     // "unsigned char" on systems where "char" is unsigned.
8593     if (lhptee->isCharType())
8594       ltrans = S.Context.UnsignedCharTy;
8595     else if (lhptee->hasSignedIntegerRepresentation())
8596       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8597 
8598     if (rhptee->isCharType())
8599       rtrans = S.Context.UnsignedCharTy;
8600     else if (rhptee->hasSignedIntegerRepresentation())
8601       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8602 
8603     if (ltrans == rtrans) {
8604       // Types are compatible ignoring the sign. Qualifier incompatibility
8605       // takes priority over sign incompatibility because the sign
8606       // warning can be disabled.
8607       if (ConvTy != Sema::Compatible)
8608         return ConvTy;
8609 
8610       return Sema::IncompatiblePointerSign;
8611     }
8612 
8613     // If we are a multi-level pointer, it's possible that our issue is simply
8614     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8615     // the eventual target type is the same and the pointers have the same
8616     // level of indirection, this must be the issue.
8617     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8618       do {
8619         std::tie(lhptee, lhq) =
8620           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8621         std::tie(rhptee, rhq) =
8622           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8623 
8624         // Inconsistent address spaces at this point is invalid, even if the
8625         // address spaces would be compatible.
8626         // FIXME: This doesn't catch address space mismatches for pointers of
8627         // different nesting levels, like:
8628         //   __local int *** a;
8629         //   int ** b = a;
8630         // It's not clear how to actually determine when such pointers are
8631         // invalidly incompatible.
8632         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8633           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8634 
8635       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8636 
8637       if (lhptee == rhptee)
8638         return Sema::IncompatibleNestedPointerQualifiers;
8639     }
8640 
8641     // General pointer incompatibility takes priority over qualifiers.
8642     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8643       return Sema::IncompatibleFunctionPointer;
8644     return Sema::IncompatiblePointer;
8645   }
8646   if (!S.getLangOpts().CPlusPlus &&
8647       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8648     return Sema::IncompatibleFunctionPointer;
8649   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8650     return Sema::IncompatibleFunctionPointer;
8651   return ConvTy;
8652 }
8653 
8654 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8655 /// block pointer types are compatible or whether a block and normal pointer
8656 /// are compatible. It is more restrict than comparing two function pointer
8657 // types.
8658 static Sema::AssignConvertType
8659 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8660                                     QualType RHSType) {
8661   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8662   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8663 
8664   QualType lhptee, rhptee;
8665 
8666   // get the "pointed to" type (ignoring qualifiers at the top level)
8667   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8668   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8669 
8670   // In C++, the types have to match exactly.
8671   if (S.getLangOpts().CPlusPlus)
8672     return Sema::IncompatibleBlockPointer;
8673 
8674   Sema::AssignConvertType ConvTy = Sema::Compatible;
8675 
8676   // For blocks we enforce that qualifiers are identical.
8677   Qualifiers LQuals = lhptee.getLocalQualifiers();
8678   Qualifiers RQuals = rhptee.getLocalQualifiers();
8679   if (S.getLangOpts().OpenCL) {
8680     LQuals.removeAddressSpace();
8681     RQuals.removeAddressSpace();
8682   }
8683   if (LQuals != RQuals)
8684     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8685 
8686   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8687   // assignment.
8688   // The current behavior is similar to C++ lambdas. A block might be
8689   // assigned to a variable iff its return type and parameters are compatible
8690   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8691   // an assignment. Presumably it should behave in way that a function pointer
8692   // assignment does in C, so for each parameter and return type:
8693   //  * CVR and address space of LHS should be a superset of CVR and address
8694   //  space of RHS.
8695   //  * unqualified types should be compatible.
8696   if (S.getLangOpts().OpenCL) {
8697     if (!S.Context.typesAreBlockPointerCompatible(
8698             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8699             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8700       return Sema::IncompatibleBlockPointer;
8701   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8702     return Sema::IncompatibleBlockPointer;
8703 
8704   return ConvTy;
8705 }
8706 
8707 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8708 /// for assignment compatibility.
8709 static Sema::AssignConvertType
8710 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8711                                    QualType RHSType) {
8712   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8713   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8714 
8715   if (LHSType->isObjCBuiltinType()) {
8716     // Class is not compatible with ObjC object pointers.
8717     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8718         !RHSType->isObjCQualifiedClassType())
8719       return Sema::IncompatiblePointer;
8720     return Sema::Compatible;
8721   }
8722   if (RHSType->isObjCBuiltinType()) {
8723     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8724         !LHSType->isObjCQualifiedClassType())
8725       return Sema::IncompatiblePointer;
8726     return Sema::Compatible;
8727   }
8728   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8729   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8730 
8731   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8732       // make an exception for id<P>
8733       !LHSType->isObjCQualifiedIdType())
8734     return Sema::CompatiblePointerDiscardsQualifiers;
8735 
8736   if (S.Context.typesAreCompatible(LHSType, RHSType))
8737     return Sema::Compatible;
8738   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8739     return Sema::IncompatibleObjCQualifiedId;
8740   return Sema::IncompatiblePointer;
8741 }
8742 
8743 Sema::AssignConvertType
8744 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8745                                  QualType LHSType, QualType RHSType) {
8746   // Fake up an opaque expression.  We don't actually care about what
8747   // cast operations are required, so if CheckAssignmentConstraints
8748   // adds casts to this they'll be wasted, but fortunately that doesn't
8749   // usually happen on valid code.
8750   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8751   ExprResult RHSPtr = &RHSExpr;
8752   CastKind K;
8753 
8754   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8755 }
8756 
8757 /// This helper function returns true if QT is a vector type that has element
8758 /// type ElementType.
8759 static bool isVector(QualType QT, QualType ElementType) {
8760   if (const VectorType *VT = QT->getAs<VectorType>())
8761     return VT->getElementType().getCanonicalType() == ElementType;
8762   return false;
8763 }
8764 
8765 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8766 /// has code to accommodate several GCC extensions when type checking
8767 /// pointers. Here are some objectionable examples that GCC considers warnings:
8768 ///
8769 ///  int a, *pint;
8770 ///  short *pshort;
8771 ///  struct foo *pfoo;
8772 ///
8773 ///  pint = pshort; // warning: assignment from incompatible pointer type
8774 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8775 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8776 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8777 ///
8778 /// As a result, the code for dealing with pointers is more complex than the
8779 /// C99 spec dictates.
8780 ///
8781 /// Sets 'Kind' for any result kind except Incompatible.
8782 Sema::AssignConvertType
8783 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8784                                  CastKind &Kind, bool ConvertRHS) {
8785   QualType RHSType = RHS.get()->getType();
8786   QualType OrigLHSType = LHSType;
8787 
8788   // Get canonical types.  We're not formatting these types, just comparing
8789   // them.
8790   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8791   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8792 
8793   // Common case: no conversion required.
8794   if (LHSType == RHSType) {
8795     Kind = CK_NoOp;
8796     return Compatible;
8797   }
8798 
8799   // If we have an atomic type, try a non-atomic assignment, then just add an
8800   // atomic qualification step.
8801   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8802     Sema::AssignConvertType result =
8803       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8804     if (result != Compatible)
8805       return result;
8806     if (Kind != CK_NoOp && ConvertRHS)
8807       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8808     Kind = CK_NonAtomicToAtomic;
8809     return Compatible;
8810   }
8811 
8812   // If the left-hand side is a reference type, then we are in a
8813   // (rare!) case where we've allowed the use of references in C,
8814   // e.g., as a parameter type in a built-in function. In this case,
8815   // just make sure that the type referenced is compatible with the
8816   // right-hand side type. The caller is responsible for adjusting
8817   // LHSType so that the resulting expression does not have reference
8818   // type.
8819   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8820     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8821       Kind = CK_LValueBitCast;
8822       return Compatible;
8823     }
8824     return Incompatible;
8825   }
8826 
8827   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8828   // to the same ExtVector type.
8829   if (LHSType->isExtVectorType()) {
8830     if (RHSType->isExtVectorType())
8831       return Incompatible;
8832     if (RHSType->isArithmeticType()) {
8833       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8834       if (ConvertRHS)
8835         RHS = prepareVectorSplat(LHSType, RHS.get());
8836       Kind = CK_VectorSplat;
8837       return Compatible;
8838     }
8839   }
8840 
8841   // Conversions to or from vector type.
8842   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8843     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8844       // Allow assignments of an AltiVec vector type to an equivalent GCC
8845       // vector type and vice versa
8846       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8847         Kind = CK_BitCast;
8848         return Compatible;
8849       }
8850 
8851       // If we are allowing lax vector conversions, and LHS and RHS are both
8852       // vectors, the total size only needs to be the same. This is a bitcast;
8853       // no bits are changed but the result type is different.
8854       if (isLaxVectorConversion(RHSType, LHSType)) {
8855         Kind = CK_BitCast;
8856         return IncompatibleVectors;
8857       }
8858     }
8859 
8860     // When the RHS comes from another lax conversion (e.g. binops between
8861     // scalars and vectors) the result is canonicalized as a vector. When the
8862     // LHS is also a vector, the lax is allowed by the condition above. Handle
8863     // the case where LHS is a scalar.
8864     if (LHSType->isScalarType()) {
8865       const VectorType *VecType = RHSType->getAs<VectorType>();
8866       if (VecType && VecType->getNumElements() == 1 &&
8867           isLaxVectorConversion(RHSType, LHSType)) {
8868         ExprResult *VecExpr = &RHS;
8869         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8870         Kind = CK_BitCast;
8871         return Compatible;
8872       }
8873     }
8874 
8875     return Incompatible;
8876   }
8877 
8878   // Diagnose attempts to convert between __float128 and long double where
8879   // such conversions currently can't be handled.
8880   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8881     return Incompatible;
8882 
8883   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8884   // discards the imaginary part.
8885   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8886       !LHSType->getAs<ComplexType>())
8887     return Incompatible;
8888 
8889   // Arithmetic conversions.
8890   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8891       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8892     if (ConvertRHS)
8893       Kind = PrepareScalarCast(RHS, LHSType);
8894     return Compatible;
8895   }
8896 
8897   // Conversions to normal pointers.
8898   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8899     // U* -> T*
8900     if (isa<PointerType>(RHSType)) {
8901       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8902       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8903       if (AddrSpaceL != AddrSpaceR)
8904         Kind = CK_AddressSpaceConversion;
8905       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8906         Kind = CK_NoOp;
8907       else
8908         Kind = CK_BitCast;
8909       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8910     }
8911 
8912     // int -> T*
8913     if (RHSType->isIntegerType()) {
8914       Kind = CK_IntegralToPointer; // FIXME: null?
8915       return IntToPointer;
8916     }
8917 
8918     // C pointers are not compatible with ObjC object pointers,
8919     // with two exceptions:
8920     if (isa<ObjCObjectPointerType>(RHSType)) {
8921       //  - conversions to void*
8922       if (LHSPointer->getPointeeType()->isVoidType()) {
8923         Kind = CK_BitCast;
8924         return Compatible;
8925       }
8926 
8927       //  - conversions from 'Class' to the redefinition type
8928       if (RHSType->isObjCClassType() &&
8929           Context.hasSameType(LHSType,
8930                               Context.getObjCClassRedefinitionType())) {
8931         Kind = CK_BitCast;
8932         return Compatible;
8933       }
8934 
8935       Kind = CK_BitCast;
8936       return IncompatiblePointer;
8937     }
8938 
8939     // U^ -> void*
8940     if (RHSType->getAs<BlockPointerType>()) {
8941       if (LHSPointer->getPointeeType()->isVoidType()) {
8942         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8943         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8944                                 ->getPointeeType()
8945                                 .getAddressSpace();
8946         Kind =
8947             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8948         return Compatible;
8949       }
8950     }
8951 
8952     return Incompatible;
8953   }
8954 
8955   // Conversions to block pointers.
8956   if (isa<BlockPointerType>(LHSType)) {
8957     // U^ -> T^
8958     if (RHSType->isBlockPointerType()) {
8959       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8960                               ->getPointeeType()
8961                               .getAddressSpace();
8962       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8963                               ->getPointeeType()
8964                               .getAddressSpace();
8965       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8966       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8967     }
8968 
8969     // int or null -> T^
8970     if (RHSType->isIntegerType()) {
8971       Kind = CK_IntegralToPointer; // FIXME: null
8972       return IntToBlockPointer;
8973     }
8974 
8975     // id -> T^
8976     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8977       Kind = CK_AnyPointerToBlockPointerCast;
8978       return Compatible;
8979     }
8980 
8981     // void* -> T^
8982     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8983       if (RHSPT->getPointeeType()->isVoidType()) {
8984         Kind = CK_AnyPointerToBlockPointerCast;
8985         return Compatible;
8986       }
8987 
8988     return Incompatible;
8989   }
8990 
8991   // Conversions to Objective-C pointers.
8992   if (isa<ObjCObjectPointerType>(LHSType)) {
8993     // A* -> B*
8994     if (RHSType->isObjCObjectPointerType()) {
8995       Kind = CK_BitCast;
8996       Sema::AssignConvertType result =
8997         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8998       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8999           result == Compatible &&
9000           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9001         result = IncompatibleObjCWeakRef;
9002       return result;
9003     }
9004 
9005     // int or null -> A*
9006     if (RHSType->isIntegerType()) {
9007       Kind = CK_IntegralToPointer; // FIXME: null
9008       return IntToPointer;
9009     }
9010 
9011     // In general, C pointers are not compatible with ObjC object pointers,
9012     // with two exceptions:
9013     if (isa<PointerType>(RHSType)) {
9014       Kind = CK_CPointerToObjCPointerCast;
9015 
9016       //  - conversions from 'void*'
9017       if (RHSType->isVoidPointerType()) {
9018         return Compatible;
9019       }
9020 
9021       //  - conversions to 'Class' from its redefinition type
9022       if (LHSType->isObjCClassType() &&
9023           Context.hasSameType(RHSType,
9024                               Context.getObjCClassRedefinitionType())) {
9025         return Compatible;
9026       }
9027 
9028       return IncompatiblePointer;
9029     }
9030 
9031     // Only under strict condition T^ is compatible with an Objective-C pointer.
9032     if (RHSType->isBlockPointerType() &&
9033         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9034       if (ConvertRHS)
9035         maybeExtendBlockObject(RHS);
9036       Kind = CK_BlockPointerToObjCPointerCast;
9037       return Compatible;
9038     }
9039 
9040     return Incompatible;
9041   }
9042 
9043   // Conversions from pointers that are not covered by the above.
9044   if (isa<PointerType>(RHSType)) {
9045     // T* -> _Bool
9046     if (LHSType == Context.BoolTy) {
9047       Kind = CK_PointerToBoolean;
9048       return Compatible;
9049     }
9050 
9051     // T* -> int
9052     if (LHSType->isIntegerType()) {
9053       Kind = CK_PointerToIntegral;
9054       return PointerToInt;
9055     }
9056 
9057     return Incompatible;
9058   }
9059 
9060   // Conversions from Objective-C pointers that are not covered by the above.
9061   if (isa<ObjCObjectPointerType>(RHSType)) {
9062     // T* -> _Bool
9063     if (LHSType == Context.BoolTy) {
9064       Kind = CK_PointerToBoolean;
9065       return Compatible;
9066     }
9067 
9068     // T* -> int
9069     if (LHSType->isIntegerType()) {
9070       Kind = CK_PointerToIntegral;
9071       return PointerToInt;
9072     }
9073 
9074     return Incompatible;
9075   }
9076 
9077   // struct A -> struct B
9078   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9079     if (Context.typesAreCompatible(LHSType, RHSType)) {
9080       Kind = CK_NoOp;
9081       return Compatible;
9082     }
9083   }
9084 
9085   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9086     Kind = CK_IntToOCLSampler;
9087     return Compatible;
9088   }
9089 
9090   return Incompatible;
9091 }
9092 
9093 /// Constructs a transparent union from an expression that is
9094 /// used to initialize the transparent union.
9095 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9096                                       ExprResult &EResult, QualType UnionType,
9097                                       FieldDecl *Field) {
9098   // Build an initializer list that designates the appropriate member
9099   // of the transparent union.
9100   Expr *E = EResult.get();
9101   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9102                                                    E, SourceLocation());
9103   Initializer->setType(UnionType);
9104   Initializer->setInitializedFieldInUnion(Field);
9105 
9106   // Build a compound literal constructing a value of the transparent
9107   // union type from this initializer list.
9108   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9109   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9110                                         VK_RValue, Initializer, false);
9111 }
9112 
9113 Sema::AssignConvertType
9114 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9115                                                ExprResult &RHS) {
9116   QualType RHSType = RHS.get()->getType();
9117 
9118   // If the ArgType is a Union type, we want to handle a potential
9119   // transparent_union GCC extension.
9120   const RecordType *UT = ArgType->getAsUnionType();
9121   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9122     return Incompatible;
9123 
9124   // The field to initialize within the transparent union.
9125   RecordDecl *UD = UT->getDecl();
9126   FieldDecl *InitField = nullptr;
9127   // It's compatible if the expression matches any of the fields.
9128   for (auto *it : UD->fields()) {
9129     if (it->getType()->isPointerType()) {
9130       // If the transparent union contains a pointer type, we allow:
9131       // 1) void pointer
9132       // 2) null pointer constant
9133       if (RHSType->isPointerType())
9134         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9135           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9136           InitField = it;
9137           break;
9138         }
9139 
9140       if (RHS.get()->isNullPointerConstant(Context,
9141                                            Expr::NPC_ValueDependentIsNull)) {
9142         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9143                                 CK_NullToPointer);
9144         InitField = it;
9145         break;
9146       }
9147     }
9148 
9149     CastKind Kind;
9150     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9151           == Compatible) {
9152       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9153       InitField = it;
9154       break;
9155     }
9156   }
9157 
9158   if (!InitField)
9159     return Incompatible;
9160 
9161   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9162   return Compatible;
9163 }
9164 
9165 Sema::AssignConvertType
9166 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9167                                        bool Diagnose,
9168                                        bool DiagnoseCFAudited,
9169                                        bool ConvertRHS) {
9170   // We need to be able to tell the caller whether we diagnosed a problem, if
9171   // they ask us to issue diagnostics.
9172   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9173 
9174   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9175   // we can't avoid *all* modifications at the moment, so we need some somewhere
9176   // to put the updated value.
9177   ExprResult LocalRHS = CallerRHS;
9178   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9179 
9180   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9181     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9182       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9183           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9184         Diag(RHS.get()->getExprLoc(),
9185              diag::warn_noderef_to_dereferenceable_pointer)
9186             << RHS.get()->getSourceRange();
9187       }
9188     }
9189   }
9190 
9191   if (getLangOpts().CPlusPlus) {
9192     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9193       // C++ 5.17p3: If the left operand is not of class type, the
9194       // expression is implicitly converted (C++ 4) to the
9195       // cv-unqualified type of the left operand.
9196       QualType RHSType = RHS.get()->getType();
9197       if (Diagnose) {
9198         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9199                                         AA_Assigning);
9200       } else {
9201         ImplicitConversionSequence ICS =
9202             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9203                                   /*SuppressUserConversions=*/false,
9204                                   AllowedExplicit::None,
9205                                   /*InOverloadResolution=*/false,
9206                                   /*CStyle=*/false,
9207                                   /*AllowObjCWritebackConversion=*/false);
9208         if (ICS.isFailure())
9209           return Incompatible;
9210         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9211                                         ICS, AA_Assigning);
9212       }
9213       if (RHS.isInvalid())
9214         return Incompatible;
9215       Sema::AssignConvertType result = Compatible;
9216       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9217           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9218         result = IncompatibleObjCWeakRef;
9219       return result;
9220     }
9221 
9222     // FIXME: Currently, we fall through and treat C++ classes like C
9223     // structures.
9224     // FIXME: We also fall through for atomics; not sure what should
9225     // happen there, though.
9226   } else if (RHS.get()->getType() == Context.OverloadTy) {
9227     // As a set of extensions to C, we support overloading on functions. These
9228     // functions need to be resolved here.
9229     DeclAccessPair DAP;
9230     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9231             RHS.get(), LHSType, /*Complain=*/false, DAP))
9232       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9233     else
9234       return Incompatible;
9235   }
9236 
9237   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9238   // a null pointer constant.
9239   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9240        LHSType->isBlockPointerType()) &&
9241       RHS.get()->isNullPointerConstant(Context,
9242                                        Expr::NPC_ValueDependentIsNull)) {
9243     if (Diagnose || ConvertRHS) {
9244       CastKind Kind;
9245       CXXCastPath Path;
9246       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9247                              /*IgnoreBaseAccess=*/false, Diagnose);
9248       if (ConvertRHS)
9249         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9250     }
9251     return Compatible;
9252   }
9253 
9254   // OpenCL queue_t type assignment.
9255   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9256                                  Context, Expr::NPC_ValueDependentIsNull)) {
9257     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9258     return Compatible;
9259   }
9260 
9261   // This check seems unnatural, however it is necessary to ensure the proper
9262   // conversion of functions/arrays. If the conversion were done for all
9263   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9264   // expressions that suppress this implicit conversion (&, sizeof).
9265   //
9266   // Suppress this for references: C++ 8.5.3p5.
9267   if (!LHSType->isReferenceType()) {
9268     // FIXME: We potentially allocate here even if ConvertRHS is false.
9269     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9270     if (RHS.isInvalid())
9271       return Incompatible;
9272   }
9273   CastKind Kind;
9274   Sema::AssignConvertType result =
9275     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9276 
9277   // C99 6.5.16.1p2: The value of the right operand is converted to the
9278   // type of the assignment expression.
9279   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9280   // so that we can use references in built-in functions even in C.
9281   // The getNonReferenceType() call makes sure that the resulting expression
9282   // does not have reference type.
9283   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9284     QualType Ty = LHSType.getNonLValueExprType(Context);
9285     Expr *E = RHS.get();
9286 
9287     // Check for various Objective-C errors. If we are not reporting
9288     // diagnostics and just checking for errors, e.g., during overload
9289     // resolution, return Incompatible to indicate the failure.
9290     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9291         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9292                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9293       if (!Diagnose)
9294         return Incompatible;
9295     }
9296     if (getLangOpts().ObjC &&
9297         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9298                                            E->getType(), E, Diagnose) ||
9299          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9300       if (!Diagnose)
9301         return Incompatible;
9302       // Replace the expression with a corrected version and continue so we
9303       // can find further errors.
9304       RHS = E;
9305       return Compatible;
9306     }
9307 
9308     if (ConvertRHS)
9309       RHS = ImpCastExprToType(E, Ty, Kind);
9310   }
9311 
9312   return result;
9313 }
9314 
9315 namespace {
9316 /// The original operand to an operator, prior to the application of the usual
9317 /// arithmetic conversions and converting the arguments of a builtin operator
9318 /// candidate.
9319 struct OriginalOperand {
9320   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9321     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9322       Op = MTE->getSubExpr();
9323     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9324       Op = BTE->getSubExpr();
9325     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9326       Orig = ICE->getSubExprAsWritten();
9327       Conversion = ICE->getConversionFunction();
9328     }
9329   }
9330 
9331   QualType getType() const { return Orig->getType(); }
9332 
9333   Expr *Orig;
9334   NamedDecl *Conversion;
9335 };
9336 }
9337 
9338 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9339                                ExprResult &RHS) {
9340   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9341 
9342   Diag(Loc, diag::err_typecheck_invalid_operands)
9343     << OrigLHS.getType() << OrigRHS.getType()
9344     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9345 
9346   // If a user-defined conversion was applied to either of the operands prior
9347   // to applying the built-in operator rules, tell the user about it.
9348   if (OrigLHS.Conversion) {
9349     Diag(OrigLHS.Conversion->getLocation(),
9350          diag::note_typecheck_invalid_operands_converted)
9351       << 0 << LHS.get()->getType();
9352   }
9353   if (OrigRHS.Conversion) {
9354     Diag(OrigRHS.Conversion->getLocation(),
9355          diag::note_typecheck_invalid_operands_converted)
9356       << 1 << RHS.get()->getType();
9357   }
9358 
9359   return QualType();
9360 }
9361 
9362 // Diagnose cases where a scalar was implicitly converted to a vector and
9363 // diagnose the underlying types. Otherwise, diagnose the error
9364 // as invalid vector logical operands for non-C++ cases.
9365 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9366                                             ExprResult &RHS) {
9367   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9368   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9369 
9370   bool LHSNatVec = LHSType->isVectorType();
9371   bool RHSNatVec = RHSType->isVectorType();
9372 
9373   if (!(LHSNatVec && RHSNatVec)) {
9374     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9375     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9376     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9377         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9378         << Vector->getSourceRange();
9379     return QualType();
9380   }
9381 
9382   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9383       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9384       << RHS.get()->getSourceRange();
9385 
9386   return QualType();
9387 }
9388 
9389 /// Try to convert a value of non-vector type to a vector type by converting
9390 /// the type to the element type of the vector and then performing a splat.
9391 /// If the language is OpenCL, we only use conversions that promote scalar
9392 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9393 /// for float->int.
9394 ///
9395 /// OpenCL V2.0 6.2.6.p2:
9396 /// An error shall occur if any scalar operand type has greater rank
9397 /// than the type of the vector element.
9398 ///
9399 /// \param scalar - if non-null, actually perform the conversions
9400 /// \return true if the operation fails (but without diagnosing the failure)
9401 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9402                                      QualType scalarTy,
9403                                      QualType vectorEltTy,
9404                                      QualType vectorTy,
9405                                      unsigned &DiagID) {
9406   // The conversion to apply to the scalar before splatting it,
9407   // if necessary.
9408   CastKind scalarCast = CK_NoOp;
9409 
9410   if (vectorEltTy->isIntegralType(S.Context)) {
9411     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9412         (scalarTy->isIntegerType() &&
9413          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9414       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9415       return true;
9416     }
9417     if (!scalarTy->isIntegralType(S.Context))
9418       return true;
9419     scalarCast = CK_IntegralCast;
9420   } else if (vectorEltTy->isRealFloatingType()) {
9421     if (scalarTy->isRealFloatingType()) {
9422       if (S.getLangOpts().OpenCL &&
9423           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9424         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9425         return true;
9426       }
9427       scalarCast = CK_FloatingCast;
9428     }
9429     else if (scalarTy->isIntegralType(S.Context))
9430       scalarCast = CK_IntegralToFloating;
9431     else
9432       return true;
9433   } else {
9434     return true;
9435   }
9436 
9437   // Adjust scalar if desired.
9438   if (scalar) {
9439     if (scalarCast != CK_NoOp)
9440       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9441     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9442   }
9443   return false;
9444 }
9445 
9446 /// Convert vector E to a vector with the same number of elements but different
9447 /// element type.
9448 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9449   const auto *VecTy = E->getType()->getAs<VectorType>();
9450   assert(VecTy && "Expression E must be a vector");
9451   QualType NewVecTy = S.Context.getVectorType(ElementType,
9452                                               VecTy->getNumElements(),
9453                                               VecTy->getVectorKind());
9454 
9455   // Look through the implicit cast. Return the subexpression if its type is
9456   // NewVecTy.
9457   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9458     if (ICE->getSubExpr()->getType() == NewVecTy)
9459       return ICE->getSubExpr();
9460 
9461   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9462   return S.ImpCastExprToType(E, NewVecTy, Cast);
9463 }
9464 
9465 /// Test if a (constant) integer Int can be casted to another integer type
9466 /// IntTy without losing precision.
9467 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9468                                       QualType OtherIntTy) {
9469   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9470 
9471   // Reject cases where the value of the Int is unknown as that would
9472   // possibly cause truncation, but accept cases where the scalar can be
9473   // demoted without loss of precision.
9474   Expr::EvalResult EVResult;
9475   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9476   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9477   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9478   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9479 
9480   if (CstInt) {
9481     // If the scalar is constant and is of a higher order and has more active
9482     // bits that the vector element type, reject it.
9483     llvm::APSInt Result = EVResult.Val.getInt();
9484     unsigned NumBits = IntSigned
9485                            ? (Result.isNegative() ? Result.getMinSignedBits()
9486                                                   : Result.getActiveBits())
9487                            : Result.getActiveBits();
9488     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9489       return true;
9490 
9491     // If the signedness of the scalar type and the vector element type
9492     // differs and the number of bits is greater than that of the vector
9493     // element reject it.
9494     return (IntSigned != OtherIntSigned &&
9495             NumBits > S.Context.getIntWidth(OtherIntTy));
9496   }
9497 
9498   // Reject cases where the value of the scalar is not constant and it's
9499   // order is greater than that of the vector element type.
9500   return (Order < 0);
9501 }
9502 
9503 /// Test if a (constant) integer Int can be casted to floating point type
9504 /// FloatTy without losing precision.
9505 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9506                                      QualType FloatTy) {
9507   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9508 
9509   // Determine if the integer constant can be expressed as a floating point
9510   // number of the appropriate type.
9511   Expr::EvalResult EVResult;
9512   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9513 
9514   uint64_t Bits = 0;
9515   if (CstInt) {
9516     // Reject constants that would be truncated if they were converted to
9517     // the floating point type. Test by simple to/from conversion.
9518     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9519     //        could be avoided if there was a convertFromAPInt method
9520     //        which could signal back if implicit truncation occurred.
9521     llvm::APSInt Result = EVResult.Val.getInt();
9522     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9523     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9524                            llvm::APFloat::rmTowardZero);
9525     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9526                              !IntTy->hasSignedIntegerRepresentation());
9527     bool Ignored = false;
9528     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9529                            &Ignored);
9530     if (Result != ConvertBack)
9531       return true;
9532   } else {
9533     // Reject types that cannot be fully encoded into the mantissa of
9534     // the float.
9535     Bits = S.Context.getTypeSize(IntTy);
9536     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9537         S.Context.getFloatTypeSemantics(FloatTy));
9538     if (Bits > FloatPrec)
9539       return true;
9540   }
9541 
9542   return false;
9543 }
9544 
9545 /// Attempt to convert and splat Scalar into a vector whose types matches
9546 /// Vector following GCC conversion rules. The rule is that implicit
9547 /// conversion can occur when Scalar can be casted to match Vector's element
9548 /// type without causing truncation of Scalar.
9549 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9550                                         ExprResult *Vector) {
9551   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9552   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9553   const VectorType *VT = VectorTy->getAs<VectorType>();
9554 
9555   assert(!isa<ExtVectorType>(VT) &&
9556          "ExtVectorTypes should not be handled here!");
9557 
9558   QualType VectorEltTy = VT->getElementType();
9559 
9560   // Reject cases where the vector element type or the scalar element type are
9561   // not integral or floating point types.
9562   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9563     return true;
9564 
9565   // The conversion to apply to the scalar before splatting it,
9566   // if necessary.
9567   CastKind ScalarCast = CK_NoOp;
9568 
9569   // Accept cases where the vector elements are integers and the scalar is
9570   // an integer.
9571   // FIXME: Notionally if the scalar was a floating point value with a precise
9572   //        integral representation, we could cast it to an appropriate integer
9573   //        type and then perform the rest of the checks here. GCC will perform
9574   //        this conversion in some cases as determined by the input language.
9575   //        We should accept it on a language independent basis.
9576   if (VectorEltTy->isIntegralType(S.Context) &&
9577       ScalarTy->isIntegralType(S.Context) &&
9578       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9579 
9580     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9581       return true;
9582 
9583     ScalarCast = CK_IntegralCast;
9584   } else if (VectorEltTy->isIntegralType(S.Context) &&
9585              ScalarTy->isRealFloatingType()) {
9586     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9587       ScalarCast = CK_FloatingToIntegral;
9588     else
9589       return true;
9590   } else if (VectorEltTy->isRealFloatingType()) {
9591     if (ScalarTy->isRealFloatingType()) {
9592 
9593       // Reject cases where the scalar type is not a constant and has a higher
9594       // Order than the vector element type.
9595       llvm::APFloat Result(0.0);
9596 
9597       // Determine whether this is a constant scalar. In the event that the
9598       // value is dependent (and thus cannot be evaluated by the constant
9599       // evaluator), skip the evaluation. This will then diagnose once the
9600       // expression is instantiated.
9601       bool CstScalar = Scalar->get()->isValueDependent() ||
9602                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9603       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9604       if (!CstScalar && Order < 0)
9605         return true;
9606 
9607       // If the scalar cannot be safely casted to the vector element type,
9608       // reject it.
9609       if (CstScalar) {
9610         bool Truncated = false;
9611         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9612                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9613         if (Truncated)
9614           return true;
9615       }
9616 
9617       ScalarCast = CK_FloatingCast;
9618     } else if (ScalarTy->isIntegralType(S.Context)) {
9619       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9620         return true;
9621 
9622       ScalarCast = CK_IntegralToFloating;
9623     } else
9624       return true;
9625   } else if (ScalarTy->isEnumeralType())
9626     return true;
9627 
9628   // Adjust scalar if desired.
9629   if (Scalar) {
9630     if (ScalarCast != CK_NoOp)
9631       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9632     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9633   }
9634   return false;
9635 }
9636 
9637 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9638                                    SourceLocation Loc, bool IsCompAssign,
9639                                    bool AllowBothBool,
9640                                    bool AllowBoolConversions) {
9641   if (!IsCompAssign) {
9642     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9643     if (LHS.isInvalid())
9644       return QualType();
9645   }
9646   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9647   if (RHS.isInvalid())
9648     return QualType();
9649 
9650   // For conversion purposes, we ignore any qualifiers.
9651   // For example, "const float" and "float" are equivalent.
9652   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9653   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9654 
9655   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9656   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9657   assert(LHSVecType || RHSVecType);
9658 
9659   // AltiVec-style "vector bool op vector bool" combinations are allowed
9660   // for some operators but not others.
9661   if (!AllowBothBool &&
9662       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9663       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9664     return InvalidOperands(Loc, LHS, RHS);
9665 
9666   // If the vector types are identical, return.
9667   if (Context.hasSameType(LHSType, RHSType))
9668     return LHSType;
9669 
9670   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9671   if (LHSVecType && RHSVecType &&
9672       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9673     if (isa<ExtVectorType>(LHSVecType)) {
9674       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9675       return LHSType;
9676     }
9677 
9678     if (!IsCompAssign)
9679       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9680     return RHSType;
9681   }
9682 
9683   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9684   // can be mixed, with the result being the non-bool type.  The non-bool
9685   // operand must have integer element type.
9686   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9687       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9688       (Context.getTypeSize(LHSVecType->getElementType()) ==
9689        Context.getTypeSize(RHSVecType->getElementType()))) {
9690     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9691         LHSVecType->getElementType()->isIntegerType() &&
9692         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9693       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9694       return LHSType;
9695     }
9696     if (!IsCompAssign &&
9697         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9698         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9699         RHSVecType->getElementType()->isIntegerType()) {
9700       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9701       return RHSType;
9702     }
9703   }
9704 
9705   // If there's a vector type and a scalar, try to convert the scalar to
9706   // the vector element type and splat.
9707   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9708   if (!RHSVecType) {
9709     if (isa<ExtVectorType>(LHSVecType)) {
9710       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9711                                     LHSVecType->getElementType(), LHSType,
9712                                     DiagID))
9713         return LHSType;
9714     } else {
9715       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9716         return LHSType;
9717     }
9718   }
9719   if (!LHSVecType) {
9720     if (isa<ExtVectorType>(RHSVecType)) {
9721       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9722                                     LHSType, RHSVecType->getElementType(),
9723                                     RHSType, DiagID))
9724         return RHSType;
9725     } else {
9726       if (LHS.get()->getValueKind() == VK_LValue ||
9727           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9728         return RHSType;
9729     }
9730   }
9731 
9732   // FIXME: The code below also handles conversion between vectors and
9733   // non-scalars, we should break this down into fine grained specific checks
9734   // and emit proper diagnostics.
9735   QualType VecType = LHSVecType ? LHSType : RHSType;
9736   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9737   QualType OtherType = LHSVecType ? RHSType : LHSType;
9738   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9739   if (isLaxVectorConversion(OtherType, VecType)) {
9740     // If we're allowing lax vector conversions, only the total (data) size
9741     // needs to be the same. For non compound assignment, if one of the types is
9742     // scalar, the result is always the vector type.
9743     if (!IsCompAssign) {
9744       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9745       return VecType;
9746     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9747     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9748     // type. Note that this is already done by non-compound assignments in
9749     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9750     // <1 x T> -> T. The result is also a vector type.
9751     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9752                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9753       ExprResult *RHSExpr = &RHS;
9754       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9755       return VecType;
9756     }
9757   }
9758 
9759   // Okay, the expression is invalid.
9760 
9761   // If there's a non-vector, non-real operand, diagnose that.
9762   if ((!RHSVecType && !RHSType->isRealType()) ||
9763       (!LHSVecType && !LHSType->isRealType())) {
9764     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9765       << LHSType << RHSType
9766       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9767     return QualType();
9768   }
9769 
9770   // OpenCL V1.1 6.2.6.p1:
9771   // If the operands are of more than one vector type, then an error shall
9772   // occur. Implicit conversions between vector types are not permitted, per
9773   // section 6.2.1.
9774   if (getLangOpts().OpenCL &&
9775       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9776       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9777     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9778                                                            << RHSType;
9779     return QualType();
9780   }
9781 
9782 
9783   // If there is a vector type that is not a ExtVector and a scalar, we reach
9784   // this point if scalar could not be converted to the vector's element type
9785   // without truncation.
9786   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9787       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9788     QualType Scalar = LHSVecType ? RHSType : LHSType;
9789     QualType Vector = LHSVecType ? LHSType : RHSType;
9790     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9791     Diag(Loc,
9792          diag::err_typecheck_vector_not_convertable_implict_truncation)
9793         << ScalarOrVector << Scalar << Vector;
9794 
9795     return QualType();
9796   }
9797 
9798   // Otherwise, use the generic diagnostic.
9799   Diag(Loc, DiagID)
9800     << LHSType << RHSType
9801     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9802   return QualType();
9803 }
9804 
9805 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9806 // expression.  These are mainly cases where the null pointer is used as an
9807 // integer instead of a pointer.
9808 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9809                                 SourceLocation Loc, bool IsCompare) {
9810   // The canonical way to check for a GNU null is with isNullPointerConstant,
9811   // but we use a bit of a hack here for speed; this is a relatively
9812   // hot path, and isNullPointerConstant is slow.
9813   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9814   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9815 
9816   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9817 
9818   // Avoid analyzing cases where the result will either be invalid (and
9819   // diagnosed as such) or entirely valid and not something to warn about.
9820   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9821       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9822     return;
9823 
9824   // Comparison operations would not make sense with a null pointer no matter
9825   // what the other expression is.
9826   if (!IsCompare) {
9827     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9828         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9829         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9830     return;
9831   }
9832 
9833   // The rest of the operations only make sense with a null pointer
9834   // if the other expression is a pointer.
9835   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9836       NonNullType->canDecayToPointerType())
9837     return;
9838 
9839   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9840       << LHSNull /* LHS is NULL */ << NonNullType
9841       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9842 }
9843 
9844 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9845                                           SourceLocation Loc) {
9846   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9847   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9848   if (!LUE || !RUE)
9849     return;
9850   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9851       RUE->getKind() != UETT_SizeOf)
9852     return;
9853 
9854   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9855   QualType LHSTy = LHSArg->getType();
9856   QualType RHSTy;
9857 
9858   if (RUE->isArgumentType())
9859     RHSTy = RUE->getArgumentType();
9860   else
9861     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9862 
9863   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9864     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9865       return;
9866 
9867     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9868     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9869       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9870         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9871             << LHSArgDecl;
9872     }
9873   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9874     QualType ArrayElemTy = ArrayTy->getElementType();
9875     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9876         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9877         ArrayElemTy->isCharType() ||
9878         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9879       return;
9880     S.Diag(Loc, diag::warn_division_sizeof_array)
9881         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9882     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9883       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9884         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9885             << LHSArgDecl;
9886     }
9887 
9888     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9889   }
9890 }
9891 
9892 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9893                                                ExprResult &RHS,
9894                                                SourceLocation Loc, bool IsDiv) {
9895   // Check for division/remainder by zero.
9896   Expr::EvalResult RHSValue;
9897   if (!RHS.get()->isValueDependent() &&
9898       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9899       RHSValue.Val.getInt() == 0)
9900     S.DiagRuntimeBehavior(Loc, RHS.get(),
9901                           S.PDiag(diag::warn_remainder_division_by_zero)
9902                             << IsDiv << RHS.get()->getSourceRange());
9903 }
9904 
9905 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9906                                            SourceLocation Loc,
9907                                            bool IsCompAssign, bool IsDiv) {
9908   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9909 
9910   if (LHS.get()->getType()->isVectorType() ||
9911       RHS.get()->getType()->isVectorType())
9912     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9913                                /*AllowBothBool*/getLangOpts().AltiVec,
9914                                /*AllowBoolConversions*/false);
9915 
9916   QualType compType = UsualArithmeticConversions(
9917       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9918   if (LHS.isInvalid() || RHS.isInvalid())
9919     return QualType();
9920 
9921 
9922   if (compType.isNull() || !compType->isArithmeticType())
9923     return InvalidOperands(Loc, LHS, RHS);
9924   if (IsDiv) {
9925     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9926     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9927   }
9928   return compType;
9929 }
9930 
9931 QualType Sema::CheckRemainderOperands(
9932   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9933   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9934 
9935   if (LHS.get()->getType()->isVectorType() ||
9936       RHS.get()->getType()->isVectorType()) {
9937     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9938         RHS.get()->getType()->hasIntegerRepresentation())
9939       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9940                                  /*AllowBothBool*/getLangOpts().AltiVec,
9941                                  /*AllowBoolConversions*/false);
9942     return InvalidOperands(Loc, LHS, RHS);
9943   }
9944 
9945   QualType compType = UsualArithmeticConversions(
9946       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9947   if (LHS.isInvalid() || RHS.isInvalid())
9948     return QualType();
9949 
9950   if (compType.isNull() || !compType->isIntegerType())
9951     return InvalidOperands(Loc, LHS, RHS);
9952   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9953   return compType;
9954 }
9955 
9956 /// Diagnose invalid arithmetic on two void pointers.
9957 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9958                                                 Expr *LHSExpr, Expr *RHSExpr) {
9959   S.Diag(Loc, S.getLangOpts().CPlusPlus
9960                 ? diag::err_typecheck_pointer_arith_void_type
9961                 : diag::ext_gnu_void_ptr)
9962     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9963                             << RHSExpr->getSourceRange();
9964 }
9965 
9966 /// Diagnose invalid arithmetic on a void pointer.
9967 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9968                                             Expr *Pointer) {
9969   S.Diag(Loc, S.getLangOpts().CPlusPlus
9970                 ? diag::err_typecheck_pointer_arith_void_type
9971                 : diag::ext_gnu_void_ptr)
9972     << 0 /* one pointer */ << Pointer->getSourceRange();
9973 }
9974 
9975 /// Diagnose invalid arithmetic on a null pointer.
9976 ///
9977 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9978 /// idiom, which we recognize as a GNU extension.
9979 ///
9980 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9981                                             Expr *Pointer, bool IsGNUIdiom) {
9982   if (IsGNUIdiom)
9983     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9984       << Pointer->getSourceRange();
9985   else
9986     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9987       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9988 }
9989 
9990 /// Diagnose invalid arithmetic on two function pointers.
9991 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9992                                                     Expr *LHS, Expr *RHS) {
9993   assert(LHS->getType()->isAnyPointerType());
9994   assert(RHS->getType()->isAnyPointerType());
9995   S.Diag(Loc, S.getLangOpts().CPlusPlus
9996                 ? diag::err_typecheck_pointer_arith_function_type
9997                 : diag::ext_gnu_ptr_func_arith)
9998     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9999     // We only show the second type if it differs from the first.
10000     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10001                                                    RHS->getType())
10002     << RHS->getType()->getPointeeType()
10003     << LHS->getSourceRange() << RHS->getSourceRange();
10004 }
10005 
10006 /// Diagnose invalid arithmetic on a function pointer.
10007 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10008                                                 Expr *Pointer) {
10009   assert(Pointer->getType()->isAnyPointerType());
10010   S.Diag(Loc, S.getLangOpts().CPlusPlus
10011                 ? diag::err_typecheck_pointer_arith_function_type
10012                 : diag::ext_gnu_ptr_func_arith)
10013     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10014     << 0 /* one pointer, so only one type */
10015     << Pointer->getSourceRange();
10016 }
10017 
10018 /// Emit error if Operand is incomplete pointer type
10019 ///
10020 /// \returns True if pointer has incomplete type
10021 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10022                                                  Expr *Operand) {
10023   QualType ResType = Operand->getType();
10024   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10025     ResType = ResAtomicType->getValueType();
10026 
10027   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10028   QualType PointeeTy = ResType->getPointeeType();
10029   return S.RequireCompleteSizedType(
10030       Loc, PointeeTy,
10031       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10032       Operand->getSourceRange());
10033 }
10034 
10035 /// Check the validity of an arithmetic pointer operand.
10036 ///
10037 /// If the operand has pointer type, this code will check for pointer types
10038 /// which are invalid in arithmetic operations. These will be diagnosed
10039 /// appropriately, including whether or not the use is supported as an
10040 /// extension.
10041 ///
10042 /// \returns True when the operand is valid to use (even if as an extension).
10043 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10044                                             Expr *Operand) {
10045   QualType ResType = Operand->getType();
10046   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10047     ResType = ResAtomicType->getValueType();
10048 
10049   if (!ResType->isAnyPointerType()) return true;
10050 
10051   QualType PointeeTy = ResType->getPointeeType();
10052   if (PointeeTy->isVoidType()) {
10053     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10054     return !S.getLangOpts().CPlusPlus;
10055   }
10056   if (PointeeTy->isFunctionType()) {
10057     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10058     return !S.getLangOpts().CPlusPlus;
10059   }
10060 
10061   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10062 
10063   return true;
10064 }
10065 
10066 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10067 /// operands.
10068 ///
10069 /// This routine will diagnose any invalid arithmetic on pointer operands much
10070 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10071 /// for emitting a single diagnostic even for operations where both LHS and RHS
10072 /// are (potentially problematic) pointers.
10073 ///
10074 /// \returns True when the operand is valid to use (even if as an extension).
10075 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10076                                                 Expr *LHSExpr, Expr *RHSExpr) {
10077   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10078   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10079   if (!isLHSPointer && !isRHSPointer) return true;
10080 
10081   QualType LHSPointeeTy, RHSPointeeTy;
10082   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10083   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10084 
10085   // if both are pointers check if operation is valid wrt address spaces
10086   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
10087     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
10088     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
10089     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
10090       S.Diag(Loc,
10091              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10092           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10093           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10094       return false;
10095     }
10096   }
10097 
10098   // Check for arithmetic on pointers to incomplete types.
10099   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10100   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10101   if (isLHSVoidPtr || isRHSVoidPtr) {
10102     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10103     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10104     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10105 
10106     return !S.getLangOpts().CPlusPlus;
10107   }
10108 
10109   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10110   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10111   if (isLHSFuncPtr || isRHSFuncPtr) {
10112     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10113     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10114                                                                 RHSExpr);
10115     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10116 
10117     return !S.getLangOpts().CPlusPlus;
10118   }
10119 
10120   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10121     return false;
10122   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10123     return false;
10124 
10125   return true;
10126 }
10127 
10128 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10129 /// literal.
10130 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10131                                   Expr *LHSExpr, Expr *RHSExpr) {
10132   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10133   Expr* IndexExpr = RHSExpr;
10134   if (!StrExpr) {
10135     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10136     IndexExpr = LHSExpr;
10137   }
10138 
10139   bool IsStringPlusInt = StrExpr &&
10140       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10141   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10142     return;
10143 
10144   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10145   Self.Diag(OpLoc, diag::warn_string_plus_int)
10146       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10147 
10148   // Only print a fixit for "str" + int, not for int + "str".
10149   if (IndexExpr == RHSExpr) {
10150     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10151     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10152         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10153         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10154         << FixItHint::CreateInsertion(EndLoc, "]");
10155   } else
10156     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10157 }
10158 
10159 /// Emit a warning when adding a char literal to a string.
10160 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10161                                    Expr *LHSExpr, Expr *RHSExpr) {
10162   const Expr *StringRefExpr = LHSExpr;
10163   const CharacterLiteral *CharExpr =
10164       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10165 
10166   if (!CharExpr) {
10167     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10168     StringRefExpr = RHSExpr;
10169   }
10170 
10171   if (!CharExpr || !StringRefExpr)
10172     return;
10173 
10174   const QualType StringType = StringRefExpr->getType();
10175 
10176   // Return if not a PointerType.
10177   if (!StringType->isAnyPointerType())
10178     return;
10179 
10180   // Return if not a CharacterType.
10181   if (!StringType->getPointeeType()->isAnyCharacterType())
10182     return;
10183 
10184   ASTContext &Ctx = Self.getASTContext();
10185   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10186 
10187   const QualType CharType = CharExpr->getType();
10188   if (!CharType->isAnyCharacterType() &&
10189       CharType->isIntegerType() &&
10190       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10191     Self.Diag(OpLoc, diag::warn_string_plus_char)
10192         << DiagRange << Ctx.CharTy;
10193   } else {
10194     Self.Diag(OpLoc, diag::warn_string_plus_char)
10195         << DiagRange << CharExpr->getType();
10196   }
10197 
10198   // Only print a fixit for str + char, not for char + str.
10199   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10200     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10201     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10202         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10203         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10204         << FixItHint::CreateInsertion(EndLoc, "]");
10205   } else {
10206     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10207   }
10208 }
10209 
10210 /// Emit error when two pointers are incompatible.
10211 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10212                                            Expr *LHSExpr, Expr *RHSExpr) {
10213   assert(LHSExpr->getType()->isAnyPointerType());
10214   assert(RHSExpr->getType()->isAnyPointerType());
10215   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10216     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10217     << RHSExpr->getSourceRange();
10218 }
10219 
10220 // C99 6.5.6
10221 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10222                                      SourceLocation Loc, BinaryOperatorKind Opc,
10223                                      QualType* CompLHSTy) {
10224   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10225 
10226   if (LHS.get()->getType()->isVectorType() ||
10227       RHS.get()->getType()->isVectorType()) {
10228     QualType compType = CheckVectorOperands(
10229         LHS, RHS, Loc, CompLHSTy,
10230         /*AllowBothBool*/getLangOpts().AltiVec,
10231         /*AllowBoolConversions*/getLangOpts().ZVector);
10232     if (CompLHSTy) *CompLHSTy = compType;
10233     return compType;
10234   }
10235 
10236   QualType compType = UsualArithmeticConversions(
10237       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10238   if (LHS.isInvalid() || RHS.isInvalid())
10239     return QualType();
10240 
10241   // Diagnose "string literal" '+' int and string '+' "char literal".
10242   if (Opc == BO_Add) {
10243     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10244     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10245   }
10246 
10247   // handle the common case first (both operands are arithmetic).
10248   if (!compType.isNull() && compType->isArithmeticType()) {
10249     if (CompLHSTy) *CompLHSTy = compType;
10250     return compType;
10251   }
10252 
10253   // Type-checking.  Ultimately the pointer's going to be in PExp;
10254   // note that we bias towards the LHS being the pointer.
10255   Expr *PExp = LHS.get(), *IExp = RHS.get();
10256 
10257   bool isObjCPointer;
10258   if (PExp->getType()->isPointerType()) {
10259     isObjCPointer = false;
10260   } else if (PExp->getType()->isObjCObjectPointerType()) {
10261     isObjCPointer = true;
10262   } else {
10263     std::swap(PExp, IExp);
10264     if (PExp->getType()->isPointerType()) {
10265       isObjCPointer = false;
10266     } else if (PExp->getType()->isObjCObjectPointerType()) {
10267       isObjCPointer = true;
10268     } else {
10269       return InvalidOperands(Loc, LHS, RHS);
10270     }
10271   }
10272   assert(PExp->getType()->isAnyPointerType());
10273 
10274   if (!IExp->getType()->isIntegerType())
10275     return InvalidOperands(Loc, LHS, RHS);
10276 
10277   // Adding to a null pointer results in undefined behavior.
10278   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10279           Context, Expr::NPC_ValueDependentIsNotNull)) {
10280     // In C++ adding zero to a null pointer is defined.
10281     Expr::EvalResult KnownVal;
10282     if (!getLangOpts().CPlusPlus ||
10283         (!IExp->isValueDependent() &&
10284          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10285           KnownVal.Val.getInt() != 0))) {
10286       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10287       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10288           Context, BO_Add, PExp, IExp);
10289       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10290     }
10291   }
10292 
10293   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10294     return QualType();
10295 
10296   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10297     return QualType();
10298 
10299   // Check array bounds for pointer arithemtic
10300   CheckArrayAccess(PExp, IExp);
10301 
10302   if (CompLHSTy) {
10303     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10304     if (LHSTy.isNull()) {
10305       LHSTy = LHS.get()->getType();
10306       if (LHSTy->isPromotableIntegerType())
10307         LHSTy = Context.getPromotedIntegerType(LHSTy);
10308     }
10309     *CompLHSTy = LHSTy;
10310   }
10311 
10312   return PExp->getType();
10313 }
10314 
10315 // C99 6.5.6
10316 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10317                                         SourceLocation Loc,
10318                                         QualType* CompLHSTy) {
10319   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10320 
10321   if (LHS.get()->getType()->isVectorType() ||
10322       RHS.get()->getType()->isVectorType()) {
10323     QualType compType = CheckVectorOperands(
10324         LHS, RHS, Loc, CompLHSTy,
10325         /*AllowBothBool*/getLangOpts().AltiVec,
10326         /*AllowBoolConversions*/getLangOpts().ZVector);
10327     if (CompLHSTy) *CompLHSTy = compType;
10328     return compType;
10329   }
10330 
10331   QualType compType = UsualArithmeticConversions(
10332       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10333   if (LHS.isInvalid() || RHS.isInvalid())
10334     return QualType();
10335 
10336   // Enforce type constraints: C99 6.5.6p3.
10337 
10338   // Handle the common case first (both operands are arithmetic).
10339   if (!compType.isNull() && compType->isArithmeticType()) {
10340     if (CompLHSTy) *CompLHSTy = compType;
10341     return compType;
10342   }
10343 
10344   // Either ptr - int   or   ptr - ptr.
10345   if (LHS.get()->getType()->isAnyPointerType()) {
10346     QualType lpointee = LHS.get()->getType()->getPointeeType();
10347 
10348     // Diagnose bad cases where we step over interface counts.
10349     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10350         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10351       return QualType();
10352 
10353     // The result type of a pointer-int computation is the pointer type.
10354     if (RHS.get()->getType()->isIntegerType()) {
10355       // Subtracting from a null pointer should produce a warning.
10356       // The last argument to the diagnose call says this doesn't match the
10357       // GNU int-to-pointer idiom.
10358       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10359                                            Expr::NPC_ValueDependentIsNotNull)) {
10360         // In C++ adding zero to a null pointer is defined.
10361         Expr::EvalResult KnownVal;
10362         if (!getLangOpts().CPlusPlus ||
10363             (!RHS.get()->isValueDependent() &&
10364              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10365               KnownVal.Val.getInt() != 0))) {
10366           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10367         }
10368       }
10369 
10370       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10371         return QualType();
10372 
10373       // Check array bounds for pointer arithemtic
10374       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10375                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10376 
10377       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10378       return LHS.get()->getType();
10379     }
10380 
10381     // Handle pointer-pointer subtractions.
10382     if (const PointerType *RHSPTy
10383           = RHS.get()->getType()->getAs<PointerType>()) {
10384       QualType rpointee = RHSPTy->getPointeeType();
10385 
10386       if (getLangOpts().CPlusPlus) {
10387         // Pointee types must be the same: C++ [expr.add]
10388         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10389           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10390         }
10391       } else {
10392         // Pointee types must be compatible C99 6.5.6p3
10393         if (!Context.typesAreCompatible(
10394                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10395                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10396           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10397           return QualType();
10398         }
10399       }
10400 
10401       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10402                                                LHS.get(), RHS.get()))
10403         return QualType();
10404 
10405       // FIXME: Add warnings for nullptr - ptr.
10406 
10407       // The pointee type may have zero size.  As an extension, a structure or
10408       // union may have zero size or an array may have zero length.  In this
10409       // case subtraction does not make sense.
10410       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10411         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10412         if (ElementSize.isZero()) {
10413           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10414             << rpointee.getUnqualifiedType()
10415             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10416         }
10417       }
10418 
10419       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10420       return Context.getPointerDiffType();
10421     }
10422   }
10423 
10424   return InvalidOperands(Loc, LHS, RHS);
10425 }
10426 
10427 static bool isScopedEnumerationType(QualType T) {
10428   if (const EnumType *ET = T->getAs<EnumType>())
10429     return ET->getDecl()->isScoped();
10430   return false;
10431 }
10432 
10433 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10434                                    SourceLocation Loc, BinaryOperatorKind Opc,
10435                                    QualType LHSType) {
10436   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10437   // so skip remaining warnings as we don't want to modify values within Sema.
10438   if (S.getLangOpts().OpenCL)
10439     return;
10440 
10441   // Check right/shifter operand
10442   Expr::EvalResult RHSResult;
10443   if (RHS.get()->isValueDependent() ||
10444       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10445     return;
10446   llvm::APSInt Right = RHSResult.Val.getInt();
10447 
10448   if (Right.isNegative()) {
10449     S.DiagRuntimeBehavior(Loc, RHS.get(),
10450                           S.PDiag(diag::warn_shift_negative)
10451                             << RHS.get()->getSourceRange());
10452     return;
10453   }
10454 
10455   QualType LHSExprType = LHS.get()->getType();
10456   uint64_t LeftSize = LHSExprType->isExtIntType()
10457                           ? S.Context.getIntWidth(LHSExprType)
10458                           : S.Context.getTypeSize(LHSExprType);
10459   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10460   if (Right.uge(LeftBits)) {
10461     S.DiagRuntimeBehavior(Loc, RHS.get(),
10462                           S.PDiag(diag::warn_shift_gt_typewidth)
10463                             << RHS.get()->getSourceRange());
10464     return;
10465   }
10466 
10467   if (Opc != BO_Shl)
10468     return;
10469 
10470   // When left shifting an ICE which is signed, we can check for overflow which
10471   // according to C++ standards prior to C++2a has undefined behavior
10472   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10473   // more than the maximum value representable in the result type, so never
10474   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10475   // expression is still probably a bug.)
10476   Expr::EvalResult LHSResult;
10477   if (LHS.get()->isValueDependent() ||
10478       LHSType->hasUnsignedIntegerRepresentation() ||
10479       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10480     return;
10481   llvm::APSInt Left = LHSResult.Val.getInt();
10482 
10483   // If LHS does not have a signed type and non-negative value
10484   // then, the behavior is undefined before C++2a. Warn about it.
10485   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10486       !S.getLangOpts().CPlusPlus20) {
10487     S.DiagRuntimeBehavior(Loc, LHS.get(),
10488                           S.PDiag(diag::warn_shift_lhs_negative)
10489                             << LHS.get()->getSourceRange());
10490     return;
10491   }
10492 
10493   llvm::APInt ResultBits =
10494       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10495   if (LeftBits.uge(ResultBits))
10496     return;
10497   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10498   Result = Result.shl(Right);
10499 
10500   // Print the bit representation of the signed integer as an unsigned
10501   // hexadecimal number.
10502   SmallString<40> HexResult;
10503   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10504 
10505   // If we are only missing a sign bit, this is less likely to result in actual
10506   // bugs -- if the result is cast back to an unsigned type, it will have the
10507   // expected value. Thus we place this behind a different warning that can be
10508   // turned off separately if needed.
10509   if (LeftBits == ResultBits - 1) {
10510     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10511         << HexResult << LHSType
10512         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10513     return;
10514   }
10515 
10516   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10517     << HexResult.str() << Result.getMinSignedBits() << LHSType
10518     << Left.getBitWidth() << LHS.get()->getSourceRange()
10519     << RHS.get()->getSourceRange();
10520 }
10521 
10522 /// Return the resulting type when a vector is shifted
10523 ///        by a scalar or vector shift amount.
10524 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10525                                  SourceLocation Loc, bool IsCompAssign) {
10526   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10527   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10528       !LHS.get()->getType()->isVectorType()) {
10529     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10530       << RHS.get()->getType() << LHS.get()->getType()
10531       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10532     return QualType();
10533   }
10534 
10535   if (!IsCompAssign) {
10536     LHS = S.UsualUnaryConversions(LHS.get());
10537     if (LHS.isInvalid()) return QualType();
10538   }
10539 
10540   RHS = S.UsualUnaryConversions(RHS.get());
10541   if (RHS.isInvalid()) return QualType();
10542 
10543   QualType LHSType = LHS.get()->getType();
10544   // Note that LHS might be a scalar because the routine calls not only in
10545   // OpenCL case.
10546   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10547   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10548 
10549   // Note that RHS might not be a vector.
10550   QualType RHSType = RHS.get()->getType();
10551   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10552   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10553 
10554   // The operands need to be integers.
10555   if (!LHSEleType->isIntegerType()) {
10556     S.Diag(Loc, diag::err_typecheck_expect_int)
10557       << LHS.get()->getType() << LHS.get()->getSourceRange();
10558     return QualType();
10559   }
10560 
10561   if (!RHSEleType->isIntegerType()) {
10562     S.Diag(Loc, diag::err_typecheck_expect_int)
10563       << RHS.get()->getType() << RHS.get()->getSourceRange();
10564     return QualType();
10565   }
10566 
10567   if (!LHSVecTy) {
10568     assert(RHSVecTy);
10569     if (IsCompAssign)
10570       return RHSType;
10571     if (LHSEleType != RHSEleType) {
10572       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10573       LHSEleType = RHSEleType;
10574     }
10575     QualType VecTy =
10576         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10577     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10578     LHSType = VecTy;
10579   } else if (RHSVecTy) {
10580     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10581     // are applied component-wise. So if RHS is a vector, then ensure
10582     // that the number of elements is the same as LHS...
10583     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10584       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10585         << LHS.get()->getType() << RHS.get()->getType()
10586         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10587       return QualType();
10588     }
10589     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10590       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10591       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10592       if (LHSBT != RHSBT &&
10593           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10594         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10595             << LHS.get()->getType() << RHS.get()->getType()
10596             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10597       }
10598     }
10599   } else {
10600     // ...else expand RHS to match the number of elements in LHS.
10601     QualType VecTy =
10602       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10603     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10604   }
10605 
10606   return LHSType;
10607 }
10608 
10609 // C99 6.5.7
10610 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10611                                   SourceLocation Loc, BinaryOperatorKind Opc,
10612                                   bool IsCompAssign) {
10613   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10614 
10615   // Vector shifts promote their scalar inputs to vector type.
10616   if (LHS.get()->getType()->isVectorType() ||
10617       RHS.get()->getType()->isVectorType()) {
10618     if (LangOpts.ZVector) {
10619       // The shift operators for the z vector extensions work basically
10620       // like general shifts, except that neither the LHS nor the RHS is
10621       // allowed to be a "vector bool".
10622       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10623         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10624           return InvalidOperands(Loc, LHS, RHS);
10625       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10626         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10627           return InvalidOperands(Loc, LHS, RHS);
10628     }
10629     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10630   }
10631 
10632   // Shifts don't perform usual arithmetic conversions, they just do integer
10633   // promotions on each operand. C99 6.5.7p3
10634 
10635   // For the LHS, do usual unary conversions, but then reset them away
10636   // if this is a compound assignment.
10637   ExprResult OldLHS = LHS;
10638   LHS = UsualUnaryConversions(LHS.get());
10639   if (LHS.isInvalid())
10640     return QualType();
10641   QualType LHSType = LHS.get()->getType();
10642   if (IsCompAssign) LHS = OldLHS;
10643 
10644   // The RHS is simpler.
10645   RHS = UsualUnaryConversions(RHS.get());
10646   if (RHS.isInvalid())
10647     return QualType();
10648   QualType RHSType = RHS.get()->getType();
10649 
10650   // C99 6.5.7p2: Each of the operands shall have integer type.
10651   if (!LHSType->hasIntegerRepresentation() ||
10652       !RHSType->hasIntegerRepresentation())
10653     return InvalidOperands(Loc, LHS, RHS);
10654 
10655   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10656   // hasIntegerRepresentation() above instead of this.
10657   if (isScopedEnumerationType(LHSType) ||
10658       isScopedEnumerationType(RHSType)) {
10659     return InvalidOperands(Loc, LHS, RHS);
10660   }
10661   // Sanity-check shift operands
10662   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10663 
10664   // "The type of the result is that of the promoted left operand."
10665   return LHSType;
10666 }
10667 
10668 /// Diagnose bad pointer comparisons.
10669 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10670                                               ExprResult &LHS, ExprResult &RHS,
10671                                               bool IsError) {
10672   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10673                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10674     << LHS.get()->getType() << RHS.get()->getType()
10675     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10676 }
10677 
10678 /// Returns false if the pointers are converted to a composite type,
10679 /// true otherwise.
10680 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10681                                            ExprResult &LHS, ExprResult &RHS) {
10682   // C++ [expr.rel]p2:
10683   //   [...] Pointer conversions (4.10) and qualification
10684   //   conversions (4.4) are performed on pointer operands (or on
10685   //   a pointer operand and a null pointer constant) to bring
10686   //   them to their composite pointer type. [...]
10687   //
10688   // C++ [expr.eq]p1 uses the same notion for (in)equality
10689   // comparisons of pointers.
10690 
10691   QualType LHSType = LHS.get()->getType();
10692   QualType RHSType = RHS.get()->getType();
10693   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10694          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10695 
10696   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10697   if (T.isNull()) {
10698     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10699         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10700       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10701     else
10702       S.InvalidOperands(Loc, LHS, RHS);
10703     return true;
10704   }
10705 
10706   return false;
10707 }
10708 
10709 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10710                                                     ExprResult &LHS,
10711                                                     ExprResult &RHS,
10712                                                     bool IsError) {
10713   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10714                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10715     << LHS.get()->getType() << RHS.get()->getType()
10716     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10717 }
10718 
10719 static bool isObjCObjectLiteral(ExprResult &E) {
10720   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10721   case Stmt::ObjCArrayLiteralClass:
10722   case Stmt::ObjCDictionaryLiteralClass:
10723   case Stmt::ObjCStringLiteralClass:
10724   case Stmt::ObjCBoxedExprClass:
10725     return true;
10726   default:
10727     // Note that ObjCBoolLiteral is NOT an object literal!
10728     return false;
10729   }
10730 }
10731 
10732 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10733   const ObjCObjectPointerType *Type =
10734     LHS->getType()->getAs<ObjCObjectPointerType>();
10735 
10736   // If this is not actually an Objective-C object, bail out.
10737   if (!Type)
10738     return false;
10739 
10740   // Get the LHS object's interface type.
10741   QualType InterfaceType = Type->getPointeeType();
10742 
10743   // If the RHS isn't an Objective-C object, bail out.
10744   if (!RHS->getType()->isObjCObjectPointerType())
10745     return false;
10746 
10747   // Try to find the -isEqual: method.
10748   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10749   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10750                                                       InterfaceType,
10751                                                       /*IsInstance=*/true);
10752   if (!Method) {
10753     if (Type->isObjCIdType()) {
10754       // For 'id', just check the global pool.
10755       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10756                                                   /*receiverId=*/true);
10757     } else {
10758       // Check protocols.
10759       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10760                                              /*IsInstance=*/true);
10761     }
10762   }
10763 
10764   if (!Method)
10765     return false;
10766 
10767   QualType T = Method->parameters()[0]->getType();
10768   if (!T->isObjCObjectPointerType())
10769     return false;
10770 
10771   QualType R = Method->getReturnType();
10772   if (!R->isScalarType())
10773     return false;
10774 
10775   return true;
10776 }
10777 
10778 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10779   FromE = FromE->IgnoreParenImpCasts();
10780   switch (FromE->getStmtClass()) {
10781     default:
10782       break;
10783     case Stmt::ObjCStringLiteralClass:
10784       // "string literal"
10785       return LK_String;
10786     case Stmt::ObjCArrayLiteralClass:
10787       // "array literal"
10788       return LK_Array;
10789     case Stmt::ObjCDictionaryLiteralClass:
10790       // "dictionary literal"
10791       return LK_Dictionary;
10792     case Stmt::BlockExprClass:
10793       return LK_Block;
10794     case Stmt::ObjCBoxedExprClass: {
10795       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10796       switch (Inner->getStmtClass()) {
10797         case Stmt::IntegerLiteralClass:
10798         case Stmt::FloatingLiteralClass:
10799         case Stmt::CharacterLiteralClass:
10800         case Stmt::ObjCBoolLiteralExprClass:
10801         case Stmt::CXXBoolLiteralExprClass:
10802           // "numeric literal"
10803           return LK_Numeric;
10804         case Stmt::ImplicitCastExprClass: {
10805           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10806           // Boolean literals can be represented by implicit casts.
10807           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10808             return LK_Numeric;
10809           break;
10810         }
10811         default:
10812           break;
10813       }
10814       return LK_Boxed;
10815     }
10816   }
10817   return LK_None;
10818 }
10819 
10820 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10821                                           ExprResult &LHS, ExprResult &RHS,
10822                                           BinaryOperator::Opcode Opc){
10823   Expr *Literal;
10824   Expr *Other;
10825   if (isObjCObjectLiteral(LHS)) {
10826     Literal = LHS.get();
10827     Other = RHS.get();
10828   } else {
10829     Literal = RHS.get();
10830     Other = LHS.get();
10831   }
10832 
10833   // Don't warn on comparisons against nil.
10834   Other = Other->IgnoreParenCasts();
10835   if (Other->isNullPointerConstant(S.getASTContext(),
10836                                    Expr::NPC_ValueDependentIsNotNull))
10837     return;
10838 
10839   // This should be kept in sync with warn_objc_literal_comparison.
10840   // LK_String should always be after the other literals, since it has its own
10841   // warning flag.
10842   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10843   assert(LiteralKind != Sema::LK_Block);
10844   if (LiteralKind == Sema::LK_None) {
10845     llvm_unreachable("Unknown Objective-C object literal kind");
10846   }
10847 
10848   if (LiteralKind == Sema::LK_String)
10849     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10850       << Literal->getSourceRange();
10851   else
10852     S.Diag(Loc, diag::warn_objc_literal_comparison)
10853       << LiteralKind << Literal->getSourceRange();
10854 
10855   if (BinaryOperator::isEqualityOp(Opc) &&
10856       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10857     SourceLocation Start = LHS.get()->getBeginLoc();
10858     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10859     CharSourceRange OpRange =
10860       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10861 
10862     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10863       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10864       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10865       << FixItHint::CreateInsertion(End, "]");
10866   }
10867 }
10868 
10869 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10870 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10871                                            ExprResult &RHS, SourceLocation Loc,
10872                                            BinaryOperatorKind Opc) {
10873   // Check that left hand side is !something.
10874   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10875   if (!UO || UO->getOpcode() != UO_LNot) return;
10876 
10877   // Only check if the right hand side is non-bool arithmetic type.
10878   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10879 
10880   // Make sure that the something in !something is not bool.
10881   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10882   if (SubExpr->isKnownToHaveBooleanValue()) return;
10883 
10884   // Emit warning.
10885   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10886   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10887       << Loc << IsBitwiseOp;
10888 
10889   // First note suggest !(x < y)
10890   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10891   SourceLocation FirstClose = RHS.get()->getEndLoc();
10892   FirstClose = S.getLocForEndOfToken(FirstClose);
10893   if (FirstClose.isInvalid())
10894     FirstOpen = SourceLocation();
10895   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10896       << IsBitwiseOp
10897       << FixItHint::CreateInsertion(FirstOpen, "(")
10898       << FixItHint::CreateInsertion(FirstClose, ")");
10899 
10900   // Second note suggests (!x) < y
10901   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10902   SourceLocation SecondClose = LHS.get()->getEndLoc();
10903   SecondClose = S.getLocForEndOfToken(SecondClose);
10904   if (SecondClose.isInvalid())
10905     SecondOpen = SourceLocation();
10906   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10907       << FixItHint::CreateInsertion(SecondOpen, "(")
10908       << FixItHint::CreateInsertion(SecondClose, ")");
10909 }
10910 
10911 // Returns true if E refers to a non-weak array.
10912 static bool checkForArray(const Expr *E) {
10913   const ValueDecl *D = nullptr;
10914   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10915     D = DR->getDecl();
10916   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10917     if (Mem->isImplicitAccess())
10918       D = Mem->getMemberDecl();
10919   }
10920   if (!D)
10921     return false;
10922   return D->getType()->isArrayType() && !D->isWeak();
10923 }
10924 
10925 /// Diagnose some forms of syntactically-obvious tautological comparison.
10926 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10927                                            Expr *LHS, Expr *RHS,
10928                                            BinaryOperatorKind Opc) {
10929   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10930   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10931 
10932   QualType LHSType = LHS->getType();
10933   QualType RHSType = RHS->getType();
10934   if (LHSType->hasFloatingRepresentation() ||
10935       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10936       S.inTemplateInstantiation())
10937     return;
10938 
10939   // Comparisons between two array types are ill-formed for operator<=>, so
10940   // we shouldn't emit any additional warnings about it.
10941   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10942     return;
10943 
10944   // For non-floating point types, check for self-comparisons of the form
10945   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10946   // often indicate logic errors in the program.
10947   //
10948   // NOTE: Don't warn about comparison expressions resulting from macro
10949   // expansion. Also don't warn about comparisons which are only self
10950   // comparisons within a template instantiation. The warnings should catch
10951   // obvious cases in the definition of the template anyways. The idea is to
10952   // warn when the typed comparison operator will always evaluate to the same
10953   // result.
10954 
10955   // Used for indexing into %select in warn_comparison_always
10956   enum {
10957     AlwaysConstant,
10958     AlwaysTrue,
10959     AlwaysFalse,
10960     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10961   };
10962 
10963   // C++2a [depr.array.comp]:
10964   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10965   //   operands of array type are deprecated.
10966   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
10967       RHSStripped->getType()->isArrayType()) {
10968     S.Diag(Loc, diag::warn_depr_array_comparison)
10969         << LHS->getSourceRange() << RHS->getSourceRange()
10970         << LHSStripped->getType() << RHSStripped->getType();
10971     // Carry on to produce the tautological comparison warning, if this
10972     // expression is potentially-evaluated, we can resolve the array to a
10973     // non-weak declaration, and so on.
10974   }
10975 
10976   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10977     if (Expr::isSameComparisonOperand(LHS, RHS)) {
10978       unsigned Result;
10979       switch (Opc) {
10980       case BO_EQ:
10981       case BO_LE:
10982       case BO_GE:
10983         Result = AlwaysTrue;
10984         break;
10985       case BO_NE:
10986       case BO_LT:
10987       case BO_GT:
10988         Result = AlwaysFalse;
10989         break;
10990       case BO_Cmp:
10991         Result = AlwaysEqual;
10992         break;
10993       default:
10994         Result = AlwaysConstant;
10995         break;
10996       }
10997       S.DiagRuntimeBehavior(Loc, nullptr,
10998                             S.PDiag(diag::warn_comparison_always)
10999                                 << 0 /*self-comparison*/
11000                                 << Result);
11001     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11002       // What is it always going to evaluate to?
11003       unsigned Result;
11004       switch (Opc) {
11005       case BO_EQ: // e.g. array1 == array2
11006         Result = AlwaysFalse;
11007         break;
11008       case BO_NE: // e.g. array1 != array2
11009         Result = AlwaysTrue;
11010         break;
11011       default: // e.g. array1 <= array2
11012         // The best we can say is 'a constant'
11013         Result = AlwaysConstant;
11014         break;
11015       }
11016       S.DiagRuntimeBehavior(Loc, nullptr,
11017                             S.PDiag(diag::warn_comparison_always)
11018                                 << 1 /*array comparison*/
11019                                 << Result);
11020     }
11021   }
11022 
11023   if (isa<CastExpr>(LHSStripped))
11024     LHSStripped = LHSStripped->IgnoreParenCasts();
11025   if (isa<CastExpr>(RHSStripped))
11026     RHSStripped = RHSStripped->IgnoreParenCasts();
11027 
11028   // Warn about comparisons against a string constant (unless the other
11029   // operand is null); the user probably wants string comparison function.
11030   Expr *LiteralString = nullptr;
11031   Expr *LiteralStringStripped = nullptr;
11032   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11033       !RHSStripped->isNullPointerConstant(S.Context,
11034                                           Expr::NPC_ValueDependentIsNull)) {
11035     LiteralString = LHS;
11036     LiteralStringStripped = LHSStripped;
11037   } else if ((isa<StringLiteral>(RHSStripped) ||
11038               isa<ObjCEncodeExpr>(RHSStripped)) &&
11039              !LHSStripped->isNullPointerConstant(S.Context,
11040                                           Expr::NPC_ValueDependentIsNull)) {
11041     LiteralString = RHS;
11042     LiteralStringStripped = RHSStripped;
11043   }
11044 
11045   if (LiteralString) {
11046     S.DiagRuntimeBehavior(Loc, nullptr,
11047                           S.PDiag(diag::warn_stringcompare)
11048                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11049                               << LiteralString->getSourceRange());
11050   }
11051 }
11052 
11053 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11054   switch (CK) {
11055   default: {
11056 #ifndef NDEBUG
11057     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11058                  << "\n";
11059 #endif
11060     llvm_unreachable("unhandled cast kind");
11061   }
11062   case CK_UserDefinedConversion:
11063     return ICK_Identity;
11064   case CK_LValueToRValue:
11065     return ICK_Lvalue_To_Rvalue;
11066   case CK_ArrayToPointerDecay:
11067     return ICK_Array_To_Pointer;
11068   case CK_FunctionToPointerDecay:
11069     return ICK_Function_To_Pointer;
11070   case CK_IntegralCast:
11071     return ICK_Integral_Conversion;
11072   case CK_FloatingCast:
11073     return ICK_Floating_Conversion;
11074   case CK_IntegralToFloating:
11075   case CK_FloatingToIntegral:
11076     return ICK_Floating_Integral;
11077   case CK_IntegralComplexCast:
11078   case CK_FloatingComplexCast:
11079   case CK_FloatingComplexToIntegralComplex:
11080   case CK_IntegralComplexToFloatingComplex:
11081     return ICK_Complex_Conversion;
11082   case CK_FloatingComplexToReal:
11083   case CK_FloatingRealToComplex:
11084   case CK_IntegralComplexToReal:
11085   case CK_IntegralRealToComplex:
11086     return ICK_Complex_Real;
11087   }
11088 }
11089 
11090 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11091                                              QualType FromType,
11092                                              SourceLocation Loc) {
11093   // Check for a narrowing implicit conversion.
11094   StandardConversionSequence SCS;
11095   SCS.setAsIdentityConversion();
11096   SCS.setToType(0, FromType);
11097   SCS.setToType(1, ToType);
11098   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11099     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11100 
11101   APValue PreNarrowingValue;
11102   QualType PreNarrowingType;
11103   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11104                                PreNarrowingType,
11105                                /*IgnoreFloatToIntegralConversion*/ true)) {
11106   case NK_Dependent_Narrowing:
11107     // Implicit conversion to a narrower type, but the expression is
11108     // value-dependent so we can't tell whether it's actually narrowing.
11109   case NK_Not_Narrowing:
11110     return false;
11111 
11112   case NK_Constant_Narrowing:
11113     // Implicit conversion to a narrower type, and the value is not a constant
11114     // expression.
11115     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11116         << /*Constant*/ 1
11117         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11118     return true;
11119 
11120   case NK_Variable_Narrowing:
11121     // Implicit conversion to a narrower type, and the value is not a constant
11122     // expression.
11123   case NK_Type_Narrowing:
11124     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11125         << /*Constant*/ 0 << FromType << ToType;
11126     // TODO: It's not a constant expression, but what if the user intended it
11127     // to be? Can we produce notes to help them figure out why it isn't?
11128     return true;
11129   }
11130   llvm_unreachable("unhandled case in switch");
11131 }
11132 
11133 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11134                                                          ExprResult &LHS,
11135                                                          ExprResult &RHS,
11136                                                          SourceLocation Loc) {
11137   QualType LHSType = LHS.get()->getType();
11138   QualType RHSType = RHS.get()->getType();
11139   // Dig out the original argument type and expression before implicit casts
11140   // were applied. These are the types/expressions we need to check the
11141   // [expr.spaceship] requirements against.
11142   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11143   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11144   QualType LHSStrippedType = LHSStripped.get()->getType();
11145   QualType RHSStrippedType = RHSStripped.get()->getType();
11146 
11147   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11148   // other is not, the program is ill-formed.
11149   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11150     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11151     return QualType();
11152   }
11153 
11154   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11155   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11156                     RHSStrippedType->isEnumeralType();
11157   if (NumEnumArgs == 1) {
11158     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11159     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11160     if (OtherTy->hasFloatingRepresentation()) {
11161       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11162       return QualType();
11163     }
11164   }
11165   if (NumEnumArgs == 2) {
11166     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11167     // type E, the operator yields the result of converting the operands
11168     // to the underlying type of E and applying <=> to the converted operands.
11169     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11170       S.InvalidOperands(Loc, LHS, RHS);
11171       return QualType();
11172     }
11173     QualType IntType =
11174         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11175     assert(IntType->isArithmeticType());
11176 
11177     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11178     // promote the boolean type, and all other promotable integer types, to
11179     // avoid this.
11180     if (IntType->isPromotableIntegerType())
11181       IntType = S.Context.getPromotedIntegerType(IntType);
11182 
11183     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11184     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11185     LHSType = RHSType = IntType;
11186   }
11187 
11188   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11189   // usual arithmetic conversions are applied to the operands.
11190   QualType Type =
11191       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11192   if (LHS.isInvalid() || RHS.isInvalid())
11193     return QualType();
11194   if (Type.isNull())
11195     return S.InvalidOperands(Loc, LHS, RHS);
11196 
11197   Optional<ComparisonCategoryType> CCT =
11198       getComparisonCategoryForBuiltinCmp(Type);
11199   if (!CCT)
11200     return S.InvalidOperands(Loc, LHS, RHS);
11201 
11202   bool HasNarrowing = checkThreeWayNarrowingConversion(
11203       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11204   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11205                                                    RHS.get()->getBeginLoc());
11206   if (HasNarrowing)
11207     return QualType();
11208 
11209   assert(!Type.isNull() && "composite type for <=> has not been set");
11210 
11211   return S.CheckComparisonCategoryType(
11212       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11213 }
11214 
11215 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11216                                                  ExprResult &RHS,
11217                                                  SourceLocation Loc,
11218                                                  BinaryOperatorKind Opc) {
11219   if (Opc == BO_Cmp)
11220     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11221 
11222   // C99 6.5.8p3 / C99 6.5.9p4
11223   QualType Type =
11224       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11225   if (LHS.isInvalid() || RHS.isInvalid())
11226     return QualType();
11227   if (Type.isNull())
11228     return S.InvalidOperands(Loc, LHS, RHS);
11229   assert(Type->isArithmeticType() || Type->isEnumeralType());
11230 
11231   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11232     return S.InvalidOperands(Loc, LHS, RHS);
11233 
11234   // Check for comparisons of floating point operands using != and ==.
11235   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11236     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11237 
11238   // The result of comparisons is 'bool' in C++, 'int' in C.
11239   return S.Context.getLogicalOperationType();
11240 }
11241 
11242 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11243   if (!NullE.get()->getType()->isAnyPointerType())
11244     return;
11245   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11246   if (!E.get()->getType()->isAnyPointerType() &&
11247       E.get()->isNullPointerConstant(Context,
11248                                      Expr::NPC_ValueDependentIsNotNull) ==
11249         Expr::NPCK_ZeroExpression) {
11250     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11251       if (CL->getValue() == 0)
11252         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11253             << NullValue
11254             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11255                                             NullValue ? "NULL" : "(void *)0");
11256     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11257         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11258         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11259         if (T == Context.CharTy)
11260           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11261               << NullValue
11262               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11263                                               NullValue ? "NULL" : "(void *)0");
11264       }
11265   }
11266 }
11267 
11268 // C99 6.5.8, C++ [expr.rel]
11269 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11270                                     SourceLocation Loc,
11271                                     BinaryOperatorKind Opc) {
11272   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11273   bool IsThreeWay = Opc == BO_Cmp;
11274   bool IsOrdered = IsRelational || IsThreeWay;
11275   auto IsAnyPointerType = [](ExprResult E) {
11276     QualType Ty = E.get()->getType();
11277     return Ty->isPointerType() || Ty->isMemberPointerType();
11278   };
11279 
11280   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11281   // type, array-to-pointer, ..., conversions are performed on both operands to
11282   // bring them to their composite type.
11283   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11284   // any type-related checks.
11285   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11286     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11287     if (LHS.isInvalid())
11288       return QualType();
11289     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11290     if (RHS.isInvalid())
11291       return QualType();
11292   } else {
11293     LHS = DefaultLvalueConversion(LHS.get());
11294     if (LHS.isInvalid())
11295       return QualType();
11296     RHS = DefaultLvalueConversion(RHS.get());
11297     if (RHS.isInvalid())
11298       return QualType();
11299   }
11300 
11301   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11302   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11303     CheckPtrComparisonWithNullChar(LHS, RHS);
11304     CheckPtrComparisonWithNullChar(RHS, LHS);
11305   }
11306 
11307   // Handle vector comparisons separately.
11308   if (LHS.get()->getType()->isVectorType() ||
11309       RHS.get()->getType()->isVectorType())
11310     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11311 
11312   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11313   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11314 
11315   QualType LHSType = LHS.get()->getType();
11316   QualType RHSType = RHS.get()->getType();
11317   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11318       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11319     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11320 
11321   const Expr::NullPointerConstantKind LHSNullKind =
11322       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11323   const Expr::NullPointerConstantKind RHSNullKind =
11324       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11325   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11326   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11327 
11328   auto computeResultTy = [&]() {
11329     if (Opc != BO_Cmp)
11330       return Context.getLogicalOperationType();
11331     assert(getLangOpts().CPlusPlus);
11332     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11333 
11334     QualType CompositeTy = LHS.get()->getType();
11335     assert(!CompositeTy->isReferenceType());
11336 
11337     Optional<ComparisonCategoryType> CCT =
11338         getComparisonCategoryForBuiltinCmp(CompositeTy);
11339     if (!CCT)
11340       return InvalidOperands(Loc, LHS, RHS);
11341 
11342     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11343       // P0946R0: Comparisons between a null pointer constant and an object
11344       // pointer result in std::strong_equality, which is ill-formed under
11345       // P1959R0.
11346       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11347           << (LHSIsNull ? LHS.get()->getSourceRange()
11348                         : RHS.get()->getSourceRange());
11349       return QualType();
11350     }
11351 
11352     return CheckComparisonCategoryType(
11353         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11354   };
11355 
11356   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11357     bool IsEquality = Opc == BO_EQ;
11358     if (RHSIsNull)
11359       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11360                                    RHS.get()->getSourceRange());
11361     else
11362       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11363                                    LHS.get()->getSourceRange());
11364   }
11365 
11366   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11367       (RHSType->isIntegerType() && !RHSIsNull)) {
11368     // Skip normal pointer conversion checks in this case; we have better
11369     // diagnostics for this below.
11370   } else if (getLangOpts().CPlusPlus) {
11371     // Equality comparison of a function pointer to a void pointer is invalid,
11372     // but we allow it as an extension.
11373     // FIXME: If we really want to allow this, should it be part of composite
11374     // pointer type computation so it works in conditionals too?
11375     if (!IsOrdered &&
11376         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11377          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11378       // This is a gcc extension compatibility comparison.
11379       // In a SFINAE context, we treat this as a hard error to maintain
11380       // conformance with the C++ standard.
11381       diagnoseFunctionPointerToVoidComparison(
11382           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11383 
11384       if (isSFINAEContext())
11385         return QualType();
11386 
11387       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11388       return computeResultTy();
11389     }
11390 
11391     // C++ [expr.eq]p2:
11392     //   If at least one operand is a pointer [...] bring them to their
11393     //   composite pointer type.
11394     // C++ [expr.spaceship]p6
11395     //  If at least one of the operands is of pointer type, [...] bring them
11396     //  to their composite pointer type.
11397     // C++ [expr.rel]p2:
11398     //   If both operands are pointers, [...] bring them to their composite
11399     //   pointer type.
11400     // For <=>, the only valid non-pointer types are arrays and functions, and
11401     // we already decayed those, so this is really the same as the relational
11402     // comparison rule.
11403     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11404             (IsOrdered ? 2 : 1) &&
11405         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11406                                          RHSType->isObjCObjectPointerType()))) {
11407       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11408         return QualType();
11409       return computeResultTy();
11410     }
11411   } else if (LHSType->isPointerType() &&
11412              RHSType->isPointerType()) { // C99 6.5.8p2
11413     // All of the following pointer-related warnings are GCC extensions, except
11414     // when handling null pointer constants.
11415     QualType LCanPointeeTy =
11416       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11417     QualType RCanPointeeTy =
11418       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11419 
11420     // C99 6.5.9p2 and C99 6.5.8p2
11421     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11422                                    RCanPointeeTy.getUnqualifiedType())) {
11423       // Valid unless a relational comparison of function pointers
11424       if (IsRelational && LCanPointeeTy->isFunctionType()) {
11425         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11426           << LHSType << RHSType << LHS.get()->getSourceRange()
11427           << RHS.get()->getSourceRange();
11428       }
11429     } else if (!IsRelational &&
11430                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11431       // Valid unless comparison between non-null pointer and function pointer
11432       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11433           && !LHSIsNull && !RHSIsNull)
11434         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11435                                                 /*isError*/false);
11436     } else {
11437       // Invalid
11438       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11439     }
11440     if (LCanPointeeTy != RCanPointeeTy) {
11441       // Treat NULL constant as a special case in OpenCL.
11442       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11443         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
11444         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
11445           Diag(Loc,
11446                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11447               << LHSType << RHSType << 0 /* comparison */
11448               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11449         }
11450       }
11451       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11452       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11453       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11454                                                : CK_BitCast;
11455       if (LHSIsNull && !RHSIsNull)
11456         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11457       else
11458         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11459     }
11460     return computeResultTy();
11461   }
11462 
11463   if (getLangOpts().CPlusPlus) {
11464     // C++ [expr.eq]p4:
11465     //   Two operands of type std::nullptr_t or one operand of type
11466     //   std::nullptr_t and the other a null pointer constant compare equal.
11467     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11468       if (LHSType->isNullPtrType()) {
11469         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11470         return computeResultTy();
11471       }
11472       if (RHSType->isNullPtrType()) {
11473         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11474         return computeResultTy();
11475       }
11476     }
11477 
11478     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11479     // These aren't covered by the composite pointer type rules.
11480     if (!IsOrdered && RHSType->isNullPtrType() &&
11481         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11482       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11483       return computeResultTy();
11484     }
11485     if (!IsOrdered && LHSType->isNullPtrType() &&
11486         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11487       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11488       return computeResultTy();
11489     }
11490 
11491     if (IsRelational &&
11492         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11493          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11494       // HACK: Relational comparison of nullptr_t against a pointer type is
11495       // invalid per DR583, but we allow it within std::less<> and friends,
11496       // since otherwise common uses of it break.
11497       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11498       // friends to have std::nullptr_t overload candidates.
11499       DeclContext *DC = CurContext;
11500       if (isa<FunctionDecl>(DC))
11501         DC = DC->getParent();
11502       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11503         if (CTSD->isInStdNamespace() &&
11504             llvm::StringSwitch<bool>(CTSD->getName())
11505                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11506                 .Default(false)) {
11507           if (RHSType->isNullPtrType())
11508             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11509           else
11510             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11511           return computeResultTy();
11512         }
11513       }
11514     }
11515 
11516     // C++ [expr.eq]p2:
11517     //   If at least one operand is a pointer to member, [...] bring them to
11518     //   their composite pointer type.
11519     if (!IsOrdered &&
11520         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11521       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11522         return QualType();
11523       else
11524         return computeResultTy();
11525     }
11526   }
11527 
11528   // Handle block pointer types.
11529   if (!IsOrdered && LHSType->isBlockPointerType() &&
11530       RHSType->isBlockPointerType()) {
11531     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11532     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11533 
11534     if (!LHSIsNull && !RHSIsNull &&
11535         !Context.typesAreCompatible(lpointee, rpointee)) {
11536       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11537         << LHSType << RHSType << LHS.get()->getSourceRange()
11538         << RHS.get()->getSourceRange();
11539     }
11540     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11541     return computeResultTy();
11542   }
11543 
11544   // Allow block pointers to be compared with null pointer constants.
11545   if (!IsOrdered
11546       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11547           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11548     if (!LHSIsNull && !RHSIsNull) {
11549       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11550              ->getPointeeType()->isVoidType())
11551             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11552                 ->getPointeeType()->isVoidType())))
11553         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11554           << LHSType << RHSType << LHS.get()->getSourceRange()
11555           << RHS.get()->getSourceRange();
11556     }
11557     if (LHSIsNull && !RHSIsNull)
11558       LHS = ImpCastExprToType(LHS.get(), RHSType,
11559                               RHSType->isPointerType() ? CK_BitCast
11560                                 : CK_AnyPointerToBlockPointerCast);
11561     else
11562       RHS = ImpCastExprToType(RHS.get(), LHSType,
11563                               LHSType->isPointerType() ? CK_BitCast
11564                                 : CK_AnyPointerToBlockPointerCast);
11565     return computeResultTy();
11566   }
11567 
11568   if (LHSType->isObjCObjectPointerType() ||
11569       RHSType->isObjCObjectPointerType()) {
11570     const PointerType *LPT = LHSType->getAs<PointerType>();
11571     const PointerType *RPT = RHSType->getAs<PointerType>();
11572     if (LPT || RPT) {
11573       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11574       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11575 
11576       if (!LPtrToVoid && !RPtrToVoid &&
11577           !Context.typesAreCompatible(LHSType, RHSType)) {
11578         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11579                                           /*isError*/false);
11580       }
11581       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11582       // the RHS, but we have test coverage for this behavior.
11583       // FIXME: Consider using convertPointersToCompositeType in C++.
11584       if (LHSIsNull && !RHSIsNull) {
11585         Expr *E = LHS.get();
11586         if (getLangOpts().ObjCAutoRefCount)
11587           CheckObjCConversion(SourceRange(), RHSType, E,
11588                               CCK_ImplicitConversion);
11589         LHS = ImpCastExprToType(E, RHSType,
11590                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11591       }
11592       else {
11593         Expr *E = RHS.get();
11594         if (getLangOpts().ObjCAutoRefCount)
11595           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11596                               /*Diagnose=*/true,
11597                               /*DiagnoseCFAudited=*/false, Opc);
11598         RHS = ImpCastExprToType(E, LHSType,
11599                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11600       }
11601       return computeResultTy();
11602     }
11603     if (LHSType->isObjCObjectPointerType() &&
11604         RHSType->isObjCObjectPointerType()) {
11605       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11606         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11607                                           /*isError*/false);
11608       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11609         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11610 
11611       if (LHSIsNull && !RHSIsNull)
11612         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11613       else
11614         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11615       return computeResultTy();
11616     }
11617 
11618     if (!IsOrdered && LHSType->isBlockPointerType() &&
11619         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11620       LHS = ImpCastExprToType(LHS.get(), RHSType,
11621                               CK_BlockPointerToObjCPointerCast);
11622       return computeResultTy();
11623     } else if (!IsOrdered &&
11624                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11625                RHSType->isBlockPointerType()) {
11626       RHS = ImpCastExprToType(RHS.get(), LHSType,
11627                               CK_BlockPointerToObjCPointerCast);
11628       return computeResultTy();
11629     }
11630   }
11631   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11632       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11633     unsigned DiagID = 0;
11634     bool isError = false;
11635     if (LangOpts.DebuggerSupport) {
11636       // Under a debugger, allow the comparison of pointers to integers,
11637       // since users tend to want to compare addresses.
11638     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11639                (RHSIsNull && RHSType->isIntegerType())) {
11640       if (IsOrdered) {
11641         isError = getLangOpts().CPlusPlus;
11642         DiagID =
11643           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11644                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11645       }
11646     } else if (getLangOpts().CPlusPlus) {
11647       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11648       isError = true;
11649     } else if (IsOrdered)
11650       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11651     else
11652       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11653 
11654     if (DiagID) {
11655       Diag(Loc, DiagID)
11656         << LHSType << RHSType << LHS.get()->getSourceRange()
11657         << RHS.get()->getSourceRange();
11658       if (isError)
11659         return QualType();
11660     }
11661 
11662     if (LHSType->isIntegerType())
11663       LHS = ImpCastExprToType(LHS.get(), RHSType,
11664                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11665     else
11666       RHS = ImpCastExprToType(RHS.get(), LHSType,
11667                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11668     return computeResultTy();
11669   }
11670 
11671   // Handle block pointers.
11672   if (!IsOrdered && RHSIsNull
11673       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11674     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11675     return computeResultTy();
11676   }
11677   if (!IsOrdered && LHSIsNull
11678       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11679     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11680     return computeResultTy();
11681   }
11682 
11683   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11684     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11685       return computeResultTy();
11686     }
11687 
11688     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11689       return computeResultTy();
11690     }
11691 
11692     if (LHSIsNull && RHSType->isQueueT()) {
11693       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11694       return computeResultTy();
11695     }
11696 
11697     if (LHSType->isQueueT() && RHSIsNull) {
11698       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11699       return computeResultTy();
11700     }
11701   }
11702 
11703   return InvalidOperands(Loc, LHS, RHS);
11704 }
11705 
11706 // Return a signed ext_vector_type that is of identical size and number of
11707 // elements. For floating point vectors, return an integer type of identical
11708 // size and number of elements. In the non ext_vector_type case, search from
11709 // the largest type to the smallest type to avoid cases where long long == long,
11710 // where long gets picked over long long.
11711 QualType Sema::GetSignedVectorType(QualType V) {
11712   const VectorType *VTy = V->castAs<VectorType>();
11713   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11714 
11715   if (isa<ExtVectorType>(VTy)) {
11716     if (TypeSize == Context.getTypeSize(Context.CharTy))
11717       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11718     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11719       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11720     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11721       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11722     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11723       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11724     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11725            "Unhandled vector element size in vector compare");
11726     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11727   }
11728 
11729   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11730     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11731                                  VectorType::GenericVector);
11732   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11733     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11734                                  VectorType::GenericVector);
11735   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11736     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11737                                  VectorType::GenericVector);
11738   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11739     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11740                                  VectorType::GenericVector);
11741   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11742          "Unhandled vector element size in vector compare");
11743   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11744                                VectorType::GenericVector);
11745 }
11746 
11747 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11748 /// operates on extended vector types.  Instead of producing an IntTy result,
11749 /// like a scalar comparison, a vector comparison produces a vector of integer
11750 /// types.
11751 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11752                                           SourceLocation Loc,
11753                                           BinaryOperatorKind Opc) {
11754   if (Opc == BO_Cmp) {
11755     Diag(Loc, diag::err_three_way_vector_comparison);
11756     return QualType();
11757   }
11758 
11759   // Check to make sure we're operating on vectors of the same type and width,
11760   // Allowing one side to be a scalar of element type.
11761   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11762                               /*AllowBothBool*/true,
11763                               /*AllowBoolConversions*/getLangOpts().ZVector);
11764   if (vType.isNull())
11765     return vType;
11766 
11767   QualType LHSType = LHS.get()->getType();
11768 
11769   // If AltiVec, the comparison results in a numeric type, i.e.
11770   // bool for C++, int for C
11771   if (getLangOpts().AltiVec &&
11772       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11773     return Context.getLogicalOperationType();
11774 
11775   // For non-floating point types, check for self-comparisons of the form
11776   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11777   // often indicate logic errors in the program.
11778   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11779 
11780   // Check for comparisons of floating point operands using != and ==.
11781   if (BinaryOperator::isEqualityOp(Opc) &&
11782       LHSType->hasFloatingRepresentation()) {
11783     assert(RHS.get()->getType()->hasFloatingRepresentation());
11784     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11785   }
11786 
11787   // Return a signed type for the vector.
11788   return GetSignedVectorType(vType);
11789 }
11790 
11791 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11792                                     const ExprResult &XorRHS,
11793                                     const SourceLocation Loc) {
11794   // Do not diagnose macros.
11795   if (Loc.isMacroID())
11796     return;
11797 
11798   bool Negative = false;
11799   bool ExplicitPlus = false;
11800   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11801   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11802 
11803   if (!LHSInt)
11804     return;
11805   if (!RHSInt) {
11806     // Check negative literals.
11807     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11808       UnaryOperatorKind Opc = UO->getOpcode();
11809       if (Opc != UO_Minus && Opc != UO_Plus)
11810         return;
11811       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11812       if (!RHSInt)
11813         return;
11814       Negative = (Opc == UO_Minus);
11815       ExplicitPlus = !Negative;
11816     } else {
11817       return;
11818     }
11819   }
11820 
11821   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11822   llvm::APInt RightSideValue = RHSInt->getValue();
11823   if (LeftSideValue != 2 && LeftSideValue != 10)
11824     return;
11825 
11826   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11827     return;
11828 
11829   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11830       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11831   llvm::StringRef ExprStr =
11832       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11833 
11834   CharSourceRange XorRange =
11835       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11836   llvm::StringRef XorStr =
11837       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11838   // Do not diagnose if xor keyword/macro is used.
11839   if (XorStr == "xor")
11840     return;
11841 
11842   std::string LHSStr = std::string(Lexer::getSourceText(
11843       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11844       S.getSourceManager(), S.getLangOpts()));
11845   std::string RHSStr = std::string(Lexer::getSourceText(
11846       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11847       S.getSourceManager(), S.getLangOpts()));
11848 
11849   if (Negative) {
11850     RightSideValue = -RightSideValue;
11851     RHSStr = "-" + RHSStr;
11852   } else if (ExplicitPlus) {
11853     RHSStr = "+" + RHSStr;
11854   }
11855 
11856   StringRef LHSStrRef = LHSStr;
11857   StringRef RHSStrRef = RHSStr;
11858   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11859   // literals.
11860   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11861       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11862       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11863       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11864       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11865       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11866       LHSStrRef.find('\'') != StringRef::npos ||
11867       RHSStrRef.find('\'') != StringRef::npos)
11868     return;
11869 
11870   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11871   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11872   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11873   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11874     std::string SuggestedExpr = "1 << " + RHSStr;
11875     bool Overflow = false;
11876     llvm::APInt One = (LeftSideValue - 1);
11877     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11878     if (Overflow) {
11879       if (RightSideIntValue < 64)
11880         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11881             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11882             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11883       else if (RightSideIntValue == 64)
11884         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11885       else
11886         return;
11887     } else {
11888       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11889           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11890           << PowValue.toString(10, true)
11891           << FixItHint::CreateReplacement(
11892                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11893     }
11894 
11895     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11896   } else if (LeftSideValue == 10) {
11897     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11898     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11899         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11900         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11901     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11902   }
11903 }
11904 
11905 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11906                                           SourceLocation Loc) {
11907   // Ensure that either both operands are of the same vector type, or
11908   // one operand is of a vector type and the other is of its element type.
11909   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11910                                        /*AllowBothBool*/true,
11911                                        /*AllowBoolConversions*/false);
11912   if (vType.isNull())
11913     return InvalidOperands(Loc, LHS, RHS);
11914   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11915       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11916     return InvalidOperands(Loc, LHS, RHS);
11917   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11918   //        usage of the logical operators && and || with vectors in C. This
11919   //        check could be notionally dropped.
11920   if (!getLangOpts().CPlusPlus &&
11921       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11922     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11923 
11924   return GetSignedVectorType(LHS.get()->getType());
11925 }
11926 
11927 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11928                                            SourceLocation Loc,
11929                                            BinaryOperatorKind Opc) {
11930   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11931 
11932   bool IsCompAssign =
11933       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11934 
11935   if (LHS.get()->getType()->isVectorType() ||
11936       RHS.get()->getType()->isVectorType()) {
11937     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11938         RHS.get()->getType()->hasIntegerRepresentation())
11939       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11940                         /*AllowBothBool*/true,
11941                         /*AllowBoolConversions*/getLangOpts().ZVector);
11942     return InvalidOperands(Loc, LHS, RHS);
11943   }
11944 
11945   if (Opc == BO_And)
11946     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11947 
11948   if (LHS.get()->getType()->hasFloatingRepresentation() ||
11949       RHS.get()->getType()->hasFloatingRepresentation())
11950     return InvalidOperands(Loc, LHS, RHS);
11951 
11952   ExprResult LHSResult = LHS, RHSResult = RHS;
11953   QualType compType = UsualArithmeticConversions(
11954       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11955   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11956     return QualType();
11957   LHS = LHSResult.get();
11958   RHS = RHSResult.get();
11959 
11960   if (Opc == BO_Xor)
11961     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11962 
11963   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11964     return compType;
11965   return InvalidOperands(Loc, LHS, RHS);
11966 }
11967 
11968 // C99 6.5.[13,14]
11969 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11970                                            SourceLocation Loc,
11971                                            BinaryOperatorKind Opc) {
11972   // Check vector operands differently.
11973   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11974     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11975 
11976   bool EnumConstantInBoolContext = false;
11977   for (const ExprResult &HS : {LHS, RHS}) {
11978     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11979       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11980       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11981         EnumConstantInBoolContext = true;
11982     }
11983   }
11984 
11985   if (EnumConstantInBoolContext)
11986     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11987 
11988   // Diagnose cases where the user write a logical and/or but probably meant a
11989   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11990   // is a constant.
11991   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11992       !LHS.get()->getType()->isBooleanType() &&
11993       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11994       // Don't warn in macros or template instantiations.
11995       !Loc.isMacroID() && !inTemplateInstantiation()) {
11996     // If the RHS can be constant folded, and if it constant folds to something
11997     // that isn't 0 or 1 (which indicate a potential logical operation that
11998     // happened to fold to true/false) then warn.
11999     // Parens on the RHS are ignored.
12000     Expr::EvalResult EVResult;
12001     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12002       llvm::APSInt Result = EVResult.Val.getInt();
12003       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12004            !RHS.get()->getExprLoc().isMacroID()) ||
12005           (Result != 0 && Result != 1)) {
12006         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12007           << RHS.get()->getSourceRange()
12008           << (Opc == BO_LAnd ? "&&" : "||");
12009         // Suggest replacing the logical operator with the bitwise version
12010         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12011             << (Opc == BO_LAnd ? "&" : "|")
12012             << FixItHint::CreateReplacement(SourceRange(
12013                                                  Loc, getLocForEndOfToken(Loc)),
12014                                             Opc == BO_LAnd ? "&" : "|");
12015         if (Opc == BO_LAnd)
12016           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12017           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12018               << FixItHint::CreateRemoval(
12019                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12020                                  RHS.get()->getEndLoc()));
12021       }
12022     }
12023   }
12024 
12025   if (!Context.getLangOpts().CPlusPlus) {
12026     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12027     // not operate on the built-in scalar and vector float types.
12028     if (Context.getLangOpts().OpenCL &&
12029         Context.getLangOpts().OpenCLVersion < 120) {
12030       if (LHS.get()->getType()->isFloatingType() ||
12031           RHS.get()->getType()->isFloatingType())
12032         return InvalidOperands(Loc, LHS, RHS);
12033     }
12034 
12035     LHS = UsualUnaryConversions(LHS.get());
12036     if (LHS.isInvalid())
12037       return QualType();
12038 
12039     RHS = UsualUnaryConversions(RHS.get());
12040     if (RHS.isInvalid())
12041       return QualType();
12042 
12043     if (!LHS.get()->getType()->isScalarType() ||
12044         !RHS.get()->getType()->isScalarType())
12045       return InvalidOperands(Loc, LHS, RHS);
12046 
12047     return Context.IntTy;
12048   }
12049 
12050   // The following is safe because we only use this method for
12051   // non-overloadable operands.
12052 
12053   // C++ [expr.log.and]p1
12054   // C++ [expr.log.or]p1
12055   // The operands are both contextually converted to type bool.
12056   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12057   if (LHSRes.isInvalid())
12058     return InvalidOperands(Loc, LHS, RHS);
12059   LHS = LHSRes;
12060 
12061   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12062   if (RHSRes.isInvalid())
12063     return InvalidOperands(Loc, LHS, RHS);
12064   RHS = RHSRes;
12065 
12066   // C++ [expr.log.and]p2
12067   // C++ [expr.log.or]p2
12068   // The result is a bool.
12069   return Context.BoolTy;
12070 }
12071 
12072 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12073   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12074   if (!ME) return false;
12075   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12076   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12077       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12078   if (!Base) return false;
12079   return Base->getMethodDecl() != nullptr;
12080 }
12081 
12082 /// Is the given expression (which must be 'const') a reference to a
12083 /// variable which was originally non-const, but which has become
12084 /// 'const' due to being captured within a block?
12085 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12086 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12087   assert(E->isLValue() && E->getType().isConstQualified());
12088   E = E->IgnoreParens();
12089 
12090   // Must be a reference to a declaration from an enclosing scope.
12091   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12092   if (!DRE) return NCCK_None;
12093   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12094 
12095   // The declaration must be a variable which is not declared 'const'.
12096   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12097   if (!var) return NCCK_None;
12098   if (var->getType().isConstQualified()) return NCCK_None;
12099   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12100 
12101   // Decide whether the first capture was for a block or a lambda.
12102   DeclContext *DC = S.CurContext, *Prev = nullptr;
12103   // Decide whether the first capture was for a block or a lambda.
12104   while (DC) {
12105     // For init-capture, it is possible that the variable belongs to the
12106     // template pattern of the current context.
12107     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12108       if (var->isInitCapture() &&
12109           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12110         break;
12111     if (DC == var->getDeclContext())
12112       break;
12113     Prev = DC;
12114     DC = DC->getParent();
12115   }
12116   // Unless we have an init-capture, we've gone one step too far.
12117   if (!var->isInitCapture())
12118     DC = Prev;
12119   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12120 }
12121 
12122 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12123   Ty = Ty.getNonReferenceType();
12124   if (IsDereference && Ty->isPointerType())
12125     Ty = Ty->getPointeeType();
12126   return !Ty.isConstQualified();
12127 }
12128 
12129 // Update err_typecheck_assign_const and note_typecheck_assign_const
12130 // when this enum is changed.
12131 enum {
12132   ConstFunction,
12133   ConstVariable,
12134   ConstMember,
12135   ConstMethod,
12136   NestedConstMember,
12137   ConstUnknown,  // Keep as last element
12138 };
12139 
12140 /// Emit the "read-only variable not assignable" error and print notes to give
12141 /// more information about why the variable is not assignable, such as pointing
12142 /// to the declaration of a const variable, showing that a method is const, or
12143 /// that the function is returning a const reference.
12144 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12145                                     SourceLocation Loc) {
12146   SourceRange ExprRange = E->getSourceRange();
12147 
12148   // Only emit one error on the first const found.  All other consts will emit
12149   // a note to the error.
12150   bool DiagnosticEmitted = false;
12151 
12152   // Track if the current expression is the result of a dereference, and if the
12153   // next checked expression is the result of a dereference.
12154   bool IsDereference = false;
12155   bool NextIsDereference = false;
12156 
12157   // Loop to process MemberExpr chains.
12158   while (true) {
12159     IsDereference = NextIsDereference;
12160 
12161     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12162     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12163       NextIsDereference = ME->isArrow();
12164       const ValueDecl *VD = ME->getMemberDecl();
12165       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12166         // Mutable fields can be modified even if the class is const.
12167         if (Field->isMutable()) {
12168           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12169           break;
12170         }
12171 
12172         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12173           if (!DiagnosticEmitted) {
12174             S.Diag(Loc, diag::err_typecheck_assign_const)
12175                 << ExprRange << ConstMember << false /*static*/ << Field
12176                 << Field->getType();
12177             DiagnosticEmitted = true;
12178           }
12179           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12180               << ConstMember << false /*static*/ << Field << Field->getType()
12181               << Field->getSourceRange();
12182         }
12183         E = ME->getBase();
12184         continue;
12185       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12186         if (VDecl->getType().isConstQualified()) {
12187           if (!DiagnosticEmitted) {
12188             S.Diag(Loc, diag::err_typecheck_assign_const)
12189                 << ExprRange << ConstMember << true /*static*/ << VDecl
12190                 << VDecl->getType();
12191             DiagnosticEmitted = true;
12192           }
12193           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12194               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12195               << VDecl->getSourceRange();
12196         }
12197         // Static fields do not inherit constness from parents.
12198         break;
12199       }
12200       break; // End MemberExpr
12201     } else if (const ArraySubscriptExpr *ASE =
12202                    dyn_cast<ArraySubscriptExpr>(E)) {
12203       E = ASE->getBase()->IgnoreParenImpCasts();
12204       continue;
12205     } else if (const ExtVectorElementExpr *EVE =
12206                    dyn_cast<ExtVectorElementExpr>(E)) {
12207       E = EVE->getBase()->IgnoreParenImpCasts();
12208       continue;
12209     }
12210     break;
12211   }
12212 
12213   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12214     // Function calls
12215     const FunctionDecl *FD = CE->getDirectCallee();
12216     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12217       if (!DiagnosticEmitted) {
12218         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12219                                                       << ConstFunction << FD;
12220         DiagnosticEmitted = true;
12221       }
12222       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12223              diag::note_typecheck_assign_const)
12224           << ConstFunction << FD << FD->getReturnType()
12225           << FD->getReturnTypeSourceRange();
12226     }
12227   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12228     // Point to variable declaration.
12229     if (const ValueDecl *VD = DRE->getDecl()) {
12230       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12231         if (!DiagnosticEmitted) {
12232           S.Diag(Loc, diag::err_typecheck_assign_const)
12233               << ExprRange << ConstVariable << VD << VD->getType();
12234           DiagnosticEmitted = true;
12235         }
12236         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12237             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12238       }
12239     }
12240   } else if (isa<CXXThisExpr>(E)) {
12241     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12242       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12243         if (MD->isConst()) {
12244           if (!DiagnosticEmitted) {
12245             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12246                                                           << ConstMethod << MD;
12247             DiagnosticEmitted = true;
12248           }
12249           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12250               << ConstMethod << MD << MD->getSourceRange();
12251         }
12252       }
12253     }
12254   }
12255 
12256   if (DiagnosticEmitted)
12257     return;
12258 
12259   // Can't determine a more specific message, so display the generic error.
12260   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12261 }
12262 
12263 enum OriginalExprKind {
12264   OEK_Variable,
12265   OEK_Member,
12266   OEK_LValue
12267 };
12268 
12269 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12270                                          const RecordType *Ty,
12271                                          SourceLocation Loc, SourceRange Range,
12272                                          OriginalExprKind OEK,
12273                                          bool &DiagnosticEmitted) {
12274   std::vector<const RecordType *> RecordTypeList;
12275   RecordTypeList.push_back(Ty);
12276   unsigned NextToCheckIndex = 0;
12277   // We walk the record hierarchy breadth-first to ensure that we print
12278   // diagnostics in field nesting order.
12279   while (RecordTypeList.size() > NextToCheckIndex) {
12280     bool IsNested = NextToCheckIndex > 0;
12281     for (const FieldDecl *Field :
12282          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12283       // First, check every field for constness.
12284       QualType FieldTy = Field->getType();
12285       if (FieldTy.isConstQualified()) {
12286         if (!DiagnosticEmitted) {
12287           S.Diag(Loc, diag::err_typecheck_assign_const)
12288               << Range << NestedConstMember << OEK << VD
12289               << IsNested << Field;
12290           DiagnosticEmitted = true;
12291         }
12292         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12293             << NestedConstMember << IsNested << Field
12294             << FieldTy << Field->getSourceRange();
12295       }
12296 
12297       // Then we append it to the list to check next in order.
12298       FieldTy = FieldTy.getCanonicalType();
12299       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12300         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12301           RecordTypeList.push_back(FieldRecTy);
12302       }
12303     }
12304     ++NextToCheckIndex;
12305   }
12306 }
12307 
12308 /// Emit an error for the case where a record we are trying to assign to has a
12309 /// const-qualified field somewhere in its hierarchy.
12310 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12311                                          SourceLocation Loc) {
12312   QualType Ty = E->getType();
12313   assert(Ty->isRecordType() && "lvalue was not record?");
12314   SourceRange Range = E->getSourceRange();
12315   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12316   bool DiagEmitted = false;
12317 
12318   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12319     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12320             Range, OEK_Member, DiagEmitted);
12321   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12322     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12323             Range, OEK_Variable, DiagEmitted);
12324   else
12325     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12326             Range, OEK_LValue, DiagEmitted);
12327   if (!DiagEmitted)
12328     DiagnoseConstAssignment(S, E, Loc);
12329 }
12330 
12331 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12332 /// emit an error and return true.  If so, return false.
12333 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12334   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12335 
12336   S.CheckShadowingDeclModification(E, Loc);
12337 
12338   SourceLocation OrigLoc = Loc;
12339   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12340                                                               &Loc);
12341   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12342     IsLV = Expr::MLV_InvalidMessageExpression;
12343   if (IsLV == Expr::MLV_Valid)
12344     return false;
12345 
12346   unsigned DiagID = 0;
12347   bool NeedType = false;
12348   switch (IsLV) { // C99 6.5.16p2
12349   case Expr::MLV_ConstQualified:
12350     // Use a specialized diagnostic when we're assigning to an object
12351     // from an enclosing function or block.
12352     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12353       if (NCCK == NCCK_Block)
12354         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12355       else
12356         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12357       break;
12358     }
12359 
12360     // In ARC, use some specialized diagnostics for occasions where we
12361     // infer 'const'.  These are always pseudo-strong variables.
12362     if (S.getLangOpts().ObjCAutoRefCount) {
12363       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12364       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12365         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12366 
12367         // Use the normal diagnostic if it's pseudo-__strong but the
12368         // user actually wrote 'const'.
12369         if (var->isARCPseudoStrong() &&
12370             (!var->getTypeSourceInfo() ||
12371              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12372           // There are three pseudo-strong cases:
12373           //  - self
12374           ObjCMethodDecl *method = S.getCurMethodDecl();
12375           if (method && var == method->getSelfDecl()) {
12376             DiagID = method->isClassMethod()
12377               ? diag::err_typecheck_arc_assign_self_class_method
12378               : diag::err_typecheck_arc_assign_self;
12379 
12380           //  - Objective-C externally_retained attribute.
12381           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12382                      isa<ParmVarDecl>(var)) {
12383             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12384 
12385           //  - fast enumeration variables
12386           } else {
12387             DiagID = diag::err_typecheck_arr_assign_enumeration;
12388           }
12389 
12390           SourceRange Assign;
12391           if (Loc != OrigLoc)
12392             Assign = SourceRange(OrigLoc, OrigLoc);
12393           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12394           // We need to preserve the AST regardless, so migration tool
12395           // can do its job.
12396           return false;
12397         }
12398       }
12399     }
12400 
12401     // If none of the special cases above are triggered, then this is a
12402     // simple const assignment.
12403     if (DiagID == 0) {
12404       DiagnoseConstAssignment(S, E, Loc);
12405       return true;
12406     }
12407 
12408     break;
12409   case Expr::MLV_ConstAddrSpace:
12410     DiagnoseConstAssignment(S, E, Loc);
12411     return true;
12412   case Expr::MLV_ConstQualifiedField:
12413     DiagnoseRecursiveConstFields(S, E, Loc);
12414     return true;
12415   case Expr::MLV_ArrayType:
12416   case Expr::MLV_ArrayTemporary:
12417     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12418     NeedType = true;
12419     break;
12420   case Expr::MLV_NotObjectType:
12421     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12422     NeedType = true;
12423     break;
12424   case Expr::MLV_LValueCast:
12425     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12426     break;
12427   case Expr::MLV_Valid:
12428     llvm_unreachable("did not take early return for MLV_Valid");
12429   case Expr::MLV_InvalidExpression:
12430   case Expr::MLV_MemberFunction:
12431   case Expr::MLV_ClassTemporary:
12432     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12433     break;
12434   case Expr::MLV_IncompleteType:
12435   case Expr::MLV_IncompleteVoidType:
12436     return S.RequireCompleteType(Loc, E->getType(),
12437              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12438   case Expr::MLV_DuplicateVectorComponents:
12439     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12440     break;
12441   case Expr::MLV_NoSetterProperty:
12442     llvm_unreachable("readonly properties should be processed differently");
12443   case Expr::MLV_InvalidMessageExpression:
12444     DiagID = diag::err_readonly_message_assignment;
12445     break;
12446   case Expr::MLV_SubObjCPropertySetting:
12447     DiagID = diag::err_no_subobject_property_setting;
12448     break;
12449   }
12450 
12451   SourceRange Assign;
12452   if (Loc != OrigLoc)
12453     Assign = SourceRange(OrigLoc, OrigLoc);
12454   if (NeedType)
12455     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12456   else
12457     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12458   return true;
12459 }
12460 
12461 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12462                                          SourceLocation Loc,
12463                                          Sema &Sema) {
12464   if (Sema.inTemplateInstantiation())
12465     return;
12466   if (Sema.isUnevaluatedContext())
12467     return;
12468   if (Loc.isInvalid() || Loc.isMacroID())
12469     return;
12470   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12471     return;
12472 
12473   // C / C++ fields
12474   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12475   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12476   if (ML && MR) {
12477     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12478       return;
12479     const ValueDecl *LHSDecl =
12480         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12481     const ValueDecl *RHSDecl =
12482         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12483     if (LHSDecl != RHSDecl)
12484       return;
12485     if (LHSDecl->getType().isVolatileQualified())
12486       return;
12487     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12488       if (RefTy->getPointeeType().isVolatileQualified())
12489         return;
12490 
12491     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12492   }
12493 
12494   // Objective-C instance variables
12495   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12496   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12497   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12498     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12499     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12500     if (RL && RR && RL->getDecl() == RR->getDecl())
12501       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12502   }
12503 }
12504 
12505 // C99 6.5.16.1
12506 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12507                                        SourceLocation Loc,
12508                                        QualType CompoundType) {
12509   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12510 
12511   // Verify that LHS is a modifiable lvalue, and emit error if not.
12512   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12513     return QualType();
12514 
12515   QualType LHSType = LHSExpr->getType();
12516   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12517                                              CompoundType;
12518   // OpenCL v1.2 s6.1.1.1 p2:
12519   // The half data type can only be used to declare a pointer to a buffer that
12520   // contains half values
12521   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12522     LHSType->isHalfType()) {
12523     Diag(Loc, diag::err_opencl_half_load_store) << 1
12524         << LHSType.getUnqualifiedType();
12525     return QualType();
12526   }
12527 
12528   AssignConvertType ConvTy;
12529   if (CompoundType.isNull()) {
12530     Expr *RHSCheck = RHS.get();
12531 
12532     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12533 
12534     QualType LHSTy(LHSType);
12535     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12536     if (RHS.isInvalid())
12537       return QualType();
12538     // Special case of NSObject attributes on c-style pointer types.
12539     if (ConvTy == IncompatiblePointer &&
12540         ((Context.isObjCNSObjectType(LHSType) &&
12541           RHSType->isObjCObjectPointerType()) ||
12542          (Context.isObjCNSObjectType(RHSType) &&
12543           LHSType->isObjCObjectPointerType())))
12544       ConvTy = Compatible;
12545 
12546     if (ConvTy == Compatible &&
12547         LHSType->isObjCObjectType())
12548         Diag(Loc, diag::err_objc_object_assignment)
12549           << LHSType;
12550 
12551     // If the RHS is a unary plus or minus, check to see if they = and + are
12552     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12553     // instead of "x += 4".
12554     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12555       RHSCheck = ICE->getSubExpr();
12556     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12557       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12558           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12559           // Only if the two operators are exactly adjacent.
12560           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12561           // And there is a space or other character before the subexpr of the
12562           // unary +/-.  We don't want to warn on "x=-1".
12563           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12564           UO->getSubExpr()->getBeginLoc().isFileID()) {
12565         Diag(Loc, diag::warn_not_compound_assign)
12566           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12567           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12568       }
12569     }
12570 
12571     if (ConvTy == Compatible) {
12572       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12573         // Warn about retain cycles where a block captures the LHS, but
12574         // not if the LHS is a simple variable into which the block is
12575         // being stored...unless that variable can be captured by reference!
12576         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12577         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12578         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12579           checkRetainCycles(LHSExpr, RHS.get());
12580       }
12581 
12582       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12583           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12584         // It is safe to assign a weak reference into a strong variable.
12585         // Although this code can still have problems:
12586         //   id x = self.weakProp;
12587         //   id y = self.weakProp;
12588         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12589         // paths through the function. This should be revisited if
12590         // -Wrepeated-use-of-weak is made flow-sensitive.
12591         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12592         // variable, which will be valid for the current autorelease scope.
12593         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12594                              RHS.get()->getBeginLoc()))
12595           getCurFunction()->markSafeWeakUse(RHS.get());
12596 
12597       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12598         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12599       }
12600     }
12601   } else {
12602     // Compound assignment "x += y"
12603     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12604   }
12605 
12606   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12607                                RHS.get(), AA_Assigning))
12608     return QualType();
12609 
12610   CheckForNullPointerDereference(*this, LHSExpr);
12611 
12612   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12613     if (CompoundType.isNull()) {
12614       // C++2a [expr.ass]p5:
12615       //   A simple-assignment whose left operand is of a volatile-qualified
12616       //   type is deprecated unless the assignment is either a discarded-value
12617       //   expression or an unevaluated operand
12618       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12619     } else {
12620       // C++2a [expr.ass]p6:
12621       //   [Compound-assignment] expressions are deprecated if E1 has
12622       //   volatile-qualified type
12623       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12624     }
12625   }
12626 
12627   // C99 6.5.16p3: The type of an assignment expression is the type of the
12628   // left operand unless the left operand has qualified type, in which case
12629   // it is the unqualified version of the type of the left operand.
12630   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12631   // is converted to the type of the assignment expression (above).
12632   // C++ 5.17p1: the type of the assignment expression is that of its left
12633   // operand.
12634   return (getLangOpts().CPlusPlus
12635           ? LHSType : LHSType.getUnqualifiedType());
12636 }
12637 
12638 // Only ignore explicit casts to void.
12639 static bool IgnoreCommaOperand(const Expr *E) {
12640   E = E->IgnoreParens();
12641 
12642   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12643     if (CE->getCastKind() == CK_ToVoid) {
12644       return true;
12645     }
12646 
12647     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12648     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12649         CE->getSubExpr()->getType()->isDependentType()) {
12650       return true;
12651     }
12652   }
12653 
12654   return false;
12655 }
12656 
12657 // Look for instances where it is likely the comma operator is confused with
12658 // another operator.  There is a whitelist of acceptable expressions for the
12659 // left hand side of the comma operator, otherwise emit a warning.
12660 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12661   // No warnings in macros
12662   if (Loc.isMacroID())
12663     return;
12664 
12665   // Don't warn in template instantiations.
12666   if (inTemplateInstantiation())
12667     return;
12668 
12669   // Scope isn't fine-grained enough to whitelist the specific cases, so
12670   // instead, skip more than needed, then call back into here with the
12671   // CommaVisitor in SemaStmt.cpp.
12672   // The whitelisted locations are the initialization and increment portions
12673   // of a for loop.  The additional checks are on the condition of
12674   // if statements, do/while loops, and for loops.
12675   // Differences in scope flags for C89 mode requires the extra logic.
12676   const unsigned ForIncrementFlags =
12677       getLangOpts().C99 || getLangOpts().CPlusPlus
12678           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12679           : Scope::ContinueScope | Scope::BreakScope;
12680   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12681   const unsigned ScopeFlags = getCurScope()->getFlags();
12682   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12683       (ScopeFlags & ForInitFlags) == ForInitFlags)
12684     return;
12685 
12686   // If there are multiple comma operators used together, get the RHS of the
12687   // of the comma operator as the LHS.
12688   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12689     if (BO->getOpcode() != BO_Comma)
12690       break;
12691     LHS = BO->getRHS();
12692   }
12693 
12694   // Only allow some expressions on LHS to not warn.
12695   if (IgnoreCommaOperand(LHS))
12696     return;
12697 
12698   Diag(Loc, diag::warn_comma_operator);
12699   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12700       << LHS->getSourceRange()
12701       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12702                                     LangOpts.CPlusPlus ? "static_cast<void>("
12703                                                        : "(void)(")
12704       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12705                                     ")");
12706 }
12707 
12708 // C99 6.5.17
12709 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12710                                    SourceLocation Loc) {
12711   LHS = S.CheckPlaceholderExpr(LHS.get());
12712   RHS = S.CheckPlaceholderExpr(RHS.get());
12713   if (LHS.isInvalid() || RHS.isInvalid())
12714     return QualType();
12715 
12716   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12717   // operands, but not unary promotions.
12718   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12719 
12720   // So we treat the LHS as a ignored value, and in C++ we allow the
12721   // containing site to determine what should be done with the RHS.
12722   LHS = S.IgnoredValueConversions(LHS.get());
12723   if (LHS.isInvalid())
12724     return QualType();
12725 
12726   S.DiagnoseUnusedExprResult(LHS.get());
12727 
12728   if (!S.getLangOpts().CPlusPlus) {
12729     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12730     if (RHS.isInvalid())
12731       return QualType();
12732     if (!RHS.get()->getType()->isVoidType())
12733       S.RequireCompleteType(Loc, RHS.get()->getType(),
12734                             diag::err_incomplete_type);
12735   }
12736 
12737   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12738     S.DiagnoseCommaOperator(LHS.get(), Loc);
12739 
12740   return RHS.get()->getType();
12741 }
12742 
12743 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12744 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12745 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12746                                                ExprValueKind &VK,
12747                                                ExprObjectKind &OK,
12748                                                SourceLocation OpLoc,
12749                                                bool IsInc, bool IsPrefix) {
12750   if (Op->isTypeDependent())
12751     return S.Context.DependentTy;
12752 
12753   QualType ResType = Op->getType();
12754   // Atomic types can be used for increment / decrement where the non-atomic
12755   // versions can, so ignore the _Atomic() specifier for the purpose of
12756   // checking.
12757   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12758     ResType = ResAtomicType->getValueType();
12759 
12760   assert(!ResType.isNull() && "no type for increment/decrement expression");
12761 
12762   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12763     // Decrement of bool is not allowed.
12764     if (!IsInc) {
12765       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12766       return QualType();
12767     }
12768     // Increment of bool sets it to true, but is deprecated.
12769     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12770                                               : diag::warn_increment_bool)
12771       << Op->getSourceRange();
12772   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12773     // Error on enum increments and decrements in C++ mode
12774     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12775     return QualType();
12776   } else if (ResType->isRealType()) {
12777     // OK!
12778   } else if (ResType->isPointerType()) {
12779     // C99 6.5.2.4p2, 6.5.6p2
12780     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12781       return QualType();
12782   } else if (ResType->isObjCObjectPointerType()) {
12783     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12784     // Otherwise, we just need a complete type.
12785     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12786         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12787       return QualType();
12788   } else if (ResType->isAnyComplexType()) {
12789     // C99 does not support ++/-- on complex types, we allow as an extension.
12790     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12791       << ResType << Op->getSourceRange();
12792   } else if (ResType->isPlaceholderType()) {
12793     ExprResult PR = S.CheckPlaceholderExpr(Op);
12794     if (PR.isInvalid()) return QualType();
12795     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12796                                           IsInc, IsPrefix);
12797   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12798     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12799   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12800              (ResType->castAs<VectorType>()->getVectorKind() !=
12801               VectorType::AltiVecBool)) {
12802     // The z vector extensions allow ++ and -- for non-bool vectors.
12803   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12804             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12805     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12806   } else {
12807     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12808       << ResType << int(IsInc) << Op->getSourceRange();
12809     return QualType();
12810   }
12811   // At this point, we know we have a real, complex or pointer type.
12812   // Now make sure the operand is a modifiable lvalue.
12813   if (CheckForModifiableLvalue(Op, OpLoc, S))
12814     return QualType();
12815   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
12816     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12817     //   An operand with volatile-qualified type is deprecated
12818     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12819         << IsInc << ResType;
12820   }
12821   // In C++, a prefix increment is the same type as the operand. Otherwise
12822   // (in C or with postfix), the increment is the unqualified type of the
12823   // operand.
12824   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12825     VK = VK_LValue;
12826     OK = Op->getObjectKind();
12827     return ResType;
12828   } else {
12829     VK = VK_RValue;
12830     return ResType.getUnqualifiedType();
12831   }
12832 }
12833 
12834 
12835 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12836 /// This routine allows us to typecheck complex/recursive expressions
12837 /// where the declaration is needed for type checking. We only need to
12838 /// handle cases when the expression references a function designator
12839 /// or is an lvalue. Here are some examples:
12840 ///  - &(x) => x
12841 ///  - &*****f => f for f a function designator.
12842 ///  - &s.xx => s
12843 ///  - &s.zz[1].yy -> s, if zz is an array
12844 ///  - *(x + 1) -> x, if x is an array
12845 ///  - &"123"[2] -> 0
12846 ///  - & __real__ x -> x
12847 ///
12848 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
12849 /// members.
12850 static ValueDecl *getPrimaryDecl(Expr *E) {
12851   switch (E->getStmtClass()) {
12852   case Stmt::DeclRefExprClass:
12853     return cast<DeclRefExpr>(E)->getDecl();
12854   case Stmt::MemberExprClass:
12855     // If this is an arrow operator, the address is an offset from
12856     // the base's value, so the object the base refers to is
12857     // irrelevant.
12858     if (cast<MemberExpr>(E)->isArrow())
12859       return nullptr;
12860     // Otherwise, the expression refers to a part of the base
12861     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12862   case Stmt::ArraySubscriptExprClass: {
12863     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12864     // promotion of register arrays earlier.
12865     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12866     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12867       if (ICE->getSubExpr()->getType()->isArrayType())
12868         return getPrimaryDecl(ICE->getSubExpr());
12869     }
12870     return nullptr;
12871   }
12872   case Stmt::UnaryOperatorClass: {
12873     UnaryOperator *UO = cast<UnaryOperator>(E);
12874 
12875     switch(UO->getOpcode()) {
12876     case UO_Real:
12877     case UO_Imag:
12878     case UO_Extension:
12879       return getPrimaryDecl(UO->getSubExpr());
12880     default:
12881       return nullptr;
12882     }
12883   }
12884   case Stmt::ParenExprClass:
12885     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12886   case Stmt::ImplicitCastExprClass:
12887     // If the result of an implicit cast is an l-value, we care about
12888     // the sub-expression; otherwise, the result here doesn't matter.
12889     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12890   case Stmt::CXXUuidofExprClass:
12891     return cast<CXXUuidofExpr>(E)->getGuidDecl();
12892   default:
12893     return nullptr;
12894   }
12895 }
12896 
12897 namespace {
12898   enum {
12899     AO_Bit_Field = 0,
12900     AO_Vector_Element = 1,
12901     AO_Property_Expansion = 2,
12902     AO_Register_Variable = 3,
12903     AO_No_Error = 4
12904   };
12905 }
12906 /// Diagnose invalid operand for address of operations.
12907 ///
12908 /// \param Type The type of operand which cannot have its address taken.
12909 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12910                                          Expr *E, unsigned Type) {
12911   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12912 }
12913 
12914 /// CheckAddressOfOperand - The operand of & must be either a function
12915 /// designator or an lvalue designating an object. If it is an lvalue, the
12916 /// object cannot be declared with storage class register or be a bit field.
12917 /// Note: The usual conversions are *not* applied to the operand of the &
12918 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12919 /// In C++, the operand might be an overloaded function name, in which case
12920 /// we allow the '&' but retain the overloaded-function type.
12921 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12922   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12923     if (PTy->getKind() == BuiltinType::Overload) {
12924       Expr *E = OrigOp.get()->IgnoreParens();
12925       if (!isa<OverloadExpr>(E)) {
12926         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12927         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12928           << OrigOp.get()->getSourceRange();
12929         return QualType();
12930       }
12931 
12932       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12933       if (isa<UnresolvedMemberExpr>(Ovl))
12934         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12935           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12936             << OrigOp.get()->getSourceRange();
12937           return QualType();
12938         }
12939 
12940       return Context.OverloadTy;
12941     }
12942 
12943     if (PTy->getKind() == BuiltinType::UnknownAny)
12944       return Context.UnknownAnyTy;
12945 
12946     if (PTy->getKind() == BuiltinType::BoundMember) {
12947       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12948         << OrigOp.get()->getSourceRange();
12949       return QualType();
12950     }
12951 
12952     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12953     if (OrigOp.isInvalid()) return QualType();
12954   }
12955 
12956   if (OrigOp.get()->isTypeDependent())
12957     return Context.DependentTy;
12958 
12959   assert(!OrigOp.get()->getType()->isPlaceholderType());
12960 
12961   // Make sure to ignore parentheses in subsequent checks
12962   Expr *op = OrigOp.get()->IgnoreParens();
12963 
12964   // In OpenCL captures for blocks called as lambda functions
12965   // are located in the private address space. Blocks used in
12966   // enqueue_kernel can be located in a different address space
12967   // depending on a vendor implementation. Thus preventing
12968   // taking an address of the capture to avoid invalid AS casts.
12969   if (LangOpts.OpenCL) {
12970     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12971     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12972       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12973       return QualType();
12974     }
12975   }
12976 
12977   if (getLangOpts().C99) {
12978     // Implement C99-only parts of addressof rules.
12979     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12980       if (uOp->getOpcode() == UO_Deref)
12981         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12982         // (assuming the deref expression is valid).
12983         return uOp->getSubExpr()->getType();
12984     }
12985     // Technically, there should be a check for array subscript
12986     // expressions here, but the result of one is always an lvalue anyway.
12987   }
12988   ValueDecl *dcl = getPrimaryDecl(op);
12989 
12990   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12991     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12992                                            op->getBeginLoc()))
12993       return QualType();
12994 
12995   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12996   unsigned AddressOfError = AO_No_Error;
12997 
12998   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12999     bool sfinae = (bool)isSFINAEContext();
13000     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13001                                   : diag::ext_typecheck_addrof_temporary)
13002       << op->getType() << op->getSourceRange();
13003     if (sfinae)
13004       return QualType();
13005     // Materialize the temporary as an lvalue so that we can take its address.
13006     OrigOp = op =
13007         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13008   } else if (isa<ObjCSelectorExpr>(op)) {
13009     return Context.getPointerType(op->getType());
13010   } else if (lval == Expr::LV_MemberFunction) {
13011     // If it's an instance method, make a member pointer.
13012     // The expression must have exactly the form &A::foo.
13013 
13014     // If the underlying expression isn't a decl ref, give up.
13015     if (!isa<DeclRefExpr>(op)) {
13016       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13017         << OrigOp.get()->getSourceRange();
13018       return QualType();
13019     }
13020     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13021     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13022 
13023     // The id-expression was parenthesized.
13024     if (OrigOp.get() != DRE) {
13025       Diag(OpLoc, diag::err_parens_pointer_member_function)
13026         << OrigOp.get()->getSourceRange();
13027 
13028     // The method was named without a qualifier.
13029     } else if (!DRE->getQualifier()) {
13030       if (MD->getParent()->getName().empty())
13031         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13032           << op->getSourceRange();
13033       else {
13034         SmallString<32> Str;
13035         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13036         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13037           << op->getSourceRange()
13038           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13039       }
13040     }
13041 
13042     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13043     if (isa<CXXDestructorDecl>(MD))
13044       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13045 
13046     QualType MPTy = Context.getMemberPointerType(
13047         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13048     // Under the MS ABI, lock down the inheritance model now.
13049     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13050       (void)isCompleteType(OpLoc, MPTy);
13051     return MPTy;
13052   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13053     // C99 6.5.3.2p1
13054     // The operand must be either an l-value or a function designator
13055     if (!op->getType()->isFunctionType()) {
13056       // Use a special diagnostic for loads from property references.
13057       if (isa<PseudoObjectExpr>(op)) {
13058         AddressOfError = AO_Property_Expansion;
13059       } else {
13060         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13061           << op->getType() << op->getSourceRange();
13062         return QualType();
13063       }
13064     }
13065   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13066     // The operand cannot be a bit-field
13067     AddressOfError = AO_Bit_Field;
13068   } else if (op->getObjectKind() == OK_VectorComponent) {
13069     // The operand cannot be an element of a vector
13070     AddressOfError = AO_Vector_Element;
13071   } else if (dcl) { // C99 6.5.3.2p1
13072     // We have an lvalue with a decl. Make sure the decl is not declared
13073     // with the register storage-class specifier.
13074     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13075       // in C++ it is not error to take address of a register
13076       // variable (c++03 7.1.1P3)
13077       if (vd->getStorageClass() == SC_Register &&
13078           !getLangOpts().CPlusPlus) {
13079         AddressOfError = AO_Register_Variable;
13080       }
13081     } else if (isa<MSPropertyDecl>(dcl)) {
13082       AddressOfError = AO_Property_Expansion;
13083     } else if (isa<FunctionTemplateDecl>(dcl)) {
13084       return Context.OverloadTy;
13085     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13086       // Okay: we can take the address of a field.
13087       // Could be a pointer to member, though, if there is an explicit
13088       // scope qualifier for the class.
13089       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13090         DeclContext *Ctx = dcl->getDeclContext();
13091         if (Ctx && Ctx->isRecord()) {
13092           if (dcl->getType()->isReferenceType()) {
13093             Diag(OpLoc,
13094                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13095               << dcl->getDeclName() << dcl->getType();
13096             return QualType();
13097           }
13098 
13099           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13100             Ctx = Ctx->getParent();
13101 
13102           QualType MPTy = Context.getMemberPointerType(
13103               op->getType(),
13104               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13105           // Under the MS ABI, lock down the inheritance model now.
13106           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13107             (void)isCompleteType(OpLoc, MPTy);
13108           return MPTy;
13109         }
13110       }
13111     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13112                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13113       llvm_unreachable("Unknown/unexpected decl type");
13114   }
13115 
13116   if (AddressOfError != AO_No_Error) {
13117     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13118     return QualType();
13119   }
13120 
13121   if (lval == Expr::LV_IncompleteVoidType) {
13122     // Taking the address of a void variable is technically illegal, but we
13123     // allow it in cases which are otherwise valid.
13124     // Example: "extern void x; void* y = &x;".
13125     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13126   }
13127 
13128   // If the operand has type "type", the result has type "pointer to type".
13129   if (op->getType()->isObjCObjectType())
13130     return Context.getObjCObjectPointerType(op->getType());
13131 
13132   CheckAddressOfPackedMember(op);
13133 
13134   return Context.getPointerType(op->getType());
13135 }
13136 
13137 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13138   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13139   if (!DRE)
13140     return;
13141   const Decl *D = DRE->getDecl();
13142   if (!D)
13143     return;
13144   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13145   if (!Param)
13146     return;
13147   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13148     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13149       return;
13150   if (FunctionScopeInfo *FD = S.getCurFunction())
13151     if (!FD->ModifiedNonNullParams.count(Param))
13152       FD->ModifiedNonNullParams.insert(Param);
13153 }
13154 
13155 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13156 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13157                                         SourceLocation OpLoc) {
13158   if (Op->isTypeDependent())
13159     return S.Context.DependentTy;
13160 
13161   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13162   if (ConvResult.isInvalid())
13163     return QualType();
13164   Op = ConvResult.get();
13165   QualType OpTy = Op->getType();
13166   QualType Result;
13167 
13168   if (isa<CXXReinterpretCastExpr>(Op)) {
13169     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13170     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13171                                      Op->getSourceRange());
13172   }
13173 
13174   if (const PointerType *PT = OpTy->getAs<PointerType>())
13175   {
13176     Result = PT->getPointeeType();
13177   }
13178   else if (const ObjCObjectPointerType *OPT =
13179              OpTy->getAs<ObjCObjectPointerType>())
13180     Result = OPT->getPointeeType();
13181   else {
13182     ExprResult PR = S.CheckPlaceholderExpr(Op);
13183     if (PR.isInvalid()) return QualType();
13184     if (PR.get() != Op)
13185       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13186   }
13187 
13188   if (Result.isNull()) {
13189     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13190       << OpTy << Op->getSourceRange();
13191     return QualType();
13192   }
13193 
13194   // Note that per both C89 and C99, indirection is always legal, even if Result
13195   // is an incomplete type or void.  It would be possible to warn about
13196   // dereferencing a void pointer, but it's completely well-defined, and such a
13197   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13198   // for pointers to 'void' but is fine for any other pointer type:
13199   //
13200   // C++ [expr.unary.op]p1:
13201   //   [...] the expression to which [the unary * operator] is applied shall
13202   //   be a pointer to an object type, or a pointer to a function type
13203   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13204     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13205       << OpTy << Op->getSourceRange();
13206 
13207   // Dereferences are usually l-values...
13208   VK = VK_LValue;
13209 
13210   // ...except that certain expressions are never l-values in C.
13211   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13212     VK = VK_RValue;
13213 
13214   return Result;
13215 }
13216 
13217 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13218   BinaryOperatorKind Opc;
13219   switch (Kind) {
13220   default: llvm_unreachable("Unknown binop!");
13221   case tok::periodstar:           Opc = BO_PtrMemD; break;
13222   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13223   case tok::star:                 Opc = BO_Mul; break;
13224   case tok::slash:                Opc = BO_Div; break;
13225   case tok::percent:              Opc = BO_Rem; break;
13226   case tok::plus:                 Opc = BO_Add; break;
13227   case tok::minus:                Opc = BO_Sub; break;
13228   case tok::lessless:             Opc = BO_Shl; break;
13229   case tok::greatergreater:       Opc = BO_Shr; break;
13230   case tok::lessequal:            Opc = BO_LE; break;
13231   case tok::less:                 Opc = BO_LT; break;
13232   case tok::greaterequal:         Opc = BO_GE; break;
13233   case tok::greater:              Opc = BO_GT; break;
13234   case tok::exclaimequal:         Opc = BO_NE; break;
13235   case tok::equalequal:           Opc = BO_EQ; break;
13236   case tok::spaceship:            Opc = BO_Cmp; break;
13237   case tok::amp:                  Opc = BO_And; break;
13238   case tok::caret:                Opc = BO_Xor; break;
13239   case tok::pipe:                 Opc = BO_Or; break;
13240   case tok::ampamp:               Opc = BO_LAnd; break;
13241   case tok::pipepipe:             Opc = BO_LOr; break;
13242   case tok::equal:                Opc = BO_Assign; break;
13243   case tok::starequal:            Opc = BO_MulAssign; break;
13244   case tok::slashequal:           Opc = BO_DivAssign; break;
13245   case tok::percentequal:         Opc = BO_RemAssign; break;
13246   case tok::plusequal:            Opc = BO_AddAssign; break;
13247   case tok::minusequal:           Opc = BO_SubAssign; break;
13248   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13249   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13250   case tok::ampequal:             Opc = BO_AndAssign; break;
13251   case tok::caretequal:           Opc = BO_XorAssign; break;
13252   case tok::pipeequal:            Opc = BO_OrAssign; break;
13253   case tok::comma:                Opc = BO_Comma; break;
13254   }
13255   return Opc;
13256 }
13257 
13258 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13259   tok::TokenKind Kind) {
13260   UnaryOperatorKind Opc;
13261   switch (Kind) {
13262   default: llvm_unreachable("Unknown unary op!");
13263   case tok::plusplus:     Opc = UO_PreInc; break;
13264   case tok::minusminus:   Opc = UO_PreDec; break;
13265   case tok::amp:          Opc = UO_AddrOf; break;
13266   case tok::star:         Opc = UO_Deref; break;
13267   case tok::plus:         Opc = UO_Plus; break;
13268   case tok::minus:        Opc = UO_Minus; break;
13269   case tok::tilde:        Opc = UO_Not; break;
13270   case tok::exclaim:      Opc = UO_LNot; break;
13271   case tok::kw___real:    Opc = UO_Real; break;
13272   case tok::kw___imag:    Opc = UO_Imag; break;
13273   case tok::kw___extension__: Opc = UO_Extension; break;
13274   }
13275   return Opc;
13276 }
13277 
13278 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13279 /// This warning suppressed in the event of macro expansions.
13280 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13281                                    SourceLocation OpLoc, bool IsBuiltin) {
13282   if (S.inTemplateInstantiation())
13283     return;
13284   if (S.isUnevaluatedContext())
13285     return;
13286   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13287     return;
13288   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13289   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13290   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13291   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13292   if (!LHSDeclRef || !RHSDeclRef ||
13293       LHSDeclRef->getLocation().isMacroID() ||
13294       RHSDeclRef->getLocation().isMacroID())
13295     return;
13296   const ValueDecl *LHSDecl =
13297     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13298   const ValueDecl *RHSDecl =
13299     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13300   if (LHSDecl != RHSDecl)
13301     return;
13302   if (LHSDecl->getType().isVolatileQualified())
13303     return;
13304   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13305     if (RefTy->getPointeeType().isVolatileQualified())
13306       return;
13307 
13308   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13309                           : diag::warn_self_assignment_overloaded)
13310       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13311       << RHSExpr->getSourceRange();
13312 }
13313 
13314 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13315 /// is usually indicative of introspection within the Objective-C pointer.
13316 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13317                                           SourceLocation OpLoc) {
13318   if (!S.getLangOpts().ObjC)
13319     return;
13320 
13321   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13322   const Expr *LHS = L.get();
13323   const Expr *RHS = R.get();
13324 
13325   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13326     ObjCPointerExpr = LHS;
13327     OtherExpr = RHS;
13328   }
13329   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13330     ObjCPointerExpr = RHS;
13331     OtherExpr = LHS;
13332   }
13333 
13334   // This warning is deliberately made very specific to reduce false
13335   // positives with logic that uses '&' for hashing.  This logic mainly
13336   // looks for code trying to introspect into tagged pointers, which
13337   // code should generally never do.
13338   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13339     unsigned Diag = diag::warn_objc_pointer_masking;
13340     // Determine if we are introspecting the result of performSelectorXXX.
13341     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13342     // Special case messages to -performSelector and friends, which
13343     // can return non-pointer values boxed in a pointer value.
13344     // Some clients may wish to silence warnings in this subcase.
13345     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13346       Selector S = ME->getSelector();
13347       StringRef SelArg0 = S.getNameForSlot(0);
13348       if (SelArg0.startswith("performSelector"))
13349         Diag = diag::warn_objc_pointer_masking_performSelector;
13350     }
13351 
13352     S.Diag(OpLoc, Diag)
13353       << ObjCPointerExpr->getSourceRange();
13354   }
13355 }
13356 
13357 static NamedDecl *getDeclFromExpr(Expr *E) {
13358   if (!E)
13359     return nullptr;
13360   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13361     return DRE->getDecl();
13362   if (auto *ME = dyn_cast<MemberExpr>(E))
13363     return ME->getMemberDecl();
13364   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13365     return IRE->getDecl();
13366   return nullptr;
13367 }
13368 
13369 // This helper function promotes a binary operator's operands (which are of a
13370 // half vector type) to a vector of floats and then truncates the result to
13371 // a vector of either half or short.
13372 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13373                                       BinaryOperatorKind Opc, QualType ResultTy,
13374                                       ExprValueKind VK, ExprObjectKind OK,
13375                                       bool IsCompAssign, SourceLocation OpLoc,
13376                                       FPOptions FPFeatures) {
13377   auto &Context = S.getASTContext();
13378   assert((isVector(ResultTy, Context.HalfTy) ||
13379           isVector(ResultTy, Context.ShortTy)) &&
13380          "Result must be a vector of half or short");
13381   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13382          isVector(RHS.get()->getType(), Context.HalfTy) &&
13383          "both operands expected to be a half vector");
13384 
13385   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13386   QualType BinOpResTy = RHS.get()->getType();
13387 
13388   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13389   // change BinOpResTy to a vector of ints.
13390   if (isVector(ResultTy, Context.ShortTy))
13391     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13392 
13393   if (IsCompAssign)
13394     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13395                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13396                                           BinOpResTy, BinOpResTy);
13397 
13398   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13399   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13400                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13401   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13402 }
13403 
13404 static std::pair<ExprResult, ExprResult>
13405 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13406                            Expr *RHSExpr) {
13407   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13408   if (!S.getLangOpts().CPlusPlus) {
13409     // C cannot handle TypoExpr nodes on either side of a binop because it
13410     // doesn't handle dependent types properly, so make sure any TypoExprs have
13411     // been dealt with before checking the operands.
13412     LHS = S.CorrectDelayedTyposInExpr(LHS);
13413     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
13414       if (Opc != BO_Assign)
13415         return ExprResult(E);
13416       // Avoid correcting the RHS to the same Expr as the LHS.
13417       Decl *D = getDeclFromExpr(E);
13418       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13419     });
13420   }
13421   return std::make_pair(LHS, RHS);
13422 }
13423 
13424 /// Returns true if conversion between vectors of halfs and vectors of floats
13425 /// is needed.
13426 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13427                                      Expr *E0, Expr *E1 = nullptr) {
13428   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13429       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13430     return false;
13431 
13432   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13433     QualType Ty = E->IgnoreImplicit()->getType();
13434 
13435     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13436     // to vectors of floats. Although the element type of the vectors is __fp16,
13437     // the vectors shouldn't be treated as storage-only types. See the
13438     // discussion here: https://reviews.llvm.org/rG825235c140e7
13439     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13440       if (VT->getVectorKind() == VectorType::NeonVector)
13441         return false;
13442       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13443     }
13444     return false;
13445   };
13446 
13447   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13448 }
13449 
13450 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13451 /// operator @p Opc at location @c TokLoc. This routine only supports
13452 /// built-in operations; ActOnBinOp handles overloaded operators.
13453 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13454                                     BinaryOperatorKind Opc,
13455                                     Expr *LHSExpr, Expr *RHSExpr) {
13456   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13457     // The syntax only allows initializer lists on the RHS of assignment,
13458     // so we don't need to worry about accepting invalid code for
13459     // non-assignment operators.
13460     // C++11 5.17p9:
13461     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13462     //   of x = {} is x = T().
13463     InitializationKind Kind = InitializationKind::CreateDirectList(
13464         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13465     InitializedEntity Entity =
13466         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13467     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13468     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13469     if (Init.isInvalid())
13470       return Init;
13471     RHSExpr = Init.get();
13472   }
13473 
13474   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13475   QualType ResultTy;     // Result type of the binary operator.
13476   // The following two variables are used for compound assignment operators
13477   QualType CompLHSTy;    // Type of LHS after promotions for computation
13478   QualType CompResultTy; // Type of computation result
13479   ExprValueKind VK = VK_RValue;
13480   ExprObjectKind OK = OK_Ordinary;
13481   bool ConvertHalfVec = false;
13482 
13483   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13484   if (!LHS.isUsable() || !RHS.isUsable())
13485     return ExprError();
13486 
13487   if (getLangOpts().OpenCL) {
13488     QualType LHSTy = LHSExpr->getType();
13489     QualType RHSTy = RHSExpr->getType();
13490     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13491     // the ATOMIC_VAR_INIT macro.
13492     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13493       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13494       if (BO_Assign == Opc)
13495         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13496       else
13497         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13498       return ExprError();
13499     }
13500 
13501     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13502     // only with a builtin functions and therefore should be disallowed here.
13503     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13504         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13505         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13506         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13507       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13508       return ExprError();
13509     }
13510   }
13511 
13512   // Diagnose operations on the unsupported types for OpenMP device compilation.
13513   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13514     if (Opc != BO_Assign && Opc != BO_Comma) {
13515       checkOpenMPDeviceExpr(LHSExpr);
13516       checkOpenMPDeviceExpr(RHSExpr);
13517     }
13518   }
13519 
13520   switch (Opc) {
13521   case BO_Assign:
13522     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13523     if (getLangOpts().CPlusPlus &&
13524         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13525       VK = LHS.get()->getValueKind();
13526       OK = LHS.get()->getObjectKind();
13527     }
13528     if (!ResultTy.isNull()) {
13529       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13530       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13531 
13532       // Avoid copying a block to the heap if the block is assigned to a local
13533       // auto variable that is declared in the same scope as the block. This
13534       // optimization is unsafe if the local variable is declared in an outer
13535       // scope. For example:
13536       //
13537       // BlockTy b;
13538       // {
13539       //   b = ^{...};
13540       // }
13541       // // It is unsafe to invoke the block here if it wasn't copied to the
13542       // // heap.
13543       // b();
13544 
13545       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13546         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13547           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13548             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13549               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13550 
13551       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13552         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13553                               NTCUC_Assignment, NTCUK_Copy);
13554     }
13555     RecordModifiableNonNullParam(*this, LHS.get());
13556     break;
13557   case BO_PtrMemD:
13558   case BO_PtrMemI:
13559     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13560                                             Opc == BO_PtrMemI);
13561     break;
13562   case BO_Mul:
13563   case BO_Div:
13564     ConvertHalfVec = true;
13565     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13566                                            Opc == BO_Div);
13567     break;
13568   case BO_Rem:
13569     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13570     break;
13571   case BO_Add:
13572     ConvertHalfVec = true;
13573     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13574     break;
13575   case BO_Sub:
13576     ConvertHalfVec = true;
13577     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13578     break;
13579   case BO_Shl:
13580   case BO_Shr:
13581     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13582     break;
13583   case BO_LE:
13584   case BO_LT:
13585   case BO_GE:
13586   case BO_GT:
13587     ConvertHalfVec = true;
13588     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13589     break;
13590   case BO_EQ:
13591   case BO_NE:
13592     ConvertHalfVec = true;
13593     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13594     break;
13595   case BO_Cmp:
13596     ConvertHalfVec = true;
13597     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13598     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13599     break;
13600   case BO_And:
13601     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13602     LLVM_FALLTHROUGH;
13603   case BO_Xor:
13604   case BO_Or:
13605     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13606     break;
13607   case BO_LAnd:
13608   case BO_LOr:
13609     ConvertHalfVec = true;
13610     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13611     break;
13612   case BO_MulAssign:
13613   case BO_DivAssign:
13614     ConvertHalfVec = true;
13615     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13616                                                Opc == BO_DivAssign);
13617     CompLHSTy = CompResultTy;
13618     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13619       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13620     break;
13621   case BO_RemAssign:
13622     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13623     CompLHSTy = CompResultTy;
13624     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13625       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13626     break;
13627   case BO_AddAssign:
13628     ConvertHalfVec = true;
13629     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13630     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13631       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13632     break;
13633   case BO_SubAssign:
13634     ConvertHalfVec = true;
13635     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13636     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13637       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13638     break;
13639   case BO_ShlAssign:
13640   case BO_ShrAssign:
13641     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13642     CompLHSTy = CompResultTy;
13643     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13644       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13645     break;
13646   case BO_AndAssign:
13647   case BO_OrAssign: // fallthrough
13648     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13649     LLVM_FALLTHROUGH;
13650   case BO_XorAssign:
13651     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13652     CompLHSTy = CompResultTy;
13653     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13654       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13655     break;
13656   case BO_Comma:
13657     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13658     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13659       VK = RHS.get()->getValueKind();
13660       OK = RHS.get()->getObjectKind();
13661     }
13662     break;
13663   }
13664   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13665     return ExprError();
13666 
13667   // Some of the binary operations require promoting operands of half vector to
13668   // float vectors and truncating the result back to half vector. For now, we do
13669   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13670   // arm64).
13671   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13672          isVector(LHS.get()->getType(), Context.HalfTy) &&
13673          "both sides are half vectors or neither sides are");
13674   ConvertHalfVec =
13675       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13676 
13677   // Check for array bounds violations for both sides of the BinaryOperator
13678   CheckArrayAccess(LHS.get());
13679   CheckArrayAccess(RHS.get());
13680 
13681   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13682     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13683                                                  &Context.Idents.get("object_setClass"),
13684                                                  SourceLocation(), LookupOrdinaryName);
13685     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13686       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13687       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13688           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13689                                         "object_setClass(")
13690           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13691                                           ",")
13692           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13693     }
13694     else
13695       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13696   }
13697   else if (const ObjCIvarRefExpr *OIRE =
13698            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13699     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13700 
13701   // Opc is not a compound assignment if CompResultTy is null.
13702   if (CompResultTy.isNull()) {
13703     if (ConvertHalfVec)
13704       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13705                                  OpLoc, CurFPFeatures);
13706     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13707                                   VK, OK, OpLoc, CurFPFeatures);
13708   }
13709 
13710   // Handle compound assignments.
13711   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13712       OK_ObjCProperty) {
13713     VK = VK_LValue;
13714     OK = LHS.get()->getObjectKind();
13715   }
13716 
13717   // The LHS is not converted to the result type for fixed-point compound
13718   // assignment as the common type is computed on demand. Reset the CompLHSTy
13719   // to the LHS type we would have gotten after unary conversions.
13720   if (CompResultTy->isFixedPointType())
13721     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13722 
13723   if (ConvertHalfVec)
13724     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13725                                OpLoc, CurFPFeatures);
13726 
13727   return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13728                                         ResultTy, VK, OK, OpLoc, CurFPFeatures,
13729                                         CompLHSTy, CompResultTy);
13730 }
13731 
13732 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13733 /// operators are mixed in a way that suggests that the programmer forgot that
13734 /// comparison operators have higher precedence. The most typical example of
13735 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13736 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13737                                       SourceLocation OpLoc, Expr *LHSExpr,
13738                                       Expr *RHSExpr) {
13739   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13740   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13741 
13742   // Check that one of the sides is a comparison operator and the other isn't.
13743   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13744   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13745   if (isLeftComp == isRightComp)
13746     return;
13747 
13748   // Bitwise operations are sometimes used as eager logical ops.
13749   // Don't diagnose this.
13750   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13751   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13752   if (isLeftBitwise || isRightBitwise)
13753     return;
13754 
13755   SourceRange DiagRange = isLeftComp
13756                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13757                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13758   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13759   SourceRange ParensRange =
13760       isLeftComp
13761           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13762           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13763 
13764   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13765     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13766   SuggestParentheses(Self, OpLoc,
13767     Self.PDiag(diag::note_precedence_silence) << OpStr,
13768     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13769   SuggestParentheses(Self, OpLoc,
13770     Self.PDiag(diag::note_precedence_bitwise_first)
13771       << BinaryOperator::getOpcodeStr(Opc),
13772     ParensRange);
13773 }
13774 
13775 /// It accepts a '&&' expr that is inside a '||' one.
13776 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13777 /// in parentheses.
13778 static void
13779 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13780                                        BinaryOperator *Bop) {
13781   assert(Bop->getOpcode() == BO_LAnd);
13782   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13783       << Bop->getSourceRange() << OpLoc;
13784   SuggestParentheses(Self, Bop->getOperatorLoc(),
13785     Self.PDiag(diag::note_precedence_silence)
13786       << Bop->getOpcodeStr(),
13787     Bop->getSourceRange());
13788 }
13789 
13790 /// Returns true if the given expression can be evaluated as a constant
13791 /// 'true'.
13792 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13793   bool Res;
13794   return !E->isValueDependent() &&
13795          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13796 }
13797 
13798 /// Returns true if the given expression can be evaluated as a constant
13799 /// 'false'.
13800 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13801   bool Res;
13802   return !E->isValueDependent() &&
13803          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13804 }
13805 
13806 /// Look for '&&' in the left hand of a '||' expr.
13807 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13808                                              Expr *LHSExpr, Expr *RHSExpr) {
13809   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13810     if (Bop->getOpcode() == BO_LAnd) {
13811       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13812       if (EvaluatesAsFalse(S, RHSExpr))
13813         return;
13814       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13815       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13816         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13817     } else if (Bop->getOpcode() == BO_LOr) {
13818       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13819         // If it's "a || b && 1 || c" we didn't warn earlier for
13820         // "a || b && 1", but warn now.
13821         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13822           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13823       }
13824     }
13825   }
13826 }
13827 
13828 /// Look for '&&' in the right hand of a '||' expr.
13829 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13830                                              Expr *LHSExpr, Expr *RHSExpr) {
13831   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13832     if (Bop->getOpcode() == BO_LAnd) {
13833       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13834       if (EvaluatesAsFalse(S, LHSExpr))
13835         return;
13836       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13837       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13838         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13839     }
13840   }
13841 }
13842 
13843 /// Look for bitwise op in the left or right hand of a bitwise op with
13844 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13845 /// the '&' expression in parentheses.
13846 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13847                                          SourceLocation OpLoc, Expr *SubExpr) {
13848   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13849     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13850       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13851         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13852         << Bop->getSourceRange() << OpLoc;
13853       SuggestParentheses(S, Bop->getOperatorLoc(),
13854         S.PDiag(diag::note_precedence_silence)
13855           << Bop->getOpcodeStr(),
13856         Bop->getSourceRange());
13857     }
13858   }
13859 }
13860 
13861 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13862                                     Expr *SubExpr, StringRef Shift) {
13863   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13864     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13865       StringRef Op = Bop->getOpcodeStr();
13866       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13867           << Bop->getSourceRange() << OpLoc << Shift << Op;
13868       SuggestParentheses(S, Bop->getOperatorLoc(),
13869           S.PDiag(diag::note_precedence_silence) << Op,
13870           Bop->getSourceRange());
13871     }
13872   }
13873 }
13874 
13875 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13876                                  Expr *LHSExpr, Expr *RHSExpr) {
13877   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13878   if (!OCE)
13879     return;
13880 
13881   FunctionDecl *FD = OCE->getDirectCallee();
13882   if (!FD || !FD->isOverloadedOperator())
13883     return;
13884 
13885   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13886   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13887     return;
13888 
13889   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13890       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13891       << (Kind == OO_LessLess);
13892   SuggestParentheses(S, OCE->getOperatorLoc(),
13893                      S.PDiag(diag::note_precedence_silence)
13894                          << (Kind == OO_LessLess ? "<<" : ">>"),
13895                      OCE->getSourceRange());
13896   SuggestParentheses(
13897       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13898       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13899 }
13900 
13901 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13902 /// precedence.
13903 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13904                                     SourceLocation OpLoc, Expr *LHSExpr,
13905                                     Expr *RHSExpr){
13906   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13907   if (BinaryOperator::isBitwiseOp(Opc))
13908     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13909 
13910   // Diagnose "arg1 & arg2 | arg3"
13911   if ((Opc == BO_Or || Opc == BO_Xor) &&
13912       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13913     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13914     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13915   }
13916 
13917   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13918   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13919   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13920     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13921     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13922   }
13923 
13924   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13925       || Opc == BO_Shr) {
13926     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13927     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13928     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13929   }
13930 
13931   // Warn on overloaded shift operators and comparisons, such as:
13932   // cout << 5 == 4;
13933   if (BinaryOperator::isComparisonOp(Opc))
13934     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13935 }
13936 
13937 // Binary Operators.  'Tok' is the token for the operator.
13938 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13939                             tok::TokenKind Kind,
13940                             Expr *LHSExpr, Expr *RHSExpr) {
13941   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13942   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13943   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13944 
13945   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13946   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13947 
13948   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13949 }
13950 
13951 /// Build an overloaded binary operator expression in the given scope.
13952 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13953                                        BinaryOperatorKind Opc,
13954                                        Expr *LHS, Expr *RHS) {
13955   switch (Opc) {
13956   case BO_Assign:
13957   case BO_DivAssign:
13958   case BO_RemAssign:
13959   case BO_SubAssign:
13960   case BO_AndAssign:
13961   case BO_OrAssign:
13962   case BO_XorAssign:
13963     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13964     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13965     break;
13966   default:
13967     break;
13968   }
13969 
13970   // Find all of the overloaded operators visible from this
13971   // point. We perform both an operator-name lookup from the local
13972   // scope and an argument-dependent lookup based on the types of
13973   // the arguments.
13974   UnresolvedSet<16> Functions;
13975   OverloadedOperatorKind OverOp
13976     = BinaryOperator::getOverloadedOperator(Opc);
13977   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13978     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13979                                    RHS->getType(), Functions);
13980 
13981   // In C++20 onwards, we may have a second operator to look up.
13982   if (S.getLangOpts().CPlusPlus20) {
13983     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13984       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13985                                      RHS->getType(), Functions);
13986   }
13987 
13988   // Build the (potentially-overloaded, potentially-dependent)
13989   // binary operation.
13990   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13991 }
13992 
13993 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13994                             BinaryOperatorKind Opc,
13995                             Expr *LHSExpr, Expr *RHSExpr) {
13996   ExprResult LHS, RHS;
13997   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13998   if (!LHS.isUsable() || !RHS.isUsable())
13999     return ExprError();
14000   LHSExpr = LHS.get();
14001   RHSExpr = RHS.get();
14002 
14003   // We want to end up calling one of checkPseudoObjectAssignment
14004   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14005   // both expressions are overloadable or either is type-dependent),
14006   // or CreateBuiltinBinOp (in any other case).  We also want to get
14007   // any placeholder types out of the way.
14008 
14009   // Handle pseudo-objects in the LHS.
14010   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14011     // Assignments with a pseudo-object l-value need special analysis.
14012     if (pty->getKind() == BuiltinType::PseudoObject &&
14013         BinaryOperator::isAssignmentOp(Opc))
14014       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14015 
14016     // Don't resolve overloads if the other type is overloadable.
14017     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14018       // We can't actually test that if we still have a placeholder,
14019       // though.  Fortunately, none of the exceptions we see in that
14020       // code below are valid when the LHS is an overload set.  Note
14021       // that an overload set can be dependently-typed, but it never
14022       // instantiates to having an overloadable type.
14023       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14024       if (resolvedRHS.isInvalid()) return ExprError();
14025       RHSExpr = resolvedRHS.get();
14026 
14027       if (RHSExpr->isTypeDependent() ||
14028           RHSExpr->getType()->isOverloadableType())
14029         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14030     }
14031 
14032     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14033     // template, diagnose the missing 'template' keyword instead of diagnosing
14034     // an invalid use of a bound member function.
14035     //
14036     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14037     // to C++1z [over.over]/1.4, but we already checked for that case above.
14038     if (Opc == BO_LT && inTemplateInstantiation() &&
14039         (pty->getKind() == BuiltinType::BoundMember ||
14040          pty->getKind() == BuiltinType::Overload)) {
14041       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14042       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14043           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14044             return isa<FunctionTemplateDecl>(ND);
14045           })) {
14046         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14047                                 : OE->getNameLoc(),
14048              diag::err_template_kw_missing)
14049           << OE->getName().getAsString() << "";
14050         return ExprError();
14051       }
14052     }
14053 
14054     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14055     if (LHS.isInvalid()) return ExprError();
14056     LHSExpr = LHS.get();
14057   }
14058 
14059   // Handle pseudo-objects in the RHS.
14060   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14061     // An overload in the RHS can potentially be resolved by the type
14062     // being assigned to.
14063     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14064       if (getLangOpts().CPlusPlus &&
14065           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14066            LHSExpr->getType()->isOverloadableType()))
14067         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14068 
14069       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14070     }
14071 
14072     // Don't resolve overloads if the other type is overloadable.
14073     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14074         LHSExpr->getType()->isOverloadableType())
14075       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14076 
14077     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14078     if (!resolvedRHS.isUsable()) return ExprError();
14079     RHSExpr = resolvedRHS.get();
14080   }
14081 
14082   if (getLangOpts().CPlusPlus) {
14083     // If either expression is type-dependent, always build an
14084     // overloaded op.
14085     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14086       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14087 
14088     // Otherwise, build an overloaded op if either expression has an
14089     // overloadable type.
14090     if (LHSExpr->getType()->isOverloadableType() ||
14091         RHSExpr->getType()->isOverloadableType())
14092       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14093   }
14094 
14095   // Build a built-in binary operation.
14096   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14097 }
14098 
14099 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14100   if (T.isNull() || T->isDependentType())
14101     return false;
14102 
14103   if (!T->isPromotableIntegerType())
14104     return true;
14105 
14106   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14107 }
14108 
14109 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14110                                       UnaryOperatorKind Opc,
14111                                       Expr *InputExpr) {
14112   ExprResult Input = InputExpr;
14113   ExprValueKind VK = VK_RValue;
14114   ExprObjectKind OK = OK_Ordinary;
14115   QualType resultType;
14116   bool CanOverflow = false;
14117 
14118   bool ConvertHalfVec = false;
14119   if (getLangOpts().OpenCL) {
14120     QualType Ty = InputExpr->getType();
14121     // The only legal unary operation for atomics is '&'.
14122     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14123     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14124     // only with a builtin functions and therefore should be disallowed here.
14125         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14126         || Ty->isBlockPointerType())) {
14127       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14128                        << InputExpr->getType()
14129                        << Input.get()->getSourceRange());
14130     }
14131   }
14132   // Diagnose operations on the unsupported types for OpenMP device compilation.
14133   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
14134     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
14135         UnaryOperator::isArithmeticOp(Opc))
14136       checkOpenMPDeviceExpr(InputExpr);
14137   }
14138 
14139   switch (Opc) {
14140   case UO_PreInc:
14141   case UO_PreDec:
14142   case UO_PostInc:
14143   case UO_PostDec:
14144     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14145                                                 OpLoc,
14146                                                 Opc == UO_PreInc ||
14147                                                 Opc == UO_PostInc,
14148                                                 Opc == UO_PreInc ||
14149                                                 Opc == UO_PreDec);
14150     CanOverflow = isOverflowingIntegerType(Context, resultType);
14151     break;
14152   case UO_AddrOf:
14153     resultType = CheckAddressOfOperand(Input, OpLoc);
14154     CheckAddressOfNoDeref(InputExpr);
14155     RecordModifiableNonNullParam(*this, InputExpr);
14156     break;
14157   case UO_Deref: {
14158     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14159     if (Input.isInvalid()) return ExprError();
14160     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14161     break;
14162   }
14163   case UO_Plus:
14164   case UO_Minus:
14165     CanOverflow = Opc == UO_Minus &&
14166                   isOverflowingIntegerType(Context, Input.get()->getType());
14167     Input = UsualUnaryConversions(Input.get());
14168     if (Input.isInvalid()) return ExprError();
14169     // Unary plus and minus require promoting an operand of half vector to a
14170     // float vector and truncating the result back to a half vector. For now, we
14171     // do this only when HalfArgsAndReturns is set (that is, when the target is
14172     // arm or arm64).
14173     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14174 
14175     // If the operand is a half vector, promote it to a float vector.
14176     if (ConvertHalfVec)
14177       Input = convertVector(Input.get(), Context.FloatTy, *this);
14178     resultType = Input.get()->getType();
14179     if (resultType->isDependentType())
14180       break;
14181     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14182       break;
14183     else if (resultType->isVectorType() &&
14184              // The z vector extensions don't allow + or - with bool vectors.
14185              (!Context.getLangOpts().ZVector ||
14186               resultType->castAs<VectorType>()->getVectorKind() !=
14187               VectorType::AltiVecBool))
14188       break;
14189     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14190              Opc == UO_Plus &&
14191              resultType->isPointerType())
14192       break;
14193 
14194     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14195       << resultType << Input.get()->getSourceRange());
14196 
14197   case UO_Not: // bitwise complement
14198     Input = UsualUnaryConversions(Input.get());
14199     if (Input.isInvalid())
14200       return ExprError();
14201     resultType = Input.get()->getType();
14202     if (resultType->isDependentType())
14203       break;
14204     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14205     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14206       // C99 does not support '~' for complex conjugation.
14207       Diag(OpLoc, diag::ext_integer_complement_complex)
14208           << resultType << Input.get()->getSourceRange();
14209     else if (resultType->hasIntegerRepresentation())
14210       break;
14211     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14212       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14213       // on vector float types.
14214       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14215       if (!T->isIntegerType())
14216         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14217                           << resultType << Input.get()->getSourceRange());
14218     } else {
14219       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14220                        << resultType << Input.get()->getSourceRange());
14221     }
14222     break;
14223 
14224   case UO_LNot: // logical negation
14225     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14226     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14227     if (Input.isInvalid()) return ExprError();
14228     resultType = Input.get()->getType();
14229 
14230     // Though we still have to promote half FP to float...
14231     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14232       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14233       resultType = Context.FloatTy;
14234     }
14235 
14236     if (resultType->isDependentType())
14237       break;
14238     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14239       // C99 6.5.3.3p1: ok, fallthrough;
14240       if (Context.getLangOpts().CPlusPlus) {
14241         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14242         // operand contextually converted to bool.
14243         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14244                                   ScalarTypeToBooleanCastKind(resultType));
14245       } else if (Context.getLangOpts().OpenCL &&
14246                  Context.getLangOpts().OpenCLVersion < 120) {
14247         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14248         // operate on scalar float types.
14249         if (!resultType->isIntegerType() && !resultType->isPointerType())
14250           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14251                            << resultType << Input.get()->getSourceRange());
14252       }
14253     } else if (resultType->isExtVectorType()) {
14254       if (Context.getLangOpts().OpenCL &&
14255           Context.getLangOpts().OpenCLVersion < 120 &&
14256           !Context.getLangOpts().OpenCLCPlusPlus) {
14257         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14258         // operate on vector float types.
14259         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14260         if (!T->isIntegerType())
14261           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14262                            << resultType << Input.get()->getSourceRange());
14263       }
14264       // Vector logical not returns the signed variant of the operand type.
14265       resultType = GetSignedVectorType(resultType);
14266       break;
14267     } else {
14268       // FIXME: GCC's vector extension permits the usage of '!' with a vector
14269       //        type in C++. We should allow that here too.
14270       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14271         << resultType << Input.get()->getSourceRange());
14272     }
14273 
14274     // LNot always has type int. C99 6.5.3.3p5.
14275     // In C++, it's bool. C++ 5.3.1p8
14276     resultType = Context.getLogicalOperationType();
14277     break;
14278   case UO_Real:
14279   case UO_Imag:
14280     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14281     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14282     // complex l-values to ordinary l-values and all other values to r-values.
14283     if (Input.isInvalid()) return ExprError();
14284     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14285       if (Input.get()->getValueKind() != VK_RValue &&
14286           Input.get()->getObjectKind() == OK_Ordinary)
14287         VK = Input.get()->getValueKind();
14288     } else if (!getLangOpts().CPlusPlus) {
14289       // In C, a volatile scalar is read by __imag. In C++, it is not.
14290       Input = DefaultLvalueConversion(Input.get());
14291     }
14292     break;
14293   case UO_Extension:
14294     resultType = Input.get()->getType();
14295     VK = Input.get()->getValueKind();
14296     OK = Input.get()->getObjectKind();
14297     break;
14298   case UO_Coawait:
14299     // It's unnecessary to represent the pass-through operator co_await in the
14300     // AST; just return the input expression instead.
14301     assert(!Input.get()->getType()->isDependentType() &&
14302                    "the co_await expression must be non-dependant before "
14303                    "building operator co_await");
14304     return Input;
14305   }
14306   if (resultType.isNull() || Input.isInvalid())
14307     return ExprError();
14308 
14309   // Check for array bounds violations in the operand of the UnaryOperator,
14310   // except for the '*' and '&' operators that have to be handled specially
14311   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14312   // that are explicitly defined as valid by the standard).
14313   if (Opc != UO_AddrOf && Opc != UO_Deref)
14314     CheckArrayAccess(Input.get());
14315 
14316   auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK,
14317                                    OK, OpLoc, CanOverflow, CurFPFeatures);
14318 
14319   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14320       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14321     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14322 
14323   // Convert the result back to a half vector.
14324   if (ConvertHalfVec)
14325     return convertVector(UO, Context.HalfTy, *this);
14326   return UO;
14327 }
14328 
14329 /// Determine whether the given expression is a qualified member
14330 /// access expression, of a form that could be turned into a pointer to member
14331 /// with the address-of operator.
14332 bool Sema::isQualifiedMemberAccess(Expr *E) {
14333   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14334     if (!DRE->getQualifier())
14335       return false;
14336 
14337     ValueDecl *VD = DRE->getDecl();
14338     if (!VD->isCXXClassMember())
14339       return false;
14340 
14341     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14342       return true;
14343     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14344       return Method->isInstance();
14345 
14346     return false;
14347   }
14348 
14349   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14350     if (!ULE->getQualifier())
14351       return false;
14352 
14353     for (NamedDecl *D : ULE->decls()) {
14354       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14355         if (Method->isInstance())
14356           return true;
14357       } else {
14358         // Overload set does not contain methods.
14359         break;
14360       }
14361     }
14362 
14363     return false;
14364   }
14365 
14366   return false;
14367 }
14368 
14369 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14370                               UnaryOperatorKind Opc, Expr *Input) {
14371   // First things first: handle placeholders so that the
14372   // overloaded-operator check considers the right type.
14373   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14374     // Increment and decrement of pseudo-object references.
14375     if (pty->getKind() == BuiltinType::PseudoObject &&
14376         UnaryOperator::isIncrementDecrementOp(Opc))
14377       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14378 
14379     // extension is always a builtin operator.
14380     if (Opc == UO_Extension)
14381       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14382 
14383     // & gets special logic for several kinds of placeholder.
14384     // The builtin code knows what to do.
14385     if (Opc == UO_AddrOf &&
14386         (pty->getKind() == BuiltinType::Overload ||
14387          pty->getKind() == BuiltinType::UnknownAny ||
14388          pty->getKind() == BuiltinType::BoundMember))
14389       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14390 
14391     // Anything else needs to be handled now.
14392     ExprResult Result = CheckPlaceholderExpr(Input);
14393     if (Result.isInvalid()) return ExprError();
14394     Input = Result.get();
14395   }
14396 
14397   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14398       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14399       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14400     // Find all of the overloaded operators visible from this
14401     // point. We perform both an operator-name lookup from the local
14402     // scope and an argument-dependent lookup based on the types of
14403     // the arguments.
14404     UnresolvedSet<16> Functions;
14405     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14406     if (S && OverOp != OO_None)
14407       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14408                                    Functions);
14409 
14410     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14411   }
14412 
14413   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14414 }
14415 
14416 // Unary Operators.  'Tok' is the token for the operator.
14417 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14418                               tok::TokenKind Op, Expr *Input) {
14419   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14420 }
14421 
14422 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14423 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14424                                 LabelDecl *TheDecl) {
14425   TheDecl->markUsed(Context);
14426   // Create the AST node.  The address of a label always has type 'void*'.
14427   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14428                                      Context.getPointerType(Context.VoidTy));
14429 }
14430 
14431 void Sema::ActOnStartStmtExpr() {
14432   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14433 }
14434 
14435 void Sema::ActOnStmtExprError() {
14436   // Note that function is also called by TreeTransform when leaving a
14437   // StmtExpr scope without rebuilding anything.
14438 
14439   DiscardCleanupsInEvaluationContext();
14440   PopExpressionEvaluationContext();
14441 }
14442 
14443 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14444                                SourceLocation RPLoc) {
14445   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14446 }
14447 
14448 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14449                                SourceLocation RPLoc, unsigned TemplateDepth) {
14450   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14451   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14452 
14453   if (hasAnyUnrecoverableErrorsInThisFunction())
14454     DiscardCleanupsInEvaluationContext();
14455   assert(!Cleanup.exprNeedsCleanups() &&
14456          "cleanups within StmtExpr not correctly bound!");
14457   PopExpressionEvaluationContext();
14458 
14459   // FIXME: there are a variety of strange constraints to enforce here, for
14460   // example, it is not possible to goto into a stmt expression apparently.
14461   // More semantic analysis is needed.
14462 
14463   // If there are sub-stmts in the compound stmt, take the type of the last one
14464   // as the type of the stmtexpr.
14465   QualType Ty = Context.VoidTy;
14466   bool StmtExprMayBindToTemp = false;
14467   if (!Compound->body_empty()) {
14468     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14469     if (const auto *LastStmt =
14470             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14471       if (const Expr *Value = LastStmt->getExprStmt()) {
14472         StmtExprMayBindToTemp = true;
14473         Ty = Value->getType();
14474       }
14475     }
14476   }
14477 
14478   // FIXME: Check that expression type is complete/non-abstract; statement
14479   // expressions are not lvalues.
14480   Expr *ResStmtExpr =
14481       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14482   if (StmtExprMayBindToTemp)
14483     return MaybeBindToTemporary(ResStmtExpr);
14484   return ResStmtExpr;
14485 }
14486 
14487 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14488   if (ER.isInvalid())
14489     return ExprError();
14490 
14491   // Do function/array conversion on the last expression, but not
14492   // lvalue-to-rvalue.  However, initialize an unqualified type.
14493   ER = DefaultFunctionArrayConversion(ER.get());
14494   if (ER.isInvalid())
14495     return ExprError();
14496   Expr *E = ER.get();
14497 
14498   if (E->isTypeDependent())
14499     return E;
14500 
14501   // In ARC, if the final expression ends in a consume, splice
14502   // the consume out and bind it later.  In the alternate case
14503   // (when dealing with a retainable type), the result
14504   // initialization will create a produce.  In both cases the
14505   // result will be +1, and we'll need to balance that out with
14506   // a bind.
14507   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14508   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14509     return Cast->getSubExpr();
14510 
14511   // FIXME: Provide a better location for the initialization.
14512   return PerformCopyInitialization(
14513       InitializedEntity::InitializeStmtExprResult(
14514           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14515       SourceLocation(), E);
14516 }
14517 
14518 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14519                                       TypeSourceInfo *TInfo,
14520                                       ArrayRef<OffsetOfComponent> Components,
14521                                       SourceLocation RParenLoc) {
14522   QualType ArgTy = TInfo->getType();
14523   bool Dependent = ArgTy->isDependentType();
14524   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14525 
14526   // We must have at least one component that refers to the type, and the first
14527   // one is known to be a field designator.  Verify that the ArgTy represents
14528   // a struct/union/class.
14529   if (!Dependent && !ArgTy->isRecordType())
14530     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14531                        << ArgTy << TypeRange);
14532 
14533   // Type must be complete per C99 7.17p3 because a declaring a variable
14534   // with an incomplete type would be ill-formed.
14535   if (!Dependent
14536       && RequireCompleteType(BuiltinLoc, ArgTy,
14537                              diag::err_offsetof_incomplete_type, TypeRange))
14538     return ExprError();
14539 
14540   bool DidWarnAboutNonPOD = false;
14541   QualType CurrentType = ArgTy;
14542   SmallVector<OffsetOfNode, 4> Comps;
14543   SmallVector<Expr*, 4> Exprs;
14544   for (const OffsetOfComponent &OC : Components) {
14545     if (OC.isBrackets) {
14546       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14547       if (!CurrentType->isDependentType()) {
14548         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14549         if(!AT)
14550           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14551                            << CurrentType);
14552         CurrentType = AT->getElementType();
14553       } else
14554         CurrentType = Context.DependentTy;
14555 
14556       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14557       if (IdxRval.isInvalid())
14558         return ExprError();
14559       Expr *Idx = IdxRval.get();
14560 
14561       // The expression must be an integral expression.
14562       // FIXME: An integral constant expression?
14563       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14564           !Idx->getType()->isIntegerType())
14565         return ExprError(
14566             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14567             << Idx->getSourceRange());
14568 
14569       // Record this array index.
14570       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14571       Exprs.push_back(Idx);
14572       continue;
14573     }
14574 
14575     // Offset of a field.
14576     if (CurrentType->isDependentType()) {
14577       // We have the offset of a field, but we can't look into the dependent
14578       // type. Just record the identifier of the field.
14579       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14580       CurrentType = Context.DependentTy;
14581       continue;
14582     }
14583 
14584     // We need to have a complete type to look into.
14585     if (RequireCompleteType(OC.LocStart, CurrentType,
14586                             diag::err_offsetof_incomplete_type))
14587       return ExprError();
14588 
14589     // Look for the designated field.
14590     const RecordType *RC = CurrentType->getAs<RecordType>();
14591     if (!RC)
14592       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14593                        << CurrentType);
14594     RecordDecl *RD = RC->getDecl();
14595 
14596     // C++ [lib.support.types]p5:
14597     //   The macro offsetof accepts a restricted set of type arguments in this
14598     //   International Standard. type shall be a POD structure or a POD union
14599     //   (clause 9).
14600     // C++11 [support.types]p4:
14601     //   If type is not a standard-layout class (Clause 9), the results are
14602     //   undefined.
14603     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14604       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14605       unsigned DiagID =
14606         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14607                             : diag::ext_offsetof_non_pod_type;
14608 
14609       if (!IsSafe && !DidWarnAboutNonPOD &&
14610           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14611                               PDiag(DiagID)
14612                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14613                               << CurrentType))
14614         DidWarnAboutNonPOD = true;
14615     }
14616 
14617     // Look for the field.
14618     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14619     LookupQualifiedName(R, RD);
14620     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14621     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14622     if (!MemberDecl) {
14623       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14624         MemberDecl = IndirectMemberDecl->getAnonField();
14625     }
14626 
14627     if (!MemberDecl)
14628       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14629                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14630                                                               OC.LocEnd));
14631 
14632     // C99 7.17p3:
14633     //   (If the specified member is a bit-field, the behavior is undefined.)
14634     //
14635     // We diagnose this as an error.
14636     if (MemberDecl->isBitField()) {
14637       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14638         << MemberDecl->getDeclName()
14639         << SourceRange(BuiltinLoc, RParenLoc);
14640       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14641       return ExprError();
14642     }
14643 
14644     RecordDecl *Parent = MemberDecl->getParent();
14645     if (IndirectMemberDecl)
14646       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14647 
14648     // If the member was found in a base class, introduce OffsetOfNodes for
14649     // the base class indirections.
14650     CXXBasePaths Paths;
14651     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14652                       Paths)) {
14653       if (Paths.getDetectedVirtual()) {
14654         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14655           << MemberDecl->getDeclName()
14656           << SourceRange(BuiltinLoc, RParenLoc);
14657         return ExprError();
14658       }
14659 
14660       CXXBasePath &Path = Paths.front();
14661       for (const CXXBasePathElement &B : Path)
14662         Comps.push_back(OffsetOfNode(B.Base));
14663     }
14664 
14665     if (IndirectMemberDecl) {
14666       for (auto *FI : IndirectMemberDecl->chain()) {
14667         assert(isa<FieldDecl>(FI));
14668         Comps.push_back(OffsetOfNode(OC.LocStart,
14669                                      cast<FieldDecl>(FI), OC.LocEnd));
14670       }
14671     } else
14672       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14673 
14674     CurrentType = MemberDecl->getType().getNonReferenceType();
14675   }
14676 
14677   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14678                               Comps, Exprs, RParenLoc);
14679 }
14680 
14681 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14682                                       SourceLocation BuiltinLoc,
14683                                       SourceLocation TypeLoc,
14684                                       ParsedType ParsedArgTy,
14685                                       ArrayRef<OffsetOfComponent> Components,
14686                                       SourceLocation RParenLoc) {
14687 
14688   TypeSourceInfo *ArgTInfo;
14689   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14690   if (ArgTy.isNull())
14691     return ExprError();
14692 
14693   if (!ArgTInfo)
14694     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14695 
14696   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14697 }
14698 
14699 
14700 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14701                                  Expr *CondExpr,
14702                                  Expr *LHSExpr, Expr *RHSExpr,
14703                                  SourceLocation RPLoc) {
14704   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14705 
14706   ExprValueKind VK = VK_RValue;
14707   ExprObjectKind OK = OK_Ordinary;
14708   QualType resType;
14709   bool CondIsTrue = false;
14710   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14711     resType = Context.DependentTy;
14712   } else {
14713     // The conditional expression is required to be a constant expression.
14714     llvm::APSInt condEval(32);
14715     ExprResult CondICE
14716       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14717           diag::err_typecheck_choose_expr_requires_constant, false);
14718     if (CondICE.isInvalid())
14719       return ExprError();
14720     CondExpr = CondICE.get();
14721     CondIsTrue = condEval.getZExtValue();
14722 
14723     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14724     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14725 
14726     resType = ActiveExpr->getType();
14727     VK = ActiveExpr->getValueKind();
14728     OK = ActiveExpr->getObjectKind();
14729   }
14730 
14731   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14732                                   resType, VK, OK, RPLoc, CondIsTrue);
14733 }
14734 
14735 //===----------------------------------------------------------------------===//
14736 // Clang Extensions.
14737 //===----------------------------------------------------------------------===//
14738 
14739 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14740 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14741   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14742 
14743   if (LangOpts.CPlusPlus) {
14744     MangleNumberingContext *MCtx;
14745     Decl *ManglingContextDecl;
14746     std::tie(MCtx, ManglingContextDecl) =
14747         getCurrentMangleNumberContext(Block->getDeclContext());
14748     if (MCtx) {
14749       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14750       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14751     }
14752   }
14753 
14754   PushBlockScope(CurScope, Block);
14755   CurContext->addDecl(Block);
14756   if (CurScope)
14757     PushDeclContext(CurScope, Block);
14758   else
14759     CurContext = Block;
14760 
14761   getCurBlock()->HasImplicitReturnType = true;
14762 
14763   // Enter a new evaluation context to insulate the block from any
14764   // cleanups from the enclosing full-expression.
14765   PushExpressionEvaluationContext(
14766       ExpressionEvaluationContext::PotentiallyEvaluated);
14767 }
14768 
14769 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14770                                Scope *CurScope) {
14771   assert(ParamInfo.getIdentifier() == nullptr &&
14772          "block-id should have no identifier!");
14773   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14774   BlockScopeInfo *CurBlock = getCurBlock();
14775 
14776   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14777   QualType T = Sig->getType();
14778 
14779   // FIXME: We should allow unexpanded parameter packs here, but that would,
14780   // in turn, make the block expression contain unexpanded parameter packs.
14781   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14782     // Drop the parameters.
14783     FunctionProtoType::ExtProtoInfo EPI;
14784     EPI.HasTrailingReturn = false;
14785     EPI.TypeQuals.addConst();
14786     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14787     Sig = Context.getTrivialTypeSourceInfo(T);
14788   }
14789 
14790   // GetTypeForDeclarator always produces a function type for a block
14791   // literal signature.  Furthermore, it is always a FunctionProtoType
14792   // unless the function was written with a typedef.
14793   assert(T->isFunctionType() &&
14794          "GetTypeForDeclarator made a non-function block signature");
14795 
14796   // Look for an explicit signature in that function type.
14797   FunctionProtoTypeLoc ExplicitSignature;
14798 
14799   if ((ExplicitSignature = Sig->getTypeLoc()
14800                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14801 
14802     // Check whether that explicit signature was synthesized by
14803     // GetTypeForDeclarator.  If so, don't save that as part of the
14804     // written signature.
14805     if (ExplicitSignature.getLocalRangeBegin() ==
14806         ExplicitSignature.getLocalRangeEnd()) {
14807       // This would be much cheaper if we stored TypeLocs instead of
14808       // TypeSourceInfos.
14809       TypeLoc Result = ExplicitSignature.getReturnLoc();
14810       unsigned Size = Result.getFullDataSize();
14811       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14812       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14813 
14814       ExplicitSignature = FunctionProtoTypeLoc();
14815     }
14816   }
14817 
14818   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14819   CurBlock->FunctionType = T;
14820 
14821   const FunctionType *Fn = T->getAs<FunctionType>();
14822   QualType RetTy = Fn->getReturnType();
14823   bool isVariadic =
14824     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14825 
14826   CurBlock->TheDecl->setIsVariadic(isVariadic);
14827 
14828   // Context.DependentTy is used as a placeholder for a missing block
14829   // return type.  TODO:  what should we do with declarators like:
14830   //   ^ * { ... }
14831   // If the answer is "apply template argument deduction"....
14832   if (RetTy != Context.DependentTy) {
14833     CurBlock->ReturnType = RetTy;
14834     CurBlock->TheDecl->setBlockMissingReturnType(false);
14835     CurBlock->HasImplicitReturnType = false;
14836   }
14837 
14838   // Push block parameters from the declarator if we had them.
14839   SmallVector<ParmVarDecl*, 8> Params;
14840   if (ExplicitSignature) {
14841     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14842       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14843       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
14844           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
14845         // Diagnose this as an extension in C17 and earlier.
14846         if (!getLangOpts().C2x)
14847           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14848       }
14849       Params.push_back(Param);
14850     }
14851 
14852   // Fake up parameter variables if we have a typedef, like
14853   //   ^ fntype { ... }
14854   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14855     for (const auto &I : Fn->param_types()) {
14856       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14857           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14858       Params.push_back(Param);
14859     }
14860   }
14861 
14862   // Set the parameters on the block decl.
14863   if (!Params.empty()) {
14864     CurBlock->TheDecl->setParams(Params);
14865     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14866                              /*CheckParameterNames=*/false);
14867   }
14868 
14869   // Finally we can process decl attributes.
14870   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14871 
14872   // Put the parameter variables in scope.
14873   for (auto AI : CurBlock->TheDecl->parameters()) {
14874     AI->setOwningFunction(CurBlock->TheDecl);
14875 
14876     // If this has an identifier, add it to the scope stack.
14877     if (AI->getIdentifier()) {
14878       CheckShadow(CurBlock->TheScope, AI);
14879 
14880       PushOnScopeChains(AI, CurBlock->TheScope);
14881     }
14882   }
14883 }
14884 
14885 /// ActOnBlockError - If there is an error parsing a block, this callback
14886 /// is invoked to pop the information about the block from the action impl.
14887 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14888   // Leave the expression-evaluation context.
14889   DiscardCleanupsInEvaluationContext();
14890   PopExpressionEvaluationContext();
14891 
14892   // Pop off CurBlock, handle nested blocks.
14893   PopDeclContext();
14894   PopFunctionScopeInfo();
14895 }
14896 
14897 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14898 /// literal was successfully completed.  ^(int x){...}
14899 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14900                                     Stmt *Body, Scope *CurScope) {
14901   // If blocks are disabled, emit an error.
14902   if (!LangOpts.Blocks)
14903     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14904 
14905   // Leave the expression-evaluation context.
14906   if (hasAnyUnrecoverableErrorsInThisFunction())
14907     DiscardCleanupsInEvaluationContext();
14908   assert(!Cleanup.exprNeedsCleanups() &&
14909          "cleanups within block not correctly bound!");
14910   PopExpressionEvaluationContext();
14911 
14912   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14913   BlockDecl *BD = BSI->TheDecl;
14914 
14915   if (BSI->HasImplicitReturnType)
14916     deduceClosureReturnType(*BSI);
14917 
14918   QualType RetTy = Context.VoidTy;
14919   if (!BSI->ReturnType.isNull())
14920     RetTy = BSI->ReturnType;
14921 
14922   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14923   QualType BlockTy;
14924 
14925   // If the user wrote a function type in some form, try to use that.
14926   if (!BSI->FunctionType.isNull()) {
14927     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14928 
14929     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14930     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14931 
14932     // Turn protoless block types into nullary block types.
14933     if (isa<FunctionNoProtoType>(FTy)) {
14934       FunctionProtoType::ExtProtoInfo EPI;
14935       EPI.ExtInfo = Ext;
14936       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14937 
14938     // Otherwise, if we don't need to change anything about the function type,
14939     // preserve its sugar structure.
14940     } else if (FTy->getReturnType() == RetTy &&
14941                (!NoReturn || FTy->getNoReturnAttr())) {
14942       BlockTy = BSI->FunctionType;
14943 
14944     // Otherwise, make the minimal modifications to the function type.
14945     } else {
14946       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14947       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14948       EPI.TypeQuals = Qualifiers();
14949       EPI.ExtInfo = Ext;
14950       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14951     }
14952 
14953   // If we don't have a function type, just build one from nothing.
14954   } else {
14955     FunctionProtoType::ExtProtoInfo EPI;
14956     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14957     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14958   }
14959 
14960   DiagnoseUnusedParameters(BD->parameters());
14961   BlockTy = Context.getBlockPointerType(BlockTy);
14962 
14963   // If needed, diagnose invalid gotos and switches in the block.
14964   if (getCurFunction()->NeedsScopeChecking() &&
14965       !PP.isCodeCompletionEnabled())
14966     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14967 
14968   BD->setBody(cast<CompoundStmt>(Body));
14969 
14970   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14971     DiagnoseUnguardedAvailabilityViolations(BD);
14972 
14973   // Try to apply the named return value optimization. We have to check again
14974   // if we can do this, though, because blocks keep return statements around
14975   // to deduce an implicit return type.
14976   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14977       !BD->isDependentContext())
14978     computeNRVO(Body, BSI);
14979 
14980   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14981       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14982     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14983                           NTCUK_Destruct|NTCUK_Copy);
14984 
14985   PopDeclContext();
14986 
14987   // Pop the block scope now but keep it alive to the end of this function.
14988   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14989   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14990 
14991   // Set the captured variables on the block.
14992   SmallVector<BlockDecl::Capture, 4> Captures;
14993   for (Capture &Cap : BSI->Captures) {
14994     if (Cap.isInvalid() || Cap.isThisCapture())
14995       continue;
14996 
14997     VarDecl *Var = Cap.getVariable();
14998     Expr *CopyExpr = nullptr;
14999     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15000       if (const RecordType *Record =
15001               Cap.getCaptureType()->getAs<RecordType>()) {
15002         // The capture logic needs the destructor, so make sure we mark it.
15003         // Usually this is unnecessary because most local variables have
15004         // their destructors marked at declaration time, but parameters are
15005         // an exception because it's technically only the call site that
15006         // actually requires the destructor.
15007         if (isa<ParmVarDecl>(Var))
15008           FinalizeVarWithDestructor(Var, Record);
15009 
15010         // Enter a separate potentially-evaluated context while building block
15011         // initializers to isolate their cleanups from those of the block
15012         // itself.
15013         // FIXME: Is this appropriate even when the block itself occurs in an
15014         // unevaluated operand?
15015         EnterExpressionEvaluationContext EvalContext(
15016             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15017 
15018         SourceLocation Loc = Cap.getLocation();
15019 
15020         ExprResult Result = BuildDeclarationNameExpr(
15021             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15022 
15023         // According to the blocks spec, the capture of a variable from
15024         // the stack requires a const copy constructor.  This is not true
15025         // of the copy/move done to move a __block variable to the heap.
15026         if (!Result.isInvalid() &&
15027             !Result.get()->getType().isConstQualified()) {
15028           Result = ImpCastExprToType(Result.get(),
15029                                      Result.get()->getType().withConst(),
15030                                      CK_NoOp, VK_LValue);
15031         }
15032 
15033         if (!Result.isInvalid()) {
15034           Result = PerformCopyInitialization(
15035               InitializedEntity::InitializeBlock(Var->getLocation(),
15036                                                  Cap.getCaptureType(), false),
15037               Loc, Result.get());
15038         }
15039 
15040         // Build a full-expression copy expression if initialization
15041         // succeeded and used a non-trivial constructor.  Recover from
15042         // errors by pretending that the copy isn't necessary.
15043         if (!Result.isInvalid() &&
15044             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15045                 ->isTrivial()) {
15046           Result = MaybeCreateExprWithCleanups(Result);
15047           CopyExpr = Result.get();
15048         }
15049       }
15050     }
15051 
15052     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15053                               CopyExpr);
15054     Captures.push_back(NewCap);
15055   }
15056   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15057 
15058   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15059 
15060   // If the block isn't obviously global, i.e. it captures anything at
15061   // all, then we need to do a few things in the surrounding context:
15062   if (Result->getBlockDecl()->hasCaptures()) {
15063     // First, this expression has a new cleanup object.
15064     ExprCleanupObjects.push_back(Result->getBlockDecl());
15065     Cleanup.setExprNeedsCleanups(true);
15066 
15067     // It also gets a branch-protected scope if any of the captured
15068     // variables needs destruction.
15069     for (const auto &CI : Result->getBlockDecl()->captures()) {
15070       const VarDecl *var = CI.getVariable();
15071       if (var->getType().isDestructedType() != QualType::DK_none) {
15072         setFunctionHasBranchProtectedScope();
15073         break;
15074       }
15075     }
15076   }
15077 
15078   if (getCurFunction())
15079     getCurFunction()->addBlock(BD);
15080 
15081   return Result;
15082 }
15083 
15084 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15085                             SourceLocation RPLoc) {
15086   TypeSourceInfo *TInfo;
15087   GetTypeFromParser(Ty, &TInfo);
15088   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15089 }
15090 
15091 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15092                                 Expr *E, TypeSourceInfo *TInfo,
15093                                 SourceLocation RPLoc) {
15094   Expr *OrigExpr = E;
15095   bool IsMS = false;
15096 
15097   // CUDA device code does not support varargs.
15098   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15099     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15100       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15101       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15102         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15103     }
15104   }
15105 
15106   // NVPTX does not support va_arg expression.
15107   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15108       Context.getTargetInfo().getTriple().isNVPTX())
15109     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15110 
15111   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15112   // as Microsoft ABI on an actual Microsoft platform, where
15113   // __builtin_ms_va_list and __builtin_va_list are the same.)
15114   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15115       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15116     QualType MSVaListType = Context.getBuiltinMSVaListType();
15117     if (Context.hasSameType(MSVaListType, E->getType())) {
15118       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15119         return ExprError();
15120       IsMS = true;
15121     }
15122   }
15123 
15124   // Get the va_list type
15125   QualType VaListType = Context.getBuiltinVaListType();
15126   if (!IsMS) {
15127     if (VaListType->isArrayType()) {
15128       // Deal with implicit array decay; for example, on x86-64,
15129       // va_list is an array, but it's supposed to decay to
15130       // a pointer for va_arg.
15131       VaListType = Context.getArrayDecayedType(VaListType);
15132       // Make sure the input expression also decays appropriately.
15133       ExprResult Result = UsualUnaryConversions(E);
15134       if (Result.isInvalid())
15135         return ExprError();
15136       E = Result.get();
15137     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15138       // If va_list is a record type and we are compiling in C++ mode,
15139       // check the argument using reference binding.
15140       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15141           Context, Context.getLValueReferenceType(VaListType), false);
15142       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15143       if (Init.isInvalid())
15144         return ExprError();
15145       E = Init.getAs<Expr>();
15146     } else {
15147       // Otherwise, the va_list argument must be an l-value because
15148       // it is modified by va_arg.
15149       if (!E->isTypeDependent() &&
15150           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15151         return ExprError();
15152     }
15153   }
15154 
15155   if (!IsMS && !E->isTypeDependent() &&
15156       !Context.hasSameType(VaListType, E->getType()))
15157     return ExprError(
15158         Diag(E->getBeginLoc(),
15159              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15160         << OrigExpr->getType() << E->getSourceRange());
15161 
15162   if (!TInfo->getType()->isDependentType()) {
15163     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15164                             diag::err_second_parameter_to_va_arg_incomplete,
15165                             TInfo->getTypeLoc()))
15166       return ExprError();
15167 
15168     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15169                                TInfo->getType(),
15170                                diag::err_second_parameter_to_va_arg_abstract,
15171                                TInfo->getTypeLoc()))
15172       return ExprError();
15173 
15174     if (!TInfo->getType().isPODType(Context)) {
15175       Diag(TInfo->getTypeLoc().getBeginLoc(),
15176            TInfo->getType()->isObjCLifetimeType()
15177              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15178              : diag::warn_second_parameter_to_va_arg_not_pod)
15179         << TInfo->getType()
15180         << TInfo->getTypeLoc().getSourceRange();
15181     }
15182 
15183     // Check for va_arg where arguments of the given type will be promoted
15184     // (i.e. this va_arg is guaranteed to have undefined behavior).
15185     QualType PromoteType;
15186     if (TInfo->getType()->isPromotableIntegerType()) {
15187       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15188       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15189         PromoteType = QualType();
15190     }
15191     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15192       PromoteType = Context.DoubleTy;
15193     if (!PromoteType.isNull())
15194       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15195                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15196                           << TInfo->getType()
15197                           << PromoteType
15198                           << TInfo->getTypeLoc().getSourceRange());
15199   }
15200 
15201   QualType T = TInfo->getType().getNonLValueExprType(Context);
15202   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15203 }
15204 
15205 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15206   // The type of __null will be int or long, depending on the size of
15207   // pointers on the target.
15208   QualType Ty;
15209   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15210   if (pw == Context.getTargetInfo().getIntWidth())
15211     Ty = Context.IntTy;
15212   else if (pw == Context.getTargetInfo().getLongWidth())
15213     Ty = Context.LongTy;
15214   else if (pw == Context.getTargetInfo().getLongLongWidth())
15215     Ty = Context.LongLongTy;
15216   else {
15217     llvm_unreachable("I don't know size of pointer!");
15218   }
15219 
15220   return new (Context) GNUNullExpr(Ty, TokenLoc);
15221 }
15222 
15223 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15224                                     SourceLocation BuiltinLoc,
15225                                     SourceLocation RPLoc) {
15226   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15227 }
15228 
15229 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15230                                     SourceLocation BuiltinLoc,
15231                                     SourceLocation RPLoc,
15232                                     DeclContext *ParentContext) {
15233   return new (Context)
15234       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15235 }
15236 
15237 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15238                                         bool Diagnose) {
15239   if (!getLangOpts().ObjC)
15240     return false;
15241 
15242   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15243   if (!PT)
15244     return false;
15245   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15246 
15247   // Ignore any parens, implicit casts (should only be
15248   // array-to-pointer decays), and not-so-opaque values.  The last is
15249   // important for making this trigger for property assignments.
15250   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15251   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15252     if (OV->getSourceExpr())
15253       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15254 
15255   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15256     if (!PT->isObjCIdType() &&
15257         !(ID && ID->getIdentifier()->isStr("NSString")))
15258       return false;
15259     if (!SL->isAscii())
15260       return false;
15261 
15262     if (Diagnose) {
15263       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15264           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15265       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15266     }
15267     return true;
15268   }
15269 
15270   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15271       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15272       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15273       !SrcExpr->isNullPointerConstant(
15274           getASTContext(), Expr::NPC_NeverValueDependent)) {
15275     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15276       return false;
15277     if (Diagnose) {
15278       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15279           << /*number*/1
15280           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15281       Expr *NumLit =
15282           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15283       if (NumLit)
15284         Exp = NumLit;
15285     }
15286     return true;
15287   }
15288 
15289   return false;
15290 }
15291 
15292 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15293                                               const Expr *SrcExpr) {
15294   if (!DstType->isFunctionPointerType() ||
15295       !SrcExpr->getType()->isFunctionType())
15296     return false;
15297 
15298   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15299   if (!DRE)
15300     return false;
15301 
15302   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15303   if (!FD)
15304     return false;
15305 
15306   return !S.checkAddressOfFunctionIsAvailable(FD,
15307                                               /*Complain=*/true,
15308                                               SrcExpr->getBeginLoc());
15309 }
15310 
15311 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15312                                     SourceLocation Loc,
15313                                     QualType DstType, QualType SrcType,
15314                                     Expr *SrcExpr, AssignmentAction Action,
15315                                     bool *Complained) {
15316   if (Complained)
15317     *Complained = false;
15318 
15319   // Decode the result (notice that AST's are still created for extensions).
15320   bool CheckInferredResultType = false;
15321   bool isInvalid = false;
15322   unsigned DiagKind = 0;
15323   FixItHint Hint;
15324   ConversionFixItGenerator ConvHints;
15325   bool MayHaveConvFixit = false;
15326   bool MayHaveFunctionDiff = false;
15327   const ObjCInterfaceDecl *IFace = nullptr;
15328   const ObjCProtocolDecl *PDecl = nullptr;
15329 
15330   switch (ConvTy) {
15331   case Compatible:
15332       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15333       return false;
15334 
15335   case PointerToInt:
15336     if (getLangOpts().CPlusPlus) {
15337       DiagKind = diag::err_typecheck_convert_pointer_int;
15338       isInvalid = true;
15339     } else {
15340       DiagKind = diag::ext_typecheck_convert_pointer_int;
15341     }
15342     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15343     MayHaveConvFixit = true;
15344     break;
15345   case IntToPointer:
15346     if (getLangOpts().CPlusPlus) {
15347       DiagKind = diag::err_typecheck_convert_int_pointer;
15348       isInvalid = true;
15349     } else {
15350       DiagKind = diag::ext_typecheck_convert_int_pointer;
15351     }
15352     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15353     MayHaveConvFixit = true;
15354     break;
15355   case IncompatibleFunctionPointer:
15356     if (getLangOpts().CPlusPlus) {
15357       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15358       isInvalid = true;
15359     } else {
15360       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15361     }
15362     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15363     MayHaveConvFixit = true;
15364     break;
15365   case IncompatiblePointer:
15366     if (Action == AA_Passing_CFAudited) {
15367       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15368     } else if (getLangOpts().CPlusPlus) {
15369       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15370       isInvalid = true;
15371     } else {
15372       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15373     }
15374     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15375       SrcType->isObjCObjectPointerType();
15376     if (Hint.isNull() && !CheckInferredResultType) {
15377       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15378     }
15379     else if (CheckInferredResultType) {
15380       SrcType = SrcType.getUnqualifiedType();
15381       DstType = DstType.getUnqualifiedType();
15382     }
15383     MayHaveConvFixit = true;
15384     break;
15385   case IncompatiblePointerSign:
15386     if (getLangOpts().CPlusPlus) {
15387       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15388       isInvalid = true;
15389     } else {
15390       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15391     }
15392     break;
15393   case FunctionVoidPointer:
15394     if (getLangOpts().CPlusPlus) {
15395       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15396       isInvalid = true;
15397     } else {
15398       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15399     }
15400     break;
15401   case IncompatiblePointerDiscardsQualifiers: {
15402     // Perform array-to-pointer decay if necessary.
15403     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15404 
15405     isInvalid = true;
15406 
15407     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15408     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15409     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15410       DiagKind = diag::err_typecheck_incompatible_address_space;
15411       break;
15412 
15413     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15414       DiagKind = diag::err_typecheck_incompatible_ownership;
15415       break;
15416     }
15417 
15418     llvm_unreachable("unknown error case for discarding qualifiers!");
15419     // fallthrough
15420   }
15421   case CompatiblePointerDiscardsQualifiers:
15422     // If the qualifiers lost were because we were applying the
15423     // (deprecated) C++ conversion from a string literal to a char*
15424     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15425     // Ideally, this check would be performed in
15426     // checkPointerTypesForAssignment. However, that would require a
15427     // bit of refactoring (so that the second argument is an
15428     // expression, rather than a type), which should be done as part
15429     // of a larger effort to fix checkPointerTypesForAssignment for
15430     // C++ semantics.
15431     if (getLangOpts().CPlusPlus &&
15432         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15433       return false;
15434     if (getLangOpts().CPlusPlus) {
15435       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15436       isInvalid = true;
15437     } else {
15438       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15439     }
15440 
15441     break;
15442   case IncompatibleNestedPointerQualifiers:
15443     if (getLangOpts().CPlusPlus) {
15444       isInvalid = true;
15445       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15446     } else {
15447       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15448     }
15449     break;
15450   case IncompatibleNestedPointerAddressSpaceMismatch:
15451     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15452     isInvalid = true;
15453     break;
15454   case IntToBlockPointer:
15455     DiagKind = diag::err_int_to_block_pointer;
15456     isInvalid = true;
15457     break;
15458   case IncompatibleBlockPointer:
15459     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15460     isInvalid = true;
15461     break;
15462   case IncompatibleObjCQualifiedId: {
15463     if (SrcType->isObjCQualifiedIdType()) {
15464       const ObjCObjectPointerType *srcOPT =
15465                 SrcType->castAs<ObjCObjectPointerType>();
15466       for (auto *srcProto : srcOPT->quals()) {
15467         PDecl = srcProto;
15468         break;
15469       }
15470       if (const ObjCInterfaceType *IFaceT =
15471             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15472         IFace = IFaceT->getDecl();
15473     }
15474     else if (DstType->isObjCQualifiedIdType()) {
15475       const ObjCObjectPointerType *dstOPT =
15476         DstType->castAs<ObjCObjectPointerType>();
15477       for (auto *dstProto : dstOPT->quals()) {
15478         PDecl = dstProto;
15479         break;
15480       }
15481       if (const ObjCInterfaceType *IFaceT =
15482             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15483         IFace = IFaceT->getDecl();
15484     }
15485     if (getLangOpts().CPlusPlus) {
15486       DiagKind = diag::err_incompatible_qualified_id;
15487       isInvalid = true;
15488     } else {
15489       DiagKind = diag::warn_incompatible_qualified_id;
15490     }
15491     break;
15492   }
15493   case IncompatibleVectors:
15494     if (getLangOpts().CPlusPlus) {
15495       DiagKind = diag::err_incompatible_vectors;
15496       isInvalid = true;
15497     } else {
15498       DiagKind = diag::warn_incompatible_vectors;
15499     }
15500     break;
15501   case IncompatibleObjCWeakRef:
15502     DiagKind = diag::err_arc_weak_unavailable_assign;
15503     isInvalid = true;
15504     break;
15505   case Incompatible:
15506     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15507       if (Complained)
15508         *Complained = true;
15509       return true;
15510     }
15511 
15512     DiagKind = diag::err_typecheck_convert_incompatible;
15513     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15514     MayHaveConvFixit = true;
15515     isInvalid = true;
15516     MayHaveFunctionDiff = true;
15517     break;
15518   }
15519 
15520   QualType FirstType, SecondType;
15521   switch (Action) {
15522   case AA_Assigning:
15523   case AA_Initializing:
15524     // The destination type comes first.
15525     FirstType = DstType;
15526     SecondType = SrcType;
15527     break;
15528 
15529   case AA_Returning:
15530   case AA_Passing:
15531   case AA_Passing_CFAudited:
15532   case AA_Converting:
15533   case AA_Sending:
15534   case AA_Casting:
15535     // The source type comes first.
15536     FirstType = SrcType;
15537     SecondType = DstType;
15538     break;
15539   }
15540 
15541   PartialDiagnostic FDiag = PDiag(DiagKind);
15542   if (Action == AA_Passing_CFAudited)
15543     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15544   else
15545     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15546 
15547   // If we can fix the conversion, suggest the FixIts.
15548   assert(ConvHints.isNull() || Hint.isNull());
15549   if (!ConvHints.isNull()) {
15550     for (FixItHint &H : ConvHints.Hints)
15551       FDiag << H;
15552   } else {
15553     FDiag << Hint;
15554   }
15555   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15556 
15557   if (MayHaveFunctionDiff)
15558     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15559 
15560   Diag(Loc, FDiag);
15561   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15562        DiagKind == diag::err_incompatible_qualified_id) &&
15563       PDecl && IFace && !IFace->hasDefinition())
15564     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15565         << IFace << PDecl;
15566 
15567   if (SecondType == Context.OverloadTy)
15568     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15569                               FirstType, /*TakingAddress=*/true);
15570 
15571   if (CheckInferredResultType)
15572     EmitRelatedResultTypeNote(SrcExpr);
15573 
15574   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15575     EmitRelatedResultTypeNoteForReturn(DstType);
15576 
15577   if (Complained)
15578     *Complained = true;
15579   return isInvalid;
15580 }
15581 
15582 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15583                                                  llvm::APSInt *Result) {
15584   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15585   public:
15586     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15587       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15588     }
15589   } Diagnoser;
15590 
15591   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15592 }
15593 
15594 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15595                                                  llvm::APSInt *Result,
15596                                                  unsigned DiagID,
15597                                                  bool AllowFold) {
15598   class IDDiagnoser : public VerifyICEDiagnoser {
15599     unsigned DiagID;
15600 
15601   public:
15602     IDDiagnoser(unsigned DiagID)
15603       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15604 
15605     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15606       S.Diag(Loc, DiagID) << SR;
15607     }
15608   } Diagnoser(DiagID);
15609 
15610   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15611 }
15612 
15613 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15614                                             SourceRange SR) {
15615   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15616 }
15617 
15618 ExprResult
15619 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15620                                       VerifyICEDiagnoser &Diagnoser,
15621                                       bool AllowFold) {
15622   SourceLocation DiagLoc = E->getBeginLoc();
15623 
15624   if (getLangOpts().CPlusPlus11) {
15625     // C++11 [expr.const]p5:
15626     //   If an expression of literal class type is used in a context where an
15627     //   integral constant expression is required, then that class type shall
15628     //   have a single non-explicit conversion function to an integral or
15629     //   unscoped enumeration type
15630     ExprResult Converted;
15631     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15632     public:
15633       CXX11ConvertDiagnoser(bool Silent)
15634           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15635                                 Silent, true) {}
15636 
15637       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15638                                            QualType T) override {
15639         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15640       }
15641 
15642       SemaDiagnosticBuilder diagnoseIncomplete(
15643           Sema &S, SourceLocation Loc, QualType T) override {
15644         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15645       }
15646 
15647       SemaDiagnosticBuilder diagnoseExplicitConv(
15648           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15649         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15650       }
15651 
15652       SemaDiagnosticBuilder noteExplicitConv(
15653           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15654         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15655                  << ConvTy->isEnumeralType() << ConvTy;
15656       }
15657 
15658       SemaDiagnosticBuilder diagnoseAmbiguous(
15659           Sema &S, SourceLocation Loc, QualType T) override {
15660         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15661       }
15662 
15663       SemaDiagnosticBuilder noteAmbiguous(
15664           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15665         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15666                  << ConvTy->isEnumeralType() << ConvTy;
15667       }
15668 
15669       SemaDiagnosticBuilder diagnoseConversion(
15670           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15671         llvm_unreachable("conversion functions are permitted");
15672       }
15673     } ConvertDiagnoser(Diagnoser.Suppress);
15674 
15675     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15676                                                     ConvertDiagnoser);
15677     if (Converted.isInvalid())
15678       return Converted;
15679     E = Converted.get();
15680     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15681       return ExprError();
15682   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15683     // An ICE must be of integral or unscoped enumeration type.
15684     if (!Diagnoser.Suppress)
15685       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15686     return ExprError();
15687   }
15688 
15689   ExprResult RValueExpr = DefaultLvalueConversion(E);
15690   if (RValueExpr.isInvalid())
15691     return ExprError();
15692 
15693   E = RValueExpr.get();
15694 
15695   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15696   // in the non-ICE case.
15697   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15698     if (Result)
15699       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15700     if (!isa<ConstantExpr>(E))
15701       E = ConstantExpr::Create(Context, E);
15702     return E;
15703   }
15704 
15705   Expr::EvalResult EvalResult;
15706   SmallVector<PartialDiagnosticAt, 8> Notes;
15707   EvalResult.Diag = &Notes;
15708 
15709   // Try to evaluate the expression, and produce diagnostics explaining why it's
15710   // not a constant expression as a side-effect.
15711   bool Folded =
15712       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15713       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15714 
15715   if (!isa<ConstantExpr>(E))
15716     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15717 
15718   // In C++11, we can rely on diagnostics being produced for any expression
15719   // which is not a constant expression. If no diagnostics were produced, then
15720   // this is a constant expression.
15721   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15722     if (Result)
15723       *Result = EvalResult.Val.getInt();
15724     return E;
15725   }
15726 
15727   // If our only note is the usual "invalid subexpression" note, just point
15728   // the caret at its location rather than producing an essentially
15729   // redundant note.
15730   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15731         diag::note_invalid_subexpr_in_const_expr) {
15732     DiagLoc = Notes[0].first;
15733     Notes.clear();
15734   }
15735 
15736   if (!Folded || !AllowFold) {
15737     if (!Diagnoser.Suppress) {
15738       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15739       for (const PartialDiagnosticAt &Note : Notes)
15740         Diag(Note.first, Note.second);
15741     }
15742 
15743     return ExprError();
15744   }
15745 
15746   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15747   for (const PartialDiagnosticAt &Note : Notes)
15748     Diag(Note.first, Note.second);
15749 
15750   if (Result)
15751     *Result = EvalResult.Val.getInt();
15752   return E;
15753 }
15754 
15755 namespace {
15756   // Handle the case where we conclude a expression which we speculatively
15757   // considered to be unevaluated is actually evaluated.
15758   class TransformToPE : public TreeTransform<TransformToPE> {
15759     typedef TreeTransform<TransformToPE> BaseTransform;
15760 
15761   public:
15762     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15763 
15764     // Make sure we redo semantic analysis
15765     bool AlwaysRebuild() { return true; }
15766     bool ReplacingOriginal() { return true; }
15767 
15768     // We need to special-case DeclRefExprs referring to FieldDecls which
15769     // are not part of a member pointer formation; normal TreeTransforming
15770     // doesn't catch this case because of the way we represent them in the AST.
15771     // FIXME: This is a bit ugly; is it really the best way to handle this
15772     // case?
15773     //
15774     // Error on DeclRefExprs referring to FieldDecls.
15775     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15776       if (isa<FieldDecl>(E->getDecl()) &&
15777           !SemaRef.isUnevaluatedContext())
15778         return SemaRef.Diag(E->getLocation(),
15779                             diag::err_invalid_non_static_member_use)
15780             << E->getDecl() << E->getSourceRange();
15781 
15782       return BaseTransform::TransformDeclRefExpr(E);
15783     }
15784 
15785     // Exception: filter out member pointer formation
15786     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15787       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15788         return E;
15789 
15790       return BaseTransform::TransformUnaryOperator(E);
15791     }
15792 
15793     // The body of a lambda-expression is in a separate expression evaluation
15794     // context so never needs to be transformed.
15795     // FIXME: Ideally we wouldn't transform the closure type either, and would
15796     // just recreate the capture expressions and lambda expression.
15797     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15798       return SkipLambdaBody(E, Body);
15799     }
15800   };
15801 }
15802 
15803 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15804   assert(isUnevaluatedContext() &&
15805          "Should only transform unevaluated expressions");
15806   ExprEvalContexts.back().Context =
15807       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15808   if (isUnevaluatedContext())
15809     return E;
15810   return TransformToPE(*this).TransformExpr(E);
15811 }
15812 
15813 void
15814 Sema::PushExpressionEvaluationContext(
15815     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15816     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15817   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15818                                 LambdaContextDecl, ExprContext);
15819   Cleanup.reset();
15820   if (!MaybeODRUseExprs.empty())
15821     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15822 }
15823 
15824 void
15825 Sema::PushExpressionEvaluationContext(
15826     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15827     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15828   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15829   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15830 }
15831 
15832 namespace {
15833 
15834 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15835   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15836   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15837     if (E->getOpcode() == UO_Deref)
15838       return CheckPossibleDeref(S, E->getSubExpr());
15839   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15840     return CheckPossibleDeref(S, E->getBase());
15841   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15842     return CheckPossibleDeref(S, E->getBase());
15843   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15844     QualType Inner;
15845     QualType Ty = E->getType();
15846     if (const auto *Ptr = Ty->getAs<PointerType>())
15847       Inner = Ptr->getPointeeType();
15848     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15849       Inner = Arr->getElementType();
15850     else
15851       return nullptr;
15852 
15853     if (Inner->hasAttr(attr::NoDeref))
15854       return E;
15855   }
15856   return nullptr;
15857 }
15858 
15859 } // namespace
15860 
15861 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15862   for (const Expr *E : Rec.PossibleDerefs) {
15863     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15864     if (DeclRef) {
15865       const ValueDecl *Decl = DeclRef->getDecl();
15866       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15867           << Decl->getName() << E->getSourceRange();
15868       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15869     } else {
15870       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15871           << E->getSourceRange();
15872     }
15873   }
15874   Rec.PossibleDerefs.clear();
15875 }
15876 
15877 /// Check whether E, which is either a discarded-value expression or an
15878 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15879 /// and if so, remove it from the list of volatile-qualified assignments that
15880 /// we are going to warn are deprecated.
15881 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15882   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
15883     return;
15884 
15885   // Note: ignoring parens here is not justified by the standard rules, but
15886   // ignoring parentheses seems like a more reasonable approach, and this only
15887   // drives a deprecation warning so doesn't affect conformance.
15888   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15889     if (BO->getOpcode() == BO_Assign) {
15890       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15891       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15892                  LHSs.end());
15893     }
15894   }
15895 }
15896 
15897 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15898   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15899       RebuildingImmediateInvocation)
15900     return E;
15901 
15902   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15903   /// It's OK if this fails; we'll also remove this in
15904   /// HandleImmediateInvocations, but catching it here allows us to avoid
15905   /// walking the AST looking for it in simple cases.
15906   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15907     if (auto *DeclRef =
15908             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15909       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15910 
15911   E = MaybeCreateExprWithCleanups(E);
15912 
15913   ConstantExpr *Res = ConstantExpr::Create(
15914       getASTContext(), E.get(),
15915       ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15916                                    getASTContext()),
15917       /*IsImmediateInvocation*/ true);
15918   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15919   return Res;
15920 }
15921 
15922 static void EvaluateAndDiagnoseImmediateInvocation(
15923     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15924   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15925   Expr::EvalResult Eval;
15926   Eval.Diag = &Notes;
15927   ConstantExpr *CE = Candidate.getPointer();
15928   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15929                                            SemaRef.getASTContext(), true);
15930   if (!Result || !Notes.empty()) {
15931     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15932     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
15933       InnerExpr = FunctionalCast->getSubExpr();
15934     FunctionDecl *FD = nullptr;
15935     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15936       FD = cast<FunctionDecl>(Call->getCalleeDecl());
15937     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15938       FD = Call->getConstructor();
15939     else
15940       llvm_unreachable("unhandled decl kind");
15941     assert(FD->isConsteval());
15942     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15943     for (auto &Note : Notes)
15944       SemaRef.Diag(Note.first, Note.second);
15945     return;
15946   }
15947   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15948 }
15949 
15950 static void RemoveNestedImmediateInvocation(
15951     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15952     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15953   struct ComplexRemove : TreeTransform<ComplexRemove> {
15954     using Base = TreeTransform<ComplexRemove>;
15955     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15956     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15957     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15958         CurrentII;
15959     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15960                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15961                   SmallVector<Sema::ImmediateInvocationCandidate,
15962                               4>::reverse_iterator Current)
15963         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15964     void RemoveImmediateInvocation(ConstantExpr* E) {
15965       auto It = std::find_if(CurrentII, IISet.rend(),
15966                              [E](Sema::ImmediateInvocationCandidate Elem) {
15967                                return Elem.getPointer() == E;
15968                              });
15969       assert(It != IISet.rend() &&
15970              "ConstantExpr marked IsImmediateInvocation should "
15971              "be present");
15972       It->setInt(1); // Mark as deleted
15973     }
15974     ExprResult TransformConstantExpr(ConstantExpr *E) {
15975       if (!E->isImmediateInvocation())
15976         return Base::TransformConstantExpr(E);
15977       RemoveImmediateInvocation(E);
15978       return Base::TransformExpr(E->getSubExpr());
15979     }
15980     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15981     /// we need to remove its DeclRefExpr from the DRSet.
15982     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15983       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15984       return Base::TransformCXXOperatorCallExpr(E);
15985     }
15986     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15987     /// here.
15988     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15989       if (!Init)
15990         return Init;
15991       /// ConstantExpr are the first layer of implicit node to be removed so if
15992       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15993       if (auto *CE = dyn_cast<ConstantExpr>(Init))
15994         if (CE->isImmediateInvocation())
15995           RemoveImmediateInvocation(CE);
15996       return Base::TransformInitializer(Init, NotCopyInit);
15997     }
15998     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15999       DRSet.erase(E);
16000       return E;
16001     }
16002     bool AlwaysRebuild() { return false; }
16003     bool ReplacingOriginal() { return true; }
16004     bool AllowSkippingCXXConstructExpr() {
16005       bool Res = AllowSkippingFirstCXXConstructExpr;
16006       AllowSkippingFirstCXXConstructExpr = true;
16007       return Res;
16008     }
16009     bool AllowSkippingFirstCXXConstructExpr = true;
16010   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16011                 Rec.ImmediateInvocationCandidates, It);
16012 
16013   /// CXXConstructExpr with a single argument are getting skipped by
16014   /// TreeTransform in some situtation because they could be implicit. This
16015   /// can only occur for the top-level CXXConstructExpr because it is used
16016   /// nowhere in the expression being transformed therefore will not be rebuilt.
16017   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16018   /// skipping the first CXXConstructExpr.
16019   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16020     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16021 
16022   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16023   assert(Res.isUsable());
16024   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16025   It->getPointer()->setSubExpr(Res.get());
16026 }
16027 
16028 static void
16029 HandleImmediateInvocations(Sema &SemaRef,
16030                            Sema::ExpressionEvaluationContextRecord &Rec) {
16031   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16032        Rec.ReferenceToConsteval.size() == 0) ||
16033       SemaRef.RebuildingImmediateInvocation)
16034     return;
16035 
16036   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16037   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16038   /// need to remove ReferenceToConsteval in the immediate invocation.
16039   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16040 
16041     /// Prevent sema calls during the tree transform from adding pointers that
16042     /// are already in the sets.
16043     llvm::SaveAndRestore<bool> DisableIITracking(
16044         SemaRef.RebuildingImmediateInvocation, true);
16045 
16046     /// Prevent diagnostic during tree transfrom as they are duplicates
16047     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16048 
16049     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16050          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16051       if (!It->getInt())
16052         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16053   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16054              Rec.ReferenceToConsteval.size()) {
16055     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16056       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16057       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16058       bool VisitDeclRefExpr(DeclRefExpr *E) {
16059         DRSet.erase(E);
16060         return DRSet.size();
16061       }
16062     } Visitor(Rec.ReferenceToConsteval);
16063     Visitor.TraverseStmt(
16064         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16065   }
16066   for (auto CE : Rec.ImmediateInvocationCandidates)
16067     if (!CE.getInt())
16068       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16069   for (auto DR : Rec.ReferenceToConsteval) {
16070     auto *FD = cast<FunctionDecl>(DR->getDecl());
16071     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16072         << FD;
16073     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16074   }
16075 }
16076 
16077 void Sema::PopExpressionEvaluationContext() {
16078   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16079   unsigned NumTypos = Rec.NumTypos;
16080 
16081   if (!Rec.Lambdas.empty()) {
16082     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16083     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16084         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16085       unsigned D;
16086       if (Rec.isUnevaluated()) {
16087         // C++11 [expr.prim.lambda]p2:
16088         //   A lambda-expression shall not appear in an unevaluated operand
16089         //   (Clause 5).
16090         D = diag::err_lambda_unevaluated_operand;
16091       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16092         // C++1y [expr.const]p2:
16093         //   A conditional-expression e is a core constant expression unless the
16094         //   evaluation of e, following the rules of the abstract machine, would
16095         //   evaluate [...] a lambda-expression.
16096         D = diag::err_lambda_in_constant_expression;
16097       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16098         // C++17 [expr.prim.lamda]p2:
16099         // A lambda-expression shall not appear [...] in a template-argument.
16100         D = diag::err_lambda_in_invalid_context;
16101       } else
16102         llvm_unreachable("Couldn't infer lambda error message.");
16103 
16104       for (const auto *L : Rec.Lambdas)
16105         Diag(L->getBeginLoc(), D);
16106     }
16107   }
16108 
16109   WarnOnPendingNoDerefs(Rec);
16110   HandleImmediateInvocations(*this, Rec);
16111 
16112   // Warn on any volatile-qualified simple-assignments that are not discarded-
16113   // value expressions nor unevaluated operands (those cases get removed from
16114   // this list by CheckUnusedVolatileAssignment).
16115   for (auto *BO : Rec.VolatileAssignmentLHSs)
16116     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16117         << BO->getType();
16118 
16119   // When are coming out of an unevaluated context, clear out any
16120   // temporaries that we may have created as part of the evaluation of
16121   // the expression in that context: they aren't relevant because they
16122   // will never be constructed.
16123   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16124     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16125                              ExprCleanupObjects.end());
16126     Cleanup = Rec.ParentCleanup;
16127     CleanupVarDeclMarking();
16128     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16129   // Otherwise, merge the contexts together.
16130   } else {
16131     Cleanup.mergeFrom(Rec.ParentCleanup);
16132     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16133                             Rec.SavedMaybeODRUseExprs.end());
16134   }
16135 
16136   // Pop the current expression evaluation context off the stack.
16137   ExprEvalContexts.pop_back();
16138 
16139   // The global expression evaluation context record is never popped.
16140   ExprEvalContexts.back().NumTypos += NumTypos;
16141 }
16142 
16143 void Sema::DiscardCleanupsInEvaluationContext() {
16144   ExprCleanupObjects.erase(
16145          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16146          ExprCleanupObjects.end());
16147   Cleanup.reset();
16148   MaybeODRUseExprs.clear();
16149 }
16150 
16151 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16152   ExprResult Result = CheckPlaceholderExpr(E);
16153   if (Result.isInvalid())
16154     return ExprError();
16155   E = Result.get();
16156   if (!E->getType()->isVariablyModifiedType())
16157     return E;
16158   return TransformToPotentiallyEvaluated(E);
16159 }
16160 
16161 /// Are we in a context that is potentially constant evaluated per C++20
16162 /// [expr.const]p12?
16163 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16164   /// C++2a [expr.const]p12:
16165   //   An expression or conversion is potentially constant evaluated if it is
16166   switch (SemaRef.ExprEvalContexts.back().Context) {
16167     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16168       // -- a manifestly constant-evaluated expression,
16169     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16170     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16171     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16172       // -- a potentially-evaluated expression,
16173     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16174       // -- an immediate subexpression of a braced-init-list,
16175 
16176       // -- [FIXME] an expression of the form & cast-expression that occurs
16177       //    within a templated entity
16178       // -- a subexpression of one of the above that is not a subexpression of
16179       // a nested unevaluated operand.
16180       return true;
16181 
16182     case Sema::ExpressionEvaluationContext::Unevaluated:
16183     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16184       // Expressions in this context are never evaluated.
16185       return false;
16186   }
16187   llvm_unreachable("Invalid context");
16188 }
16189 
16190 /// Return true if this function has a calling convention that requires mangling
16191 /// in the size of the parameter pack.
16192 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16193   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16194   // we don't need parameter type sizes.
16195   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16196   if (!TT.isOSWindows() || !TT.isX86())
16197     return false;
16198 
16199   // If this is C++ and this isn't an extern "C" function, parameters do not
16200   // need to be complete. In this case, C++ mangling will apply, which doesn't
16201   // use the size of the parameters.
16202   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16203     return false;
16204 
16205   // Stdcall, fastcall, and vectorcall need this special treatment.
16206   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16207   switch (CC) {
16208   case CC_X86StdCall:
16209   case CC_X86FastCall:
16210   case CC_X86VectorCall:
16211     return true;
16212   default:
16213     break;
16214   }
16215   return false;
16216 }
16217 
16218 /// Require that all of the parameter types of function be complete. Normally,
16219 /// parameter types are only required to be complete when a function is called
16220 /// or defined, but to mangle functions with certain calling conventions, the
16221 /// mangler needs to know the size of the parameter list. In this situation,
16222 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16223 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16224 /// result in a linker error. Clang doesn't implement this behavior, and instead
16225 /// attempts to error at compile time.
16226 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16227                                                   SourceLocation Loc) {
16228   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16229     FunctionDecl *FD;
16230     ParmVarDecl *Param;
16231 
16232   public:
16233     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16234         : FD(FD), Param(Param) {}
16235 
16236     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16237       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16238       StringRef CCName;
16239       switch (CC) {
16240       case CC_X86StdCall:
16241         CCName = "stdcall";
16242         break;
16243       case CC_X86FastCall:
16244         CCName = "fastcall";
16245         break;
16246       case CC_X86VectorCall:
16247         CCName = "vectorcall";
16248         break;
16249       default:
16250         llvm_unreachable("CC does not need mangling");
16251       }
16252 
16253       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16254           << Param->getDeclName() << FD->getDeclName() << CCName;
16255     }
16256   };
16257 
16258   for (ParmVarDecl *Param : FD->parameters()) {
16259     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16260     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16261   }
16262 }
16263 
16264 namespace {
16265 enum class OdrUseContext {
16266   /// Declarations in this context are not odr-used.
16267   None,
16268   /// Declarations in this context are formally odr-used, but this is a
16269   /// dependent context.
16270   Dependent,
16271   /// Declarations in this context are odr-used but not actually used (yet).
16272   FormallyOdrUsed,
16273   /// Declarations in this context are used.
16274   Used
16275 };
16276 }
16277 
16278 /// Are we within a context in which references to resolved functions or to
16279 /// variables result in odr-use?
16280 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16281   OdrUseContext Result;
16282 
16283   switch (SemaRef.ExprEvalContexts.back().Context) {
16284     case Sema::ExpressionEvaluationContext::Unevaluated:
16285     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16286     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16287       return OdrUseContext::None;
16288 
16289     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16290     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16291       Result = OdrUseContext::Used;
16292       break;
16293 
16294     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16295       Result = OdrUseContext::FormallyOdrUsed;
16296       break;
16297 
16298     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16299       // A default argument formally results in odr-use, but doesn't actually
16300       // result in a use in any real sense until it itself is used.
16301       Result = OdrUseContext::FormallyOdrUsed;
16302       break;
16303   }
16304 
16305   if (SemaRef.CurContext->isDependentContext())
16306     return OdrUseContext::Dependent;
16307 
16308   return Result;
16309 }
16310 
16311 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16312   return Func->isConstexpr() &&
16313          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16314 }
16315 
16316 /// Mark a function referenced, and check whether it is odr-used
16317 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16318 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16319                                   bool MightBeOdrUse) {
16320   assert(Func && "No function?");
16321 
16322   Func->setReferenced();
16323 
16324   // Recursive functions aren't really used until they're used from some other
16325   // context.
16326   bool IsRecursiveCall = CurContext == Func;
16327 
16328   // C++11 [basic.def.odr]p3:
16329   //   A function whose name appears as a potentially-evaluated expression is
16330   //   odr-used if it is the unique lookup result or the selected member of a
16331   //   set of overloaded functions [...].
16332   //
16333   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16334   // can just check that here.
16335   OdrUseContext OdrUse =
16336       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16337   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16338     OdrUse = OdrUseContext::FormallyOdrUsed;
16339 
16340   // Trivial default constructors and destructors are never actually used.
16341   // FIXME: What about other special members?
16342   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16343       OdrUse == OdrUseContext::Used) {
16344     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16345       if (Constructor->isDefaultConstructor())
16346         OdrUse = OdrUseContext::FormallyOdrUsed;
16347     if (isa<CXXDestructorDecl>(Func))
16348       OdrUse = OdrUseContext::FormallyOdrUsed;
16349   }
16350 
16351   // C++20 [expr.const]p12:
16352   //   A function [...] is needed for constant evaluation if it is [...] a
16353   //   constexpr function that is named by an expression that is potentially
16354   //   constant evaluated
16355   bool NeededForConstantEvaluation =
16356       isPotentiallyConstantEvaluatedContext(*this) &&
16357       isImplicitlyDefinableConstexprFunction(Func);
16358 
16359   // Determine whether we require a function definition to exist, per
16360   // C++11 [temp.inst]p3:
16361   //   Unless a function template specialization has been explicitly
16362   //   instantiated or explicitly specialized, the function template
16363   //   specialization is implicitly instantiated when the specialization is
16364   //   referenced in a context that requires a function definition to exist.
16365   // C++20 [temp.inst]p7:
16366   //   The existence of a definition of a [...] function is considered to
16367   //   affect the semantics of the program if the [...] function is needed for
16368   //   constant evaluation by an expression
16369   // C++20 [basic.def.odr]p10:
16370   //   Every program shall contain exactly one definition of every non-inline
16371   //   function or variable that is odr-used in that program outside of a
16372   //   discarded statement
16373   // C++20 [special]p1:
16374   //   The implementation will implicitly define [defaulted special members]
16375   //   if they are odr-used or needed for constant evaluation.
16376   //
16377   // Note that we skip the implicit instantiation of templates that are only
16378   // used in unused default arguments or by recursive calls to themselves.
16379   // This is formally non-conforming, but seems reasonable in practice.
16380   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16381                                              NeededForConstantEvaluation);
16382 
16383   // C++14 [temp.expl.spec]p6:
16384   //   If a template [...] is explicitly specialized then that specialization
16385   //   shall be declared before the first use of that specialization that would
16386   //   cause an implicit instantiation to take place, in every translation unit
16387   //   in which such a use occurs
16388   if (NeedDefinition &&
16389       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16390        Func->getMemberSpecializationInfo()))
16391     checkSpecializationVisibility(Loc, Func);
16392 
16393   if (getLangOpts().CUDA)
16394     CheckCUDACall(Loc, Func);
16395 
16396   // If we need a definition, try to create one.
16397   if (NeedDefinition && !Func->getBody()) {
16398     runWithSufficientStackSpace(Loc, [&] {
16399       if (CXXConstructorDecl *Constructor =
16400               dyn_cast<CXXConstructorDecl>(Func)) {
16401         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16402         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16403           if (Constructor->isDefaultConstructor()) {
16404             if (Constructor->isTrivial() &&
16405                 !Constructor->hasAttr<DLLExportAttr>())
16406               return;
16407             DefineImplicitDefaultConstructor(Loc, Constructor);
16408           } else if (Constructor->isCopyConstructor()) {
16409             DefineImplicitCopyConstructor(Loc, Constructor);
16410           } else if (Constructor->isMoveConstructor()) {
16411             DefineImplicitMoveConstructor(Loc, Constructor);
16412           }
16413         } else if (Constructor->getInheritedConstructor()) {
16414           DefineInheritingConstructor(Loc, Constructor);
16415         }
16416       } else if (CXXDestructorDecl *Destructor =
16417                      dyn_cast<CXXDestructorDecl>(Func)) {
16418         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16419         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16420           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16421             return;
16422           DefineImplicitDestructor(Loc, Destructor);
16423         }
16424         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16425           MarkVTableUsed(Loc, Destructor->getParent());
16426       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16427         if (MethodDecl->isOverloadedOperator() &&
16428             MethodDecl->getOverloadedOperator() == OO_Equal) {
16429           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16430           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16431             if (MethodDecl->isCopyAssignmentOperator())
16432               DefineImplicitCopyAssignment(Loc, MethodDecl);
16433             else if (MethodDecl->isMoveAssignmentOperator())
16434               DefineImplicitMoveAssignment(Loc, MethodDecl);
16435           }
16436         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16437                    MethodDecl->getParent()->isLambda()) {
16438           CXXConversionDecl *Conversion =
16439               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16440           if (Conversion->isLambdaToBlockPointerConversion())
16441             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16442           else
16443             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16444         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16445           MarkVTableUsed(Loc, MethodDecl->getParent());
16446       }
16447 
16448       if (Func->isDefaulted() && !Func->isDeleted()) {
16449         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16450         if (DCK != DefaultedComparisonKind::None)
16451           DefineDefaultedComparison(Loc, Func, DCK);
16452       }
16453 
16454       // Implicit instantiation of function templates and member functions of
16455       // class templates.
16456       if (Func->isImplicitlyInstantiable()) {
16457         TemplateSpecializationKind TSK =
16458             Func->getTemplateSpecializationKindForInstantiation();
16459         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16460         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16461         if (FirstInstantiation) {
16462           PointOfInstantiation = Loc;
16463           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16464         } else if (TSK != TSK_ImplicitInstantiation) {
16465           // Use the point of use as the point of instantiation, instead of the
16466           // point of explicit instantiation (which we track as the actual point
16467           // of instantiation). This gives better backtraces in diagnostics.
16468           PointOfInstantiation = Loc;
16469         }
16470 
16471         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16472             Func->isConstexpr()) {
16473           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16474               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16475               CodeSynthesisContexts.size())
16476             PendingLocalImplicitInstantiations.push_back(
16477                 std::make_pair(Func, PointOfInstantiation));
16478           else if (Func->isConstexpr())
16479             // Do not defer instantiations of constexpr functions, to avoid the
16480             // expression evaluator needing to call back into Sema if it sees a
16481             // call to such a function.
16482             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16483           else {
16484             Func->setInstantiationIsPending(true);
16485             PendingInstantiations.push_back(
16486                 std::make_pair(Func, PointOfInstantiation));
16487             // Notify the consumer that a function was implicitly instantiated.
16488             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16489           }
16490         }
16491       } else {
16492         // Walk redefinitions, as some of them may be instantiable.
16493         for (auto i : Func->redecls()) {
16494           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16495             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16496         }
16497       }
16498     });
16499   }
16500 
16501   // C++14 [except.spec]p17:
16502   //   An exception-specification is considered to be needed when:
16503   //   - the function is odr-used or, if it appears in an unevaluated operand,
16504   //     would be odr-used if the expression were potentially-evaluated;
16505   //
16506   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16507   // function is a pure virtual function we're calling, and in that case the
16508   // function was selected by overload resolution and we need to resolve its
16509   // exception specification for a different reason.
16510   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16511   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16512     ResolveExceptionSpec(Loc, FPT);
16513 
16514   // If this is the first "real" use, act on that.
16515   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16516     // Keep track of used but undefined functions.
16517     if (!Func->isDefined()) {
16518       if (mightHaveNonExternalLinkage(Func))
16519         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16520       else if (Func->getMostRecentDecl()->isInlined() &&
16521                !LangOpts.GNUInline &&
16522                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16523         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16524       else if (isExternalWithNoLinkageType(Func))
16525         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16526     }
16527 
16528     // Some x86 Windows calling conventions mangle the size of the parameter
16529     // pack into the name. Computing the size of the parameters requires the
16530     // parameter types to be complete. Check that now.
16531     if (funcHasParameterSizeMangling(*this, Func))
16532       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16533 
16534     // In the MS C++ ABI, the compiler emits destructor variants where they are
16535     // used. If the destructor is used here but defined elsewhere, mark the
16536     // virtual base destructors referenced. If those virtual base destructors
16537     // are inline, this will ensure they are defined when emitting the complete
16538     // destructor variant. This checking may be redundant if the destructor is
16539     // provided later in this TU.
16540     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16541       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16542         CXXRecordDecl *Parent = Dtor->getParent();
16543         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16544           CheckCompleteDestructorVariant(Loc, Dtor);
16545       }
16546     }
16547 
16548     Func->markUsed(Context);
16549   }
16550 }
16551 
16552 /// Directly mark a variable odr-used. Given a choice, prefer to use
16553 /// MarkVariableReferenced since it does additional checks and then
16554 /// calls MarkVarDeclODRUsed.
16555 /// If the variable must be captured:
16556 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16557 ///  - else capture it in the DeclContext that maps to the
16558 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16559 static void
16560 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16561                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16562   // Keep track of used but undefined variables.
16563   // FIXME: We shouldn't suppress this warning for static data members.
16564   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16565       (!Var->isExternallyVisible() || Var->isInline() ||
16566        SemaRef.isExternalWithNoLinkageType(Var)) &&
16567       !(Var->isStaticDataMember() && Var->hasInit())) {
16568     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16569     if (old.isInvalid())
16570       old = Loc;
16571   }
16572   QualType CaptureType, DeclRefType;
16573   if (SemaRef.LangOpts.OpenMP)
16574     SemaRef.tryCaptureOpenMPLambdas(Var);
16575   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16576     /*EllipsisLoc*/ SourceLocation(),
16577     /*BuildAndDiagnose*/ true,
16578     CaptureType, DeclRefType,
16579     FunctionScopeIndexToStopAt);
16580 
16581   Var->markUsed(SemaRef.Context);
16582 }
16583 
16584 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16585                                              SourceLocation Loc,
16586                                              unsigned CapturingScopeIndex) {
16587   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16588 }
16589 
16590 static void
16591 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16592                                    ValueDecl *var, DeclContext *DC) {
16593   DeclContext *VarDC = var->getDeclContext();
16594 
16595   //  If the parameter still belongs to the translation unit, then
16596   //  we're actually just using one parameter in the declaration of
16597   //  the next.
16598   if (isa<ParmVarDecl>(var) &&
16599       isa<TranslationUnitDecl>(VarDC))
16600     return;
16601 
16602   // For C code, don't diagnose about capture if we're not actually in code
16603   // right now; it's impossible to write a non-constant expression outside of
16604   // function context, so we'll get other (more useful) diagnostics later.
16605   //
16606   // For C++, things get a bit more nasty... it would be nice to suppress this
16607   // diagnostic for certain cases like using a local variable in an array bound
16608   // for a member of a local class, but the correct predicate is not obvious.
16609   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16610     return;
16611 
16612   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16613   unsigned ContextKind = 3; // unknown
16614   if (isa<CXXMethodDecl>(VarDC) &&
16615       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16616     ContextKind = 2;
16617   } else if (isa<FunctionDecl>(VarDC)) {
16618     ContextKind = 0;
16619   } else if (isa<BlockDecl>(VarDC)) {
16620     ContextKind = 1;
16621   }
16622 
16623   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16624     << var << ValueKind << ContextKind << VarDC;
16625   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16626       << var;
16627 
16628   // FIXME: Add additional diagnostic info about class etc. which prevents
16629   // capture.
16630 }
16631 
16632 
16633 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16634                                       bool &SubCapturesAreNested,
16635                                       QualType &CaptureType,
16636                                       QualType &DeclRefType) {
16637    // Check whether we've already captured it.
16638   if (CSI->CaptureMap.count(Var)) {
16639     // If we found a capture, any subcaptures are nested.
16640     SubCapturesAreNested = true;
16641 
16642     // Retrieve the capture type for this variable.
16643     CaptureType = CSI->getCapture(Var).getCaptureType();
16644 
16645     // Compute the type of an expression that refers to this variable.
16646     DeclRefType = CaptureType.getNonReferenceType();
16647 
16648     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16649     // are mutable in the sense that user can change their value - they are
16650     // private instances of the captured declarations.
16651     const Capture &Cap = CSI->getCapture(Var);
16652     if (Cap.isCopyCapture() &&
16653         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16654         !(isa<CapturedRegionScopeInfo>(CSI) &&
16655           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16656       DeclRefType.addConst();
16657     return true;
16658   }
16659   return false;
16660 }
16661 
16662 // Only block literals, captured statements, and lambda expressions can
16663 // capture; other scopes don't work.
16664 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16665                                  SourceLocation Loc,
16666                                  const bool Diagnose, Sema &S) {
16667   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16668     return getLambdaAwareParentOfDeclContext(DC);
16669   else if (Var->hasLocalStorage()) {
16670     if (Diagnose)
16671        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16672   }
16673   return nullptr;
16674 }
16675 
16676 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16677 // certain types of variables (unnamed, variably modified types etc.)
16678 // so check for eligibility.
16679 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16680                                  SourceLocation Loc,
16681                                  const bool Diagnose, Sema &S) {
16682 
16683   bool IsBlock = isa<BlockScopeInfo>(CSI);
16684   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16685 
16686   // Lambdas are not allowed to capture unnamed variables
16687   // (e.g. anonymous unions).
16688   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16689   // assuming that's the intent.
16690   if (IsLambda && !Var->getDeclName()) {
16691     if (Diagnose) {
16692       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16693       S.Diag(Var->getLocation(), diag::note_declared_at);
16694     }
16695     return false;
16696   }
16697 
16698   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16699   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16700     if (Diagnose) {
16701       S.Diag(Loc, diag::err_ref_vm_type);
16702       S.Diag(Var->getLocation(), diag::note_previous_decl)
16703         << Var->getDeclName();
16704     }
16705     return false;
16706   }
16707   // Prohibit structs with flexible array members too.
16708   // We cannot capture what is in the tail end of the struct.
16709   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16710     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16711       if (Diagnose) {
16712         if (IsBlock)
16713           S.Diag(Loc, diag::err_ref_flexarray_type);
16714         else
16715           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16716             << Var->getDeclName();
16717         S.Diag(Var->getLocation(), diag::note_previous_decl)
16718           << Var->getDeclName();
16719       }
16720       return false;
16721     }
16722   }
16723   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16724   // Lambdas and captured statements are not allowed to capture __block
16725   // variables; they don't support the expected semantics.
16726   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16727     if (Diagnose) {
16728       S.Diag(Loc, diag::err_capture_block_variable)
16729         << Var->getDeclName() << !IsLambda;
16730       S.Diag(Var->getLocation(), diag::note_previous_decl)
16731         << Var->getDeclName();
16732     }
16733     return false;
16734   }
16735   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16736   if (S.getLangOpts().OpenCL && IsBlock &&
16737       Var->getType()->isBlockPointerType()) {
16738     if (Diagnose)
16739       S.Diag(Loc, diag::err_opencl_block_ref_block);
16740     return false;
16741   }
16742 
16743   return true;
16744 }
16745 
16746 // Returns true if the capture by block was successful.
16747 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16748                                  SourceLocation Loc,
16749                                  const bool BuildAndDiagnose,
16750                                  QualType &CaptureType,
16751                                  QualType &DeclRefType,
16752                                  const bool Nested,
16753                                  Sema &S, bool Invalid) {
16754   bool ByRef = false;
16755 
16756   // Blocks are not allowed to capture arrays, excepting OpenCL.
16757   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16758   // (decayed to pointers).
16759   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16760     if (BuildAndDiagnose) {
16761       S.Diag(Loc, diag::err_ref_array_type);
16762       S.Diag(Var->getLocation(), diag::note_previous_decl)
16763       << Var->getDeclName();
16764       Invalid = true;
16765     } else {
16766       return false;
16767     }
16768   }
16769 
16770   // Forbid the block-capture of autoreleasing variables.
16771   if (!Invalid &&
16772       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16773     if (BuildAndDiagnose) {
16774       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16775         << /*block*/ 0;
16776       S.Diag(Var->getLocation(), diag::note_previous_decl)
16777         << Var->getDeclName();
16778       Invalid = true;
16779     } else {
16780       return false;
16781     }
16782   }
16783 
16784   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16785   if (const auto *PT = CaptureType->getAs<PointerType>()) {
16786     QualType PointeeTy = PT->getPointeeType();
16787 
16788     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16789         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16790         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16791       if (BuildAndDiagnose) {
16792         SourceLocation VarLoc = Var->getLocation();
16793         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16794         S.Diag(VarLoc, diag::note_declare_parameter_strong);
16795       }
16796     }
16797   }
16798 
16799   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16800   if (HasBlocksAttr || CaptureType->isReferenceType() ||
16801       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16802     // Block capture by reference does not change the capture or
16803     // declaration reference types.
16804     ByRef = true;
16805   } else {
16806     // Block capture by copy introduces 'const'.
16807     CaptureType = CaptureType.getNonReferenceType().withConst();
16808     DeclRefType = CaptureType;
16809   }
16810 
16811   // Actually capture the variable.
16812   if (BuildAndDiagnose)
16813     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16814                     CaptureType, Invalid);
16815 
16816   return !Invalid;
16817 }
16818 
16819 
16820 /// Capture the given variable in the captured region.
16821 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16822                                     VarDecl *Var,
16823                                     SourceLocation Loc,
16824                                     const bool BuildAndDiagnose,
16825                                     QualType &CaptureType,
16826                                     QualType &DeclRefType,
16827                                     const bool RefersToCapturedVariable,
16828                                     Sema &S, bool Invalid) {
16829   // By default, capture variables by reference.
16830   bool ByRef = true;
16831   // Using an LValue reference type is consistent with Lambdas (see below).
16832   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16833     if (S.isOpenMPCapturedDecl(Var)) {
16834       bool HasConst = DeclRefType.isConstQualified();
16835       DeclRefType = DeclRefType.getUnqualifiedType();
16836       // Don't lose diagnostics about assignments to const.
16837       if (HasConst)
16838         DeclRefType.addConst();
16839     }
16840     // Do not capture firstprivates in tasks.
16841     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
16842         OMPC_unknown)
16843       return true;
16844     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16845                                     RSI->OpenMPCaptureLevel);
16846   }
16847 
16848   if (ByRef)
16849     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16850   else
16851     CaptureType = DeclRefType;
16852 
16853   // Actually capture the variable.
16854   if (BuildAndDiagnose)
16855     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16856                     Loc, SourceLocation(), CaptureType, Invalid);
16857 
16858   return !Invalid;
16859 }
16860 
16861 /// Capture the given variable in the lambda.
16862 static bool captureInLambda(LambdaScopeInfo *LSI,
16863                             VarDecl *Var,
16864                             SourceLocation Loc,
16865                             const bool BuildAndDiagnose,
16866                             QualType &CaptureType,
16867                             QualType &DeclRefType,
16868                             const bool RefersToCapturedVariable,
16869                             const Sema::TryCaptureKind Kind,
16870                             SourceLocation EllipsisLoc,
16871                             const bool IsTopScope,
16872                             Sema &S, bool Invalid) {
16873   // Determine whether we are capturing by reference or by value.
16874   bool ByRef = false;
16875   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16876     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16877   } else {
16878     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16879   }
16880 
16881   // Compute the type of the field that will capture this variable.
16882   if (ByRef) {
16883     // C++11 [expr.prim.lambda]p15:
16884     //   An entity is captured by reference if it is implicitly or
16885     //   explicitly captured but not captured by copy. It is
16886     //   unspecified whether additional unnamed non-static data
16887     //   members are declared in the closure type for entities
16888     //   captured by reference.
16889     //
16890     // FIXME: It is not clear whether we want to build an lvalue reference
16891     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16892     // to do the former, while EDG does the latter. Core issue 1249 will
16893     // clarify, but for now we follow GCC because it's a more permissive and
16894     // easily defensible position.
16895     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16896   } else {
16897     // C++11 [expr.prim.lambda]p14:
16898     //   For each entity captured by copy, an unnamed non-static
16899     //   data member is declared in the closure type. The
16900     //   declaration order of these members is unspecified. The type
16901     //   of such a data member is the type of the corresponding
16902     //   captured entity if the entity is not a reference to an
16903     //   object, or the referenced type otherwise. [Note: If the
16904     //   captured entity is a reference to a function, the
16905     //   corresponding data member is also a reference to a
16906     //   function. - end note ]
16907     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16908       if (!RefType->getPointeeType()->isFunctionType())
16909         CaptureType = RefType->getPointeeType();
16910     }
16911 
16912     // Forbid the lambda copy-capture of autoreleasing variables.
16913     if (!Invalid &&
16914         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16915       if (BuildAndDiagnose) {
16916         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16917         S.Diag(Var->getLocation(), diag::note_previous_decl)
16918           << Var->getDeclName();
16919         Invalid = true;
16920       } else {
16921         return false;
16922       }
16923     }
16924 
16925     // Make sure that by-copy captures are of a complete and non-abstract type.
16926     if (!Invalid && BuildAndDiagnose) {
16927       if (!CaptureType->isDependentType() &&
16928           S.RequireCompleteSizedType(
16929               Loc, CaptureType,
16930               diag::err_capture_of_incomplete_or_sizeless_type,
16931               Var->getDeclName()))
16932         Invalid = true;
16933       else if (S.RequireNonAbstractType(Loc, CaptureType,
16934                                         diag::err_capture_of_abstract_type))
16935         Invalid = true;
16936     }
16937   }
16938 
16939   // Compute the type of a reference to this captured variable.
16940   if (ByRef)
16941     DeclRefType = CaptureType.getNonReferenceType();
16942   else {
16943     // C++ [expr.prim.lambda]p5:
16944     //   The closure type for a lambda-expression has a public inline
16945     //   function call operator [...]. This function call operator is
16946     //   declared const (9.3.1) if and only if the lambda-expression's
16947     //   parameter-declaration-clause is not followed by mutable.
16948     DeclRefType = CaptureType.getNonReferenceType();
16949     if (!LSI->Mutable && !CaptureType->isReferenceType())
16950       DeclRefType.addConst();
16951   }
16952 
16953   // Add the capture.
16954   if (BuildAndDiagnose)
16955     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16956                     Loc, EllipsisLoc, CaptureType, Invalid);
16957 
16958   return !Invalid;
16959 }
16960 
16961 bool Sema::tryCaptureVariable(
16962     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16963     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16964     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16965   // An init-capture is notionally from the context surrounding its
16966   // declaration, but its parent DC is the lambda class.
16967   DeclContext *VarDC = Var->getDeclContext();
16968   if (Var->isInitCapture())
16969     VarDC = VarDC->getParent();
16970 
16971   DeclContext *DC = CurContext;
16972   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16973       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16974   // We need to sync up the Declaration Context with the
16975   // FunctionScopeIndexToStopAt
16976   if (FunctionScopeIndexToStopAt) {
16977     unsigned FSIndex = FunctionScopes.size() - 1;
16978     while (FSIndex != MaxFunctionScopesIndex) {
16979       DC = getLambdaAwareParentOfDeclContext(DC);
16980       --FSIndex;
16981     }
16982   }
16983 
16984 
16985   // If the variable is declared in the current context, there is no need to
16986   // capture it.
16987   if (VarDC == DC) return true;
16988 
16989   // Capture global variables if it is required to use private copy of this
16990   // variable.
16991   bool IsGlobal = !Var->hasLocalStorage();
16992   if (IsGlobal &&
16993       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16994                                                 MaxFunctionScopesIndex)))
16995     return true;
16996   Var = Var->getCanonicalDecl();
16997 
16998   // Walk up the stack to determine whether we can capture the variable,
16999   // performing the "simple" checks that don't depend on type. We stop when
17000   // we've either hit the declared scope of the variable or find an existing
17001   // capture of that variable.  We start from the innermost capturing-entity
17002   // (the DC) and ensure that all intervening capturing-entities
17003   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17004   // declcontext can either capture the variable or have already captured
17005   // the variable.
17006   CaptureType = Var->getType();
17007   DeclRefType = CaptureType.getNonReferenceType();
17008   bool Nested = false;
17009   bool Explicit = (Kind != TryCapture_Implicit);
17010   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17011   do {
17012     // Only block literals, captured statements, and lambda expressions can
17013     // capture; other scopes don't work.
17014     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17015                                                               ExprLoc,
17016                                                               BuildAndDiagnose,
17017                                                               *this);
17018     // We need to check for the parent *first* because, if we *have*
17019     // private-captured a global variable, we need to recursively capture it in
17020     // intermediate blocks, lambdas, etc.
17021     if (!ParentDC) {
17022       if (IsGlobal) {
17023         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17024         break;
17025       }
17026       return true;
17027     }
17028 
17029     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17030     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17031 
17032 
17033     // Check whether we've already captured it.
17034     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17035                                              DeclRefType)) {
17036       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17037       break;
17038     }
17039     // If we are instantiating a generic lambda call operator body,
17040     // we do not want to capture new variables.  What was captured
17041     // during either a lambdas transformation or initial parsing
17042     // should be used.
17043     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17044       if (BuildAndDiagnose) {
17045         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17046         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17047           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17048           Diag(Var->getLocation(), diag::note_previous_decl)
17049              << Var->getDeclName();
17050           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17051         } else
17052           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17053       }
17054       return true;
17055     }
17056 
17057     // Try to capture variable-length arrays types.
17058     if (Var->getType()->isVariablyModifiedType()) {
17059       // We're going to walk down into the type and look for VLA
17060       // expressions.
17061       QualType QTy = Var->getType();
17062       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17063         QTy = PVD->getOriginalType();
17064       captureVariablyModifiedType(Context, QTy, CSI);
17065     }
17066 
17067     if (getLangOpts().OpenMP) {
17068       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17069         // OpenMP private variables should not be captured in outer scope, so
17070         // just break here. Similarly, global variables that are captured in a
17071         // target region should not be captured outside the scope of the region.
17072         if (RSI->CapRegionKind == CR_OpenMP) {
17073           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17074               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17075           // If the variable is private (i.e. not captured) and has variably
17076           // modified type, we still need to capture the type for correct
17077           // codegen in all regions, associated with the construct. Currently,
17078           // it is captured in the innermost captured region only.
17079           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17080               Var->getType()->isVariablyModifiedType()) {
17081             QualType QTy = Var->getType();
17082             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17083               QTy = PVD->getOriginalType();
17084             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17085                  I < E; ++I) {
17086               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17087                   FunctionScopes[FunctionScopesIndex - I]);
17088               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17089                      "Wrong number of captured regions associated with the "
17090                      "OpenMP construct.");
17091               captureVariablyModifiedType(Context, QTy, OuterRSI);
17092             }
17093           }
17094           bool IsTargetCap =
17095               IsOpenMPPrivateDecl != OMPC_private &&
17096               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17097                                          RSI->OpenMPCaptureLevel);
17098           // Do not capture global if it is not privatized in outer regions.
17099           bool IsGlobalCap =
17100               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17101                                                      RSI->OpenMPCaptureLevel);
17102 
17103           // When we detect target captures we are looking from inside the
17104           // target region, therefore we need to propagate the capture from the
17105           // enclosing region. Therefore, the capture is not initially nested.
17106           if (IsTargetCap)
17107             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17108 
17109           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17110               (IsGlobal && !IsGlobalCap)) {
17111             Nested = !IsTargetCap;
17112             DeclRefType = DeclRefType.getUnqualifiedType();
17113             CaptureType = Context.getLValueReferenceType(DeclRefType);
17114             break;
17115           }
17116         }
17117       }
17118     }
17119     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17120       // No capture-default, and this is not an explicit capture
17121       // so cannot capture this variable.
17122       if (BuildAndDiagnose) {
17123         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17124         Diag(Var->getLocation(), diag::note_previous_decl)
17125           << Var->getDeclName();
17126         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17127           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17128                diag::note_lambda_decl);
17129         // FIXME: If we error out because an outer lambda can not implicitly
17130         // capture a variable that an inner lambda explicitly captures, we
17131         // should have the inner lambda do the explicit capture - because
17132         // it makes for cleaner diagnostics later.  This would purely be done
17133         // so that the diagnostic does not misleadingly claim that a variable
17134         // can not be captured by a lambda implicitly even though it is captured
17135         // explicitly.  Suggestion:
17136         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17137         //    at the function head
17138         //  - cache the StartingDeclContext - this must be a lambda
17139         //  - captureInLambda in the innermost lambda the variable.
17140       }
17141       return true;
17142     }
17143 
17144     FunctionScopesIndex--;
17145     DC = ParentDC;
17146     Explicit = false;
17147   } while (!VarDC->Equals(DC));
17148 
17149   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17150   // computing the type of the capture at each step, checking type-specific
17151   // requirements, and adding captures if requested.
17152   // If the variable had already been captured previously, we start capturing
17153   // at the lambda nested within that one.
17154   bool Invalid = false;
17155   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17156        ++I) {
17157     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17158 
17159     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17160     // certain types of variables (unnamed, variably modified types etc.)
17161     // so check for eligibility.
17162     if (!Invalid)
17163       Invalid =
17164           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17165 
17166     // After encountering an error, if we're actually supposed to capture, keep
17167     // capturing in nested contexts to suppress any follow-on diagnostics.
17168     if (Invalid && !BuildAndDiagnose)
17169       return true;
17170 
17171     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17172       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17173                                DeclRefType, Nested, *this, Invalid);
17174       Nested = true;
17175     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17176       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17177                                          CaptureType, DeclRefType, Nested,
17178                                          *this, Invalid);
17179       Nested = true;
17180     } else {
17181       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17182       Invalid =
17183           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17184                            DeclRefType, Nested, Kind, EllipsisLoc,
17185                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17186       Nested = true;
17187     }
17188 
17189     if (Invalid && !BuildAndDiagnose)
17190       return true;
17191   }
17192   return Invalid;
17193 }
17194 
17195 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17196                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17197   QualType CaptureType;
17198   QualType DeclRefType;
17199   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17200                             /*BuildAndDiagnose=*/true, CaptureType,
17201                             DeclRefType, nullptr);
17202 }
17203 
17204 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17205   QualType CaptureType;
17206   QualType DeclRefType;
17207   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17208                              /*BuildAndDiagnose=*/false, CaptureType,
17209                              DeclRefType, nullptr);
17210 }
17211 
17212 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17213   QualType CaptureType;
17214   QualType DeclRefType;
17215 
17216   // Determine whether we can capture this variable.
17217   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17218                          /*BuildAndDiagnose=*/false, CaptureType,
17219                          DeclRefType, nullptr))
17220     return QualType();
17221 
17222   return DeclRefType;
17223 }
17224 
17225 namespace {
17226 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17227 // The produced TemplateArgumentListInfo* points to data stored within this
17228 // object, so should only be used in contexts where the pointer will not be
17229 // used after the CopiedTemplateArgs object is destroyed.
17230 class CopiedTemplateArgs {
17231   bool HasArgs;
17232   TemplateArgumentListInfo TemplateArgStorage;
17233 public:
17234   template<typename RefExpr>
17235   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17236     if (HasArgs)
17237       E->copyTemplateArgumentsInto(TemplateArgStorage);
17238   }
17239   operator TemplateArgumentListInfo*()
17240 #ifdef __has_cpp_attribute
17241 #if __has_cpp_attribute(clang::lifetimebound)
17242   [[clang::lifetimebound]]
17243 #endif
17244 #endif
17245   {
17246     return HasArgs ? &TemplateArgStorage : nullptr;
17247   }
17248 };
17249 }
17250 
17251 /// Walk the set of potential results of an expression and mark them all as
17252 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17253 ///
17254 /// \return A new expression if we found any potential results, ExprEmpty() if
17255 ///         not, and ExprError() if we diagnosed an error.
17256 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17257                                                       NonOdrUseReason NOUR) {
17258   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17259   // an object that satisfies the requirements for appearing in a
17260   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17261   // is immediately applied."  This function handles the lvalue-to-rvalue
17262   // conversion part.
17263   //
17264   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17265   // transform it into the relevant kind of non-odr-use node and rebuild the
17266   // tree of nodes leading to it.
17267   //
17268   // This is a mini-TreeTransform that only transforms a restricted subset of
17269   // nodes (and only certain operands of them).
17270 
17271   // Rebuild a subexpression.
17272   auto Rebuild = [&](Expr *Sub) {
17273     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17274   };
17275 
17276   // Check whether a potential result satisfies the requirements of NOUR.
17277   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17278     // Any entity other than a VarDecl is always odr-used whenever it's named
17279     // in a potentially-evaluated expression.
17280     auto *VD = dyn_cast<VarDecl>(D);
17281     if (!VD)
17282       return true;
17283 
17284     // C++2a [basic.def.odr]p4:
17285     //   A variable x whose name appears as a potentially-evalauted expression
17286     //   e is odr-used by e unless
17287     //   -- x is a reference that is usable in constant expressions, or
17288     //   -- x is a variable of non-reference type that is usable in constant
17289     //      expressions and has no mutable subobjects, and e is an element of
17290     //      the set of potential results of an expression of
17291     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17292     //      conversion is applied, or
17293     //   -- x is a variable of non-reference type, and e is an element of the
17294     //      set of potential results of a discarded-value expression to which
17295     //      the lvalue-to-rvalue conversion is not applied
17296     //
17297     // We check the first bullet and the "potentially-evaluated" condition in
17298     // BuildDeclRefExpr. We check the type requirements in the second bullet
17299     // in CheckLValueToRValueConversionOperand below.
17300     switch (NOUR) {
17301     case NOUR_None:
17302     case NOUR_Unevaluated:
17303       llvm_unreachable("unexpected non-odr-use-reason");
17304 
17305     case NOUR_Constant:
17306       // Constant references were handled when they were built.
17307       if (VD->getType()->isReferenceType())
17308         return true;
17309       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17310         if (RD->hasMutableFields())
17311           return true;
17312       if (!VD->isUsableInConstantExpressions(S.Context))
17313         return true;
17314       break;
17315 
17316     case NOUR_Discarded:
17317       if (VD->getType()->isReferenceType())
17318         return true;
17319       break;
17320     }
17321     return false;
17322   };
17323 
17324   // Mark that this expression does not constitute an odr-use.
17325   auto MarkNotOdrUsed = [&] {
17326     S.MaybeODRUseExprs.erase(E);
17327     if (LambdaScopeInfo *LSI = S.getCurLambda())
17328       LSI->markVariableExprAsNonODRUsed(E);
17329   };
17330 
17331   // C++2a [basic.def.odr]p2:
17332   //   The set of potential results of an expression e is defined as follows:
17333   switch (E->getStmtClass()) {
17334   //   -- If e is an id-expression, ...
17335   case Expr::DeclRefExprClass: {
17336     auto *DRE = cast<DeclRefExpr>(E);
17337     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17338       break;
17339 
17340     // Rebuild as a non-odr-use DeclRefExpr.
17341     MarkNotOdrUsed();
17342     return DeclRefExpr::Create(
17343         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17344         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17345         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17346         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17347   }
17348 
17349   case Expr::FunctionParmPackExprClass: {
17350     auto *FPPE = cast<FunctionParmPackExpr>(E);
17351     // If any of the declarations in the pack is odr-used, then the expression
17352     // as a whole constitutes an odr-use.
17353     for (VarDecl *D : *FPPE)
17354       if (IsPotentialResultOdrUsed(D))
17355         return ExprEmpty();
17356 
17357     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17358     // nothing cares about whether we marked this as an odr-use, but it might
17359     // be useful for non-compiler tools.
17360     MarkNotOdrUsed();
17361     break;
17362   }
17363 
17364   //   -- If e is a subscripting operation with an array operand...
17365   case Expr::ArraySubscriptExprClass: {
17366     auto *ASE = cast<ArraySubscriptExpr>(E);
17367     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17368     if (!OldBase->getType()->isArrayType())
17369       break;
17370     ExprResult Base = Rebuild(OldBase);
17371     if (!Base.isUsable())
17372       return Base;
17373     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17374     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17375     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17376     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17377                                      ASE->getRBracketLoc());
17378   }
17379 
17380   case Expr::MemberExprClass: {
17381     auto *ME = cast<MemberExpr>(E);
17382     // -- If e is a class member access expression [...] naming a non-static
17383     //    data member...
17384     if (isa<FieldDecl>(ME->getMemberDecl())) {
17385       ExprResult Base = Rebuild(ME->getBase());
17386       if (!Base.isUsable())
17387         return Base;
17388       return MemberExpr::Create(
17389           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17390           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17391           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17392           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17393           ME->getObjectKind(), ME->isNonOdrUse());
17394     }
17395 
17396     if (ME->getMemberDecl()->isCXXInstanceMember())
17397       break;
17398 
17399     // -- If e is a class member access expression naming a static data member,
17400     //    ...
17401     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17402       break;
17403 
17404     // Rebuild as a non-odr-use MemberExpr.
17405     MarkNotOdrUsed();
17406     return MemberExpr::Create(
17407         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17408         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17409         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17410         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17411     return ExprEmpty();
17412   }
17413 
17414   case Expr::BinaryOperatorClass: {
17415     auto *BO = cast<BinaryOperator>(E);
17416     Expr *LHS = BO->getLHS();
17417     Expr *RHS = BO->getRHS();
17418     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17419     if (BO->getOpcode() == BO_PtrMemD) {
17420       ExprResult Sub = Rebuild(LHS);
17421       if (!Sub.isUsable())
17422         return Sub;
17423       LHS = Sub.get();
17424     //   -- If e is a comma expression, ...
17425     } else if (BO->getOpcode() == BO_Comma) {
17426       ExprResult Sub = Rebuild(RHS);
17427       if (!Sub.isUsable())
17428         return Sub;
17429       RHS = Sub.get();
17430     } else {
17431       break;
17432     }
17433     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17434                         LHS, RHS);
17435   }
17436 
17437   //   -- If e has the form (e1)...
17438   case Expr::ParenExprClass: {
17439     auto *PE = cast<ParenExpr>(E);
17440     ExprResult Sub = Rebuild(PE->getSubExpr());
17441     if (!Sub.isUsable())
17442       return Sub;
17443     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17444   }
17445 
17446   //   -- If e is a glvalue conditional expression, ...
17447   // We don't apply this to a binary conditional operator. FIXME: Should we?
17448   case Expr::ConditionalOperatorClass: {
17449     auto *CO = cast<ConditionalOperator>(E);
17450     ExprResult LHS = Rebuild(CO->getLHS());
17451     if (LHS.isInvalid())
17452       return ExprError();
17453     ExprResult RHS = Rebuild(CO->getRHS());
17454     if (RHS.isInvalid())
17455       return ExprError();
17456     if (!LHS.isUsable() && !RHS.isUsable())
17457       return ExprEmpty();
17458     if (!LHS.isUsable())
17459       LHS = CO->getLHS();
17460     if (!RHS.isUsable())
17461       RHS = CO->getRHS();
17462     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17463                                 CO->getCond(), LHS.get(), RHS.get());
17464   }
17465 
17466   // [Clang extension]
17467   //   -- If e has the form __extension__ e1...
17468   case Expr::UnaryOperatorClass: {
17469     auto *UO = cast<UnaryOperator>(E);
17470     if (UO->getOpcode() != UO_Extension)
17471       break;
17472     ExprResult Sub = Rebuild(UO->getSubExpr());
17473     if (!Sub.isUsable())
17474       return Sub;
17475     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17476                           Sub.get());
17477   }
17478 
17479   // [Clang extension]
17480   //   -- If e has the form _Generic(...), the set of potential results is the
17481   //      union of the sets of potential results of the associated expressions.
17482   case Expr::GenericSelectionExprClass: {
17483     auto *GSE = cast<GenericSelectionExpr>(E);
17484 
17485     SmallVector<Expr *, 4> AssocExprs;
17486     bool AnyChanged = false;
17487     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17488       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17489       if (AssocExpr.isInvalid())
17490         return ExprError();
17491       if (AssocExpr.isUsable()) {
17492         AssocExprs.push_back(AssocExpr.get());
17493         AnyChanged = true;
17494       } else {
17495         AssocExprs.push_back(OrigAssocExpr);
17496       }
17497     }
17498 
17499     return AnyChanged ? S.CreateGenericSelectionExpr(
17500                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17501                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17502                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17503                       : ExprEmpty();
17504   }
17505 
17506   // [Clang extension]
17507   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17508   //      results is the union of the sets of potential results of the
17509   //      second and third subexpressions.
17510   case Expr::ChooseExprClass: {
17511     auto *CE = cast<ChooseExpr>(E);
17512 
17513     ExprResult LHS = Rebuild(CE->getLHS());
17514     if (LHS.isInvalid())
17515       return ExprError();
17516 
17517     ExprResult RHS = Rebuild(CE->getLHS());
17518     if (RHS.isInvalid())
17519       return ExprError();
17520 
17521     if (!LHS.get() && !RHS.get())
17522       return ExprEmpty();
17523     if (!LHS.isUsable())
17524       LHS = CE->getLHS();
17525     if (!RHS.isUsable())
17526       RHS = CE->getRHS();
17527 
17528     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17529                              RHS.get(), CE->getRParenLoc());
17530   }
17531 
17532   // Step through non-syntactic nodes.
17533   case Expr::ConstantExprClass: {
17534     auto *CE = cast<ConstantExpr>(E);
17535     ExprResult Sub = Rebuild(CE->getSubExpr());
17536     if (!Sub.isUsable())
17537       return Sub;
17538     return ConstantExpr::Create(S.Context, Sub.get());
17539   }
17540 
17541   // We could mostly rely on the recursive rebuilding to rebuild implicit
17542   // casts, but not at the top level, so rebuild them here.
17543   case Expr::ImplicitCastExprClass: {
17544     auto *ICE = cast<ImplicitCastExpr>(E);
17545     // Only step through the narrow set of cast kinds we expect to encounter.
17546     // Anything else suggests we've left the region in which potential results
17547     // can be found.
17548     switch (ICE->getCastKind()) {
17549     case CK_NoOp:
17550     case CK_DerivedToBase:
17551     case CK_UncheckedDerivedToBase: {
17552       ExprResult Sub = Rebuild(ICE->getSubExpr());
17553       if (!Sub.isUsable())
17554         return Sub;
17555       CXXCastPath Path(ICE->path());
17556       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17557                                  ICE->getValueKind(), &Path);
17558     }
17559 
17560     default:
17561       break;
17562     }
17563     break;
17564   }
17565 
17566   default:
17567     break;
17568   }
17569 
17570   // Can't traverse through this node. Nothing to do.
17571   return ExprEmpty();
17572 }
17573 
17574 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17575   // Check whether the operand is or contains an object of non-trivial C union
17576   // type.
17577   if (E->getType().isVolatileQualified() &&
17578       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17579        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17580     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17581                           Sema::NTCUC_LValueToRValueVolatile,
17582                           NTCUK_Destruct|NTCUK_Copy);
17583 
17584   // C++2a [basic.def.odr]p4:
17585   //   [...] an expression of non-volatile-qualified non-class type to which
17586   //   the lvalue-to-rvalue conversion is applied [...]
17587   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17588     return E;
17589 
17590   ExprResult Result =
17591       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17592   if (Result.isInvalid())
17593     return ExprError();
17594   return Result.get() ? Result : E;
17595 }
17596 
17597 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17598   Res = CorrectDelayedTyposInExpr(Res);
17599 
17600   if (!Res.isUsable())
17601     return Res;
17602 
17603   // If a constant-expression is a reference to a variable where we delay
17604   // deciding whether it is an odr-use, just assume we will apply the
17605   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17606   // (a non-type template argument), we have special handling anyway.
17607   return CheckLValueToRValueConversionOperand(Res.get());
17608 }
17609 
17610 void Sema::CleanupVarDeclMarking() {
17611   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17612   // call.
17613   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17614   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17615 
17616   for (Expr *E : LocalMaybeODRUseExprs) {
17617     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17618       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17619                          DRE->getLocation(), *this);
17620     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17621       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17622                          *this);
17623     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17624       for (VarDecl *VD : *FP)
17625         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17626     } else {
17627       llvm_unreachable("Unexpected expression");
17628     }
17629   }
17630 
17631   assert(MaybeODRUseExprs.empty() &&
17632          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17633 }
17634 
17635 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17636                                     VarDecl *Var, Expr *E) {
17637   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17638           isa<FunctionParmPackExpr>(E)) &&
17639          "Invalid Expr argument to DoMarkVarDeclReferenced");
17640   Var->setReferenced();
17641 
17642   if (Var->isInvalidDecl())
17643     return;
17644 
17645   auto *MSI = Var->getMemberSpecializationInfo();
17646   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17647                                        : Var->getTemplateSpecializationKind();
17648 
17649   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17650   bool UsableInConstantExpr =
17651       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17652 
17653   // C++20 [expr.const]p12:
17654   //   A variable [...] is needed for constant evaluation if it is [...] a
17655   //   variable whose name appears as a potentially constant evaluated
17656   //   expression that is either a contexpr variable or is of non-volatile
17657   //   const-qualified integral type or of reference type
17658   bool NeededForConstantEvaluation =
17659       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17660 
17661   bool NeedDefinition =
17662       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17663 
17664   VarTemplateSpecializationDecl *VarSpec =
17665       dyn_cast<VarTemplateSpecializationDecl>(Var);
17666   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17667          "Can't instantiate a partial template specialization.");
17668 
17669   // If this might be a member specialization of a static data member, check
17670   // the specialization is visible. We already did the checks for variable
17671   // template specializations when we created them.
17672   if (NeedDefinition && TSK != TSK_Undeclared &&
17673       !isa<VarTemplateSpecializationDecl>(Var))
17674     SemaRef.checkSpecializationVisibility(Loc, Var);
17675 
17676   // Perform implicit instantiation of static data members, static data member
17677   // templates of class templates, and variable template specializations. Delay
17678   // instantiations of variable templates, except for those that could be used
17679   // in a constant expression.
17680   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17681     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17682     // instantiation declaration if a variable is usable in a constant
17683     // expression (among other cases).
17684     bool TryInstantiating =
17685         TSK == TSK_ImplicitInstantiation ||
17686         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17687 
17688     if (TryInstantiating) {
17689       SourceLocation PointOfInstantiation =
17690           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17691       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17692       if (FirstInstantiation) {
17693         PointOfInstantiation = Loc;
17694         if (MSI)
17695           MSI->setPointOfInstantiation(PointOfInstantiation);
17696         else
17697           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17698       }
17699 
17700       bool InstantiationDependent = false;
17701       bool IsNonDependent =
17702           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17703                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17704                   : true;
17705 
17706       // Do not instantiate specializations that are still type-dependent.
17707       if (IsNonDependent) {
17708         if (UsableInConstantExpr) {
17709           // Do not defer instantiations of variables that could be used in a
17710           // constant expression.
17711           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17712             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17713           });
17714         } else if (FirstInstantiation ||
17715                    isa<VarTemplateSpecializationDecl>(Var)) {
17716           // FIXME: For a specialization of a variable template, we don't
17717           // distinguish between "declaration and type implicitly instantiated"
17718           // and "implicit instantiation of definition requested", so we have
17719           // no direct way to avoid enqueueing the pending instantiation
17720           // multiple times.
17721           SemaRef.PendingInstantiations
17722               .push_back(std::make_pair(Var, PointOfInstantiation));
17723         }
17724       }
17725     }
17726   }
17727 
17728   // C++2a [basic.def.odr]p4:
17729   //   A variable x whose name appears as a potentially-evaluated expression e
17730   //   is odr-used by e unless
17731   //   -- x is a reference that is usable in constant expressions
17732   //   -- x is a variable of non-reference type that is usable in constant
17733   //      expressions and has no mutable subobjects [FIXME], and e is an
17734   //      element of the set of potential results of an expression of
17735   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17736   //      conversion is applied
17737   //   -- x is a variable of non-reference type, and e is an element of the set
17738   //      of potential results of a discarded-value expression to which the
17739   //      lvalue-to-rvalue conversion is not applied [FIXME]
17740   //
17741   // We check the first part of the second bullet here, and
17742   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17743   // FIXME: To get the third bullet right, we need to delay this even for
17744   // variables that are not usable in constant expressions.
17745 
17746   // If we already know this isn't an odr-use, there's nothing more to do.
17747   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17748     if (DRE->isNonOdrUse())
17749       return;
17750   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17751     if (ME->isNonOdrUse())
17752       return;
17753 
17754   switch (OdrUse) {
17755   case OdrUseContext::None:
17756     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17757            "missing non-odr-use marking for unevaluated decl ref");
17758     break;
17759 
17760   case OdrUseContext::FormallyOdrUsed:
17761     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17762     // behavior.
17763     break;
17764 
17765   case OdrUseContext::Used:
17766     // If we might later find that this expression isn't actually an odr-use,
17767     // delay the marking.
17768     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17769       SemaRef.MaybeODRUseExprs.insert(E);
17770     else
17771       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17772     break;
17773 
17774   case OdrUseContext::Dependent:
17775     // If this is a dependent context, we don't need to mark variables as
17776     // odr-used, but we may still need to track them for lambda capture.
17777     // FIXME: Do we also need to do this inside dependent typeid expressions
17778     // (which are modeled as unevaluated at this point)?
17779     const bool RefersToEnclosingScope =
17780         (SemaRef.CurContext != Var->getDeclContext() &&
17781          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17782     if (RefersToEnclosingScope) {
17783       LambdaScopeInfo *const LSI =
17784           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17785       if (LSI && (!LSI->CallOperator ||
17786                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17787         // If a variable could potentially be odr-used, defer marking it so
17788         // until we finish analyzing the full expression for any
17789         // lvalue-to-rvalue
17790         // or discarded value conversions that would obviate odr-use.
17791         // Add it to the list of potential captures that will be analyzed
17792         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17793         // unless the variable is a reference that was initialized by a constant
17794         // expression (this will never need to be captured or odr-used).
17795         //
17796         // FIXME: We can simplify this a lot after implementing P0588R1.
17797         assert(E && "Capture variable should be used in an expression.");
17798         if (!Var->getType()->isReferenceType() ||
17799             !Var->isUsableInConstantExpressions(SemaRef.Context))
17800           LSI->addPotentialCapture(E->IgnoreParens());
17801       }
17802     }
17803     break;
17804   }
17805 }
17806 
17807 /// Mark a variable referenced, and check whether it is odr-used
17808 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
17809 /// used directly for normal expressions referring to VarDecl.
17810 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17811   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17812 }
17813 
17814 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17815                                Decl *D, Expr *E, bool MightBeOdrUse) {
17816   if (SemaRef.isInOpenMPDeclareTargetContext())
17817     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17818 
17819   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17820     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17821     return;
17822   }
17823 
17824   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17825 
17826   // If this is a call to a method via a cast, also mark the method in the
17827   // derived class used in case codegen can devirtualize the call.
17828   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17829   if (!ME)
17830     return;
17831   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17832   if (!MD)
17833     return;
17834   // Only attempt to devirtualize if this is truly a virtual call.
17835   bool IsVirtualCall = MD->isVirtual() &&
17836                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
17837   if (!IsVirtualCall)
17838     return;
17839 
17840   // If it's possible to devirtualize the call, mark the called function
17841   // referenced.
17842   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17843       ME->getBase(), SemaRef.getLangOpts().AppleKext);
17844   if (DM)
17845     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17846 }
17847 
17848 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17849 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17850   // TODO: update this with DR# once a defect report is filed.
17851   // C++11 defect. The address of a pure member should not be an ODR use, even
17852   // if it's a qualified reference.
17853   bool OdrUse = true;
17854   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17855     if (Method->isVirtual() &&
17856         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17857       OdrUse = false;
17858 
17859   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17860     if (!isConstantEvaluated() && FD->isConsteval() &&
17861         !RebuildingImmediateInvocation)
17862       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17863   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17864 }
17865 
17866 /// Perform reference-marking and odr-use handling for a MemberExpr.
17867 void Sema::MarkMemberReferenced(MemberExpr *E) {
17868   // C++11 [basic.def.odr]p2:
17869   //   A non-overloaded function whose name appears as a potentially-evaluated
17870   //   expression or a member of a set of candidate functions, if selected by
17871   //   overload resolution when referred to from a potentially-evaluated
17872   //   expression, is odr-used, unless it is a pure virtual function and its
17873   //   name is not explicitly qualified.
17874   bool MightBeOdrUse = true;
17875   if (E->performsVirtualDispatch(getLangOpts())) {
17876     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17877       if (Method->isPure())
17878         MightBeOdrUse = false;
17879   }
17880   SourceLocation Loc =
17881       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17882   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17883 }
17884 
17885 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17886 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17887   for (VarDecl *VD : *E)
17888     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17889 }
17890 
17891 /// Perform marking for a reference to an arbitrary declaration.  It
17892 /// marks the declaration referenced, and performs odr-use checking for
17893 /// functions and variables. This method should not be used when building a
17894 /// normal expression which refers to a variable.
17895 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17896                                  bool MightBeOdrUse) {
17897   if (MightBeOdrUse) {
17898     if (auto *VD = dyn_cast<VarDecl>(D)) {
17899       MarkVariableReferenced(Loc, VD);
17900       return;
17901     }
17902   }
17903   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17904     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17905     return;
17906   }
17907   D->setReferenced();
17908 }
17909 
17910 namespace {
17911   // Mark all of the declarations used by a type as referenced.
17912   // FIXME: Not fully implemented yet! We need to have a better understanding
17913   // of when we're entering a context we should not recurse into.
17914   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17915   // TreeTransforms rebuilding the type in a new context. Rather than
17916   // duplicating the TreeTransform logic, we should consider reusing it here.
17917   // Currently that causes problems when rebuilding LambdaExprs.
17918   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17919     Sema &S;
17920     SourceLocation Loc;
17921 
17922   public:
17923     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17924 
17925     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17926 
17927     bool TraverseTemplateArgument(const TemplateArgument &Arg);
17928   };
17929 }
17930 
17931 bool MarkReferencedDecls::TraverseTemplateArgument(
17932     const TemplateArgument &Arg) {
17933   {
17934     // A non-type template argument is a constant-evaluated context.
17935     EnterExpressionEvaluationContext Evaluated(
17936         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17937     if (Arg.getKind() == TemplateArgument::Declaration) {
17938       if (Decl *D = Arg.getAsDecl())
17939         S.MarkAnyDeclReferenced(Loc, D, true);
17940     } else if (Arg.getKind() == TemplateArgument::Expression) {
17941       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17942     }
17943   }
17944 
17945   return Inherited::TraverseTemplateArgument(Arg);
17946 }
17947 
17948 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17949   MarkReferencedDecls Marker(*this, Loc);
17950   Marker.TraverseType(T);
17951 }
17952 
17953 namespace {
17954 /// Helper class that marks all of the declarations referenced by
17955 /// potentially-evaluated subexpressions as "referenced".
17956 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
17957 public:
17958   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
17959   bool SkipLocalVariables;
17960 
17961   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17962       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
17963 
17964   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17965     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
17966   }
17967 
17968   void VisitDeclRefExpr(DeclRefExpr *E) {
17969     // If we were asked not to visit local variables, don't.
17970     if (SkipLocalVariables) {
17971       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17972         if (VD->hasLocalStorage())
17973           return;
17974     }
17975     S.MarkDeclRefReferenced(E);
17976   }
17977 
17978   void VisitMemberExpr(MemberExpr *E) {
17979     S.MarkMemberReferenced(E);
17980     Visit(E->getBase());
17981   }
17982 };
17983 } // namespace
17984 
17985 /// Mark any declarations that appear within this expression or any
17986 /// potentially-evaluated subexpressions as "referenced".
17987 ///
17988 /// \param SkipLocalVariables If true, don't mark local variables as
17989 /// 'referenced'.
17990 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17991                                             bool SkipLocalVariables) {
17992   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17993 }
17994 
17995 /// Emit a diagnostic that describes an effect on the run-time behavior
17996 /// of the program being compiled.
17997 ///
17998 /// This routine emits the given diagnostic when the code currently being
17999 /// type-checked is "potentially evaluated", meaning that there is a
18000 /// possibility that the code will actually be executable. Code in sizeof()
18001 /// expressions, code used only during overload resolution, etc., are not
18002 /// potentially evaluated. This routine will suppress such diagnostics or,
18003 /// in the absolutely nutty case of potentially potentially evaluated
18004 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18005 /// later.
18006 ///
18007 /// This routine should be used for all diagnostics that describe the run-time
18008 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18009 /// Failure to do so will likely result in spurious diagnostics or failures
18010 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18011 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18012                                const PartialDiagnostic &PD) {
18013   switch (ExprEvalContexts.back().Context) {
18014   case ExpressionEvaluationContext::Unevaluated:
18015   case ExpressionEvaluationContext::UnevaluatedList:
18016   case ExpressionEvaluationContext::UnevaluatedAbstract:
18017   case ExpressionEvaluationContext::DiscardedStatement:
18018     // The argument will never be evaluated, so don't complain.
18019     break;
18020 
18021   case ExpressionEvaluationContext::ConstantEvaluated:
18022     // Relevant diagnostics should be produced by constant evaluation.
18023     break;
18024 
18025   case ExpressionEvaluationContext::PotentiallyEvaluated:
18026   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18027     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18028       FunctionScopes.back()->PossiblyUnreachableDiags.
18029         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18030       return true;
18031     }
18032 
18033     // The initializer of a constexpr variable or of the first declaration of a
18034     // static data member is not syntactically a constant evaluated constant,
18035     // but nonetheless is always required to be a constant expression, so we
18036     // can skip diagnosing.
18037     // FIXME: Using the mangling context here is a hack.
18038     if (auto *VD = dyn_cast_or_null<VarDecl>(
18039             ExprEvalContexts.back().ManglingContextDecl)) {
18040       if (VD->isConstexpr() ||
18041           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18042         break;
18043       // FIXME: For any other kind of variable, we should build a CFG for its
18044       // initializer and check whether the context in question is reachable.
18045     }
18046 
18047     Diag(Loc, PD);
18048     return true;
18049   }
18050 
18051   return false;
18052 }
18053 
18054 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18055                                const PartialDiagnostic &PD) {
18056   return DiagRuntimeBehavior(
18057       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18058 }
18059 
18060 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18061                                CallExpr *CE, FunctionDecl *FD) {
18062   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18063     return false;
18064 
18065   // If we're inside a decltype's expression, don't check for a valid return
18066   // type or construct temporaries until we know whether this is the last call.
18067   if (ExprEvalContexts.back().ExprContext ==
18068       ExpressionEvaluationContextRecord::EK_Decltype) {
18069     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18070     return false;
18071   }
18072 
18073   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18074     FunctionDecl *FD;
18075     CallExpr *CE;
18076 
18077   public:
18078     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18079       : FD(FD), CE(CE) { }
18080 
18081     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18082       if (!FD) {
18083         S.Diag(Loc, diag::err_call_incomplete_return)
18084           << T << CE->getSourceRange();
18085         return;
18086       }
18087 
18088       S.Diag(Loc, diag::err_call_function_incomplete_return)
18089         << CE->getSourceRange() << FD->getDeclName() << T;
18090       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18091           << FD->getDeclName();
18092     }
18093   } Diagnoser(FD, CE);
18094 
18095   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18096     return true;
18097 
18098   return false;
18099 }
18100 
18101 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18102 // will prevent this condition from triggering, which is what we want.
18103 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18104   SourceLocation Loc;
18105 
18106   unsigned diagnostic = diag::warn_condition_is_assignment;
18107   bool IsOrAssign = false;
18108 
18109   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18110     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18111       return;
18112 
18113     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18114 
18115     // Greylist some idioms by putting them into a warning subcategory.
18116     if (ObjCMessageExpr *ME
18117           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18118       Selector Sel = ME->getSelector();
18119 
18120       // self = [<foo> init...]
18121       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18122         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18123 
18124       // <foo> = [<bar> nextObject]
18125       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18126         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18127     }
18128 
18129     Loc = Op->getOperatorLoc();
18130   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18131     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18132       return;
18133 
18134     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18135     Loc = Op->getOperatorLoc();
18136   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18137     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18138   else {
18139     // Not an assignment.
18140     return;
18141   }
18142 
18143   Diag(Loc, diagnostic) << E->getSourceRange();
18144 
18145   SourceLocation Open = E->getBeginLoc();
18146   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18147   Diag(Loc, diag::note_condition_assign_silence)
18148         << FixItHint::CreateInsertion(Open, "(")
18149         << FixItHint::CreateInsertion(Close, ")");
18150 
18151   if (IsOrAssign)
18152     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18153       << FixItHint::CreateReplacement(Loc, "!=");
18154   else
18155     Diag(Loc, diag::note_condition_assign_to_comparison)
18156       << FixItHint::CreateReplacement(Loc, "==");
18157 }
18158 
18159 /// Redundant parentheses over an equality comparison can indicate
18160 /// that the user intended an assignment used as condition.
18161 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18162   // Don't warn if the parens came from a macro.
18163   SourceLocation parenLoc = ParenE->getBeginLoc();
18164   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18165     return;
18166   // Don't warn for dependent expressions.
18167   if (ParenE->isTypeDependent())
18168     return;
18169 
18170   Expr *E = ParenE->IgnoreParens();
18171 
18172   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18173     if (opE->getOpcode() == BO_EQ &&
18174         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18175                                                            == Expr::MLV_Valid) {
18176       SourceLocation Loc = opE->getOperatorLoc();
18177 
18178       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18179       SourceRange ParenERange = ParenE->getSourceRange();
18180       Diag(Loc, diag::note_equality_comparison_silence)
18181         << FixItHint::CreateRemoval(ParenERange.getBegin())
18182         << FixItHint::CreateRemoval(ParenERange.getEnd());
18183       Diag(Loc, diag::note_equality_comparison_to_assign)
18184         << FixItHint::CreateReplacement(Loc, "=");
18185     }
18186 }
18187 
18188 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18189                                        bool IsConstexpr) {
18190   DiagnoseAssignmentAsCondition(E);
18191   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18192     DiagnoseEqualityWithExtraParens(parenE);
18193 
18194   ExprResult result = CheckPlaceholderExpr(E);
18195   if (result.isInvalid()) return ExprError();
18196   E = result.get();
18197 
18198   if (!E->isTypeDependent()) {
18199     if (getLangOpts().CPlusPlus)
18200       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18201 
18202     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18203     if (ERes.isInvalid())
18204       return ExprError();
18205     E = ERes.get();
18206 
18207     QualType T = E->getType();
18208     if (!T->isScalarType()) { // C99 6.8.4.1p1
18209       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18210         << T << E->getSourceRange();
18211       return ExprError();
18212     }
18213     CheckBoolLikeConversion(E, Loc);
18214   }
18215 
18216   return E;
18217 }
18218 
18219 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18220                                            Expr *SubExpr, ConditionKind CK) {
18221   // Empty conditions are valid in for-statements.
18222   if (!SubExpr)
18223     return ConditionResult();
18224 
18225   ExprResult Cond;
18226   switch (CK) {
18227   case ConditionKind::Boolean:
18228     Cond = CheckBooleanCondition(Loc, SubExpr);
18229     break;
18230 
18231   case ConditionKind::ConstexprIf:
18232     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18233     break;
18234 
18235   case ConditionKind::Switch:
18236     Cond = CheckSwitchCondition(Loc, SubExpr);
18237     break;
18238   }
18239   if (Cond.isInvalid())
18240     return ConditionError();
18241 
18242   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18243   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18244   if (!FullExpr.get())
18245     return ConditionError();
18246 
18247   return ConditionResult(*this, nullptr, FullExpr,
18248                          CK == ConditionKind::ConstexprIf);
18249 }
18250 
18251 namespace {
18252   /// A visitor for rebuilding a call to an __unknown_any expression
18253   /// to have an appropriate type.
18254   struct RebuildUnknownAnyFunction
18255     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18256 
18257     Sema &S;
18258 
18259     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18260 
18261     ExprResult VisitStmt(Stmt *S) {
18262       llvm_unreachable("unexpected statement!");
18263     }
18264 
18265     ExprResult VisitExpr(Expr *E) {
18266       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18267         << E->getSourceRange();
18268       return ExprError();
18269     }
18270 
18271     /// Rebuild an expression which simply semantically wraps another
18272     /// expression which it shares the type and value kind of.
18273     template <class T> ExprResult rebuildSugarExpr(T *E) {
18274       ExprResult SubResult = Visit(E->getSubExpr());
18275       if (SubResult.isInvalid()) return ExprError();
18276 
18277       Expr *SubExpr = SubResult.get();
18278       E->setSubExpr(SubExpr);
18279       E->setType(SubExpr->getType());
18280       E->setValueKind(SubExpr->getValueKind());
18281       assert(E->getObjectKind() == OK_Ordinary);
18282       return E;
18283     }
18284 
18285     ExprResult VisitParenExpr(ParenExpr *E) {
18286       return rebuildSugarExpr(E);
18287     }
18288 
18289     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18290       return rebuildSugarExpr(E);
18291     }
18292 
18293     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18294       ExprResult SubResult = Visit(E->getSubExpr());
18295       if (SubResult.isInvalid()) return ExprError();
18296 
18297       Expr *SubExpr = SubResult.get();
18298       E->setSubExpr(SubExpr);
18299       E->setType(S.Context.getPointerType(SubExpr->getType()));
18300       assert(E->getValueKind() == VK_RValue);
18301       assert(E->getObjectKind() == OK_Ordinary);
18302       return E;
18303     }
18304 
18305     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18306       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18307 
18308       E->setType(VD->getType());
18309 
18310       assert(E->getValueKind() == VK_RValue);
18311       if (S.getLangOpts().CPlusPlus &&
18312           !(isa<CXXMethodDecl>(VD) &&
18313             cast<CXXMethodDecl>(VD)->isInstance()))
18314         E->setValueKind(VK_LValue);
18315 
18316       return E;
18317     }
18318 
18319     ExprResult VisitMemberExpr(MemberExpr *E) {
18320       return resolveDecl(E, E->getMemberDecl());
18321     }
18322 
18323     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18324       return resolveDecl(E, E->getDecl());
18325     }
18326   };
18327 }
18328 
18329 /// Given a function expression of unknown-any type, try to rebuild it
18330 /// to have a function type.
18331 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18332   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18333   if (Result.isInvalid()) return ExprError();
18334   return S.DefaultFunctionArrayConversion(Result.get());
18335 }
18336 
18337 namespace {
18338   /// A visitor for rebuilding an expression of type __unknown_anytype
18339   /// into one which resolves the type directly on the referring
18340   /// expression.  Strict preservation of the original source
18341   /// structure is not a goal.
18342   struct RebuildUnknownAnyExpr
18343     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18344 
18345     Sema &S;
18346 
18347     /// The current destination type.
18348     QualType DestType;
18349 
18350     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18351       : S(S), DestType(CastType) {}
18352 
18353     ExprResult VisitStmt(Stmt *S) {
18354       llvm_unreachable("unexpected statement!");
18355     }
18356 
18357     ExprResult VisitExpr(Expr *E) {
18358       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18359         << E->getSourceRange();
18360       return ExprError();
18361     }
18362 
18363     ExprResult VisitCallExpr(CallExpr *E);
18364     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18365 
18366     /// Rebuild an expression which simply semantically wraps another
18367     /// expression which it shares the type and value kind of.
18368     template <class T> ExprResult rebuildSugarExpr(T *E) {
18369       ExprResult SubResult = Visit(E->getSubExpr());
18370       if (SubResult.isInvalid()) return ExprError();
18371       Expr *SubExpr = SubResult.get();
18372       E->setSubExpr(SubExpr);
18373       E->setType(SubExpr->getType());
18374       E->setValueKind(SubExpr->getValueKind());
18375       assert(E->getObjectKind() == OK_Ordinary);
18376       return E;
18377     }
18378 
18379     ExprResult VisitParenExpr(ParenExpr *E) {
18380       return rebuildSugarExpr(E);
18381     }
18382 
18383     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18384       return rebuildSugarExpr(E);
18385     }
18386 
18387     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18388       const PointerType *Ptr = DestType->getAs<PointerType>();
18389       if (!Ptr) {
18390         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18391           << E->getSourceRange();
18392         return ExprError();
18393       }
18394 
18395       if (isa<CallExpr>(E->getSubExpr())) {
18396         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18397           << E->getSourceRange();
18398         return ExprError();
18399       }
18400 
18401       assert(E->getValueKind() == VK_RValue);
18402       assert(E->getObjectKind() == OK_Ordinary);
18403       E->setType(DestType);
18404 
18405       // Build the sub-expression as if it were an object of the pointee type.
18406       DestType = Ptr->getPointeeType();
18407       ExprResult SubResult = Visit(E->getSubExpr());
18408       if (SubResult.isInvalid()) return ExprError();
18409       E->setSubExpr(SubResult.get());
18410       return E;
18411     }
18412 
18413     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18414 
18415     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18416 
18417     ExprResult VisitMemberExpr(MemberExpr *E) {
18418       return resolveDecl(E, E->getMemberDecl());
18419     }
18420 
18421     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18422       return resolveDecl(E, E->getDecl());
18423     }
18424   };
18425 }
18426 
18427 /// Rebuilds a call expression which yielded __unknown_anytype.
18428 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18429   Expr *CalleeExpr = E->getCallee();
18430 
18431   enum FnKind {
18432     FK_MemberFunction,
18433     FK_FunctionPointer,
18434     FK_BlockPointer
18435   };
18436 
18437   FnKind Kind;
18438   QualType CalleeType = CalleeExpr->getType();
18439   if (CalleeType == S.Context.BoundMemberTy) {
18440     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18441     Kind = FK_MemberFunction;
18442     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18443   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18444     CalleeType = Ptr->getPointeeType();
18445     Kind = FK_FunctionPointer;
18446   } else {
18447     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18448     Kind = FK_BlockPointer;
18449   }
18450   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18451 
18452   // Verify that this is a legal result type of a function.
18453   if (DestType->isArrayType() || DestType->isFunctionType()) {
18454     unsigned diagID = diag::err_func_returning_array_function;
18455     if (Kind == FK_BlockPointer)
18456       diagID = diag::err_block_returning_array_function;
18457 
18458     S.Diag(E->getExprLoc(), diagID)
18459       << DestType->isFunctionType() << DestType;
18460     return ExprError();
18461   }
18462 
18463   // Otherwise, go ahead and set DestType as the call's result.
18464   E->setType(DestType.getNonLValueExprType(S.Context));
18465   E->setValueKind(Expr::getValueKindForType(DestType));
18466   assert(E->getObjectKind() == OK_Ordinary);
18467 
18468   // Rebuild the function type, replacing the result type with DestType.
18469   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18470   if (Proto) {
18471     // __unknown_anytype(...) is a special case used by the debugger when
18472     // it has no idea what a function's signature is.
18473     //
18474     // We want to build this call essentially under the K&R
18475     // unprototyped rules, but making a FunctionNoProtoType in C++
18476     // would foul up all sorts of assumptions.  However, we cannot
18477     // simply pass all arguments as variadic arguments, nor can we
18478     // portably just call the function under a non-variadic type; see
18479     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18480     // However, it turns out that in practice it is generally safe to
18481     // call a function declared as "A foo(B,C,D);" under the prototype
18482     // "A foo(B,C,D,...);".  The only known exception is with the
18483     // Windows ABI, where any variadic function is implicitly cdecl
18484     // regardless of its normal CC.  Therefore we change the parameter
18485     // types to match the types of the arguments.
18486     //
18487     // This is a hack, but it is far superior to moving the
18488     // corresponding target-specific code from IR-gen to Sema/AST.
18489 
18490     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18491     SmallVector<QualType, 8> ArgTypes;
18492     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18493       ArgTypes.reserve(E->getNumArgs());
18494       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18495         Expr *Arg = E->getArg(i);
18496         QualType ArgType = Arg->getType();
18497         if (E->isLValue()) {
18498           ArgType = S.Context.getLValueReferenceType(ArgType);
18499         } else if (E->isXValue()) {
18500           ArgType = S.Context.getRValueReferenceType(ArgType);
18501         }
18502         ArgTypes.push_back(ArgType);
18503       }
18504       ParamTypes = ArgTypes;
18505     }
18506     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18507                                          Proto->getExtProtoInfo());
18508   } else {
18509     DestType = S.Context.getFunctionNoProtoType(DestType,
18510                                                 FnType->getExtInfo());
18511   }
18512 
18513   // Rebuild the appropriate pointer-to-function type.
18514   switch (Kind) {
18515   case FK_MemberFunction:
18516     // Nothing to do.
18517     break;
18518 
18519   case FK_FunctionPointer:
18520     DestType = S.Context.getPointerType(DestType);
18521     break;
18522 
18523   case FK_BlockPointer:
18524     DestType = S.Context.getBlockPointerType(DestType);
18525     break;
18526   }
18527 
18528   // Finally, we can recurse.
18529   ExprResult CalleeResult = Visit(CalleeExpr);
18530   if (!CalleeResult.isUsable()) return ExprError();
18531   E->setCallee(CalleeResult.get());
18532 
18533   // Bind a temporary if necessary.
18534   return S.MaybeBindToTemporary(E);
18535 }
18536 
18537 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18538   // Verify that this is a legal result type of a call.
18539   if (DestType->isArrayType() || DestType->isFunctionType()) {
18540     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18541       << DestType->isFunctionType() << DestType;
18542     return ExprError();
18543   }
18544 
18545   // Rewrite the method result type if available.
18546   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18547     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18548     Method->setReturnType(DestType);
18549   }
18550 
18551   // Change the type of the message.
18552   E->setType(DestType.getNonReferenceType());
18553   E->setValueKind(Expr::getValueKindForType(DestType));
18554 
18555   return S.MaybeBindToTemporary(E);
18556 }
18557 
18558 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18559   // The only case we should ever see here is a function-to-pointer decay.
18560   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18561     assert(E->getValueKind() == VK_RValue);
18562     assert(E->getObjectKind() == OK_Ordinary);
18563 
18564     E->setType(DestType);
18565 
18566     // Rebuild the sub-expression as the pointee (function) type.
18567     DestType = DestType->castAs<PointerType>()->getPointeeType();
18568 
18569     ExprResult Result = Visit(E->getSubExpr());
18570     if (!Result.isUsable()) return ExprError();
18571 
18572     E->setSubExpr(Result.get());
18573     return E;
18574   } else if (E->getCastKind() == CK_LValueToRValue) {
18575     assert(E->getValueKind() == VK_RValue);
18576     assert(E->getObjectKind() == OK_Ordinary);
18577 
18578     assert(isa<BlockPointerType>(E->getType()));
18579 
18580     E->setType(DestType);
18581 
18582     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18583     DestType = S.Context.getLValueReferenceType(DestType);
18584 
18585     ExprResult Result = Visit(E->getSubExpr());
18586     if (!Result.isUsable()) return ExprError();
18587 
18588     E->setSubExpr(Result.get());
18589     return E;
18590   } else {
18591     llvm_unreachable("Unhandled cast type!");
18592   }
18593 }
18594 
18595 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18596   ExprValueKind ValueKind = VK_LValue;
18597   QualType Type = DestType;
18598 
18599   // We know how to make this work for certain kinds of decls:
18600 
18601   //  - functions
18602   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18603     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18604       DestType = Ptr->getPointeeType();
18605       ExprResult Result = resolveDecl(E, VD);
18606       if (Result.isInvalid()) return ExprError();
18607       return S.ImpCastExprToType(Result.get(), Type,
18608                                  CK_FunctionToPointerDecay, VK_RValue);
18609     }
18610 
18611     if (!Type->isFunctionType()) {
18612       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18613         << VD << E->getSourceRange();
18614       return ExprError();
18615     }
18616     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18617       // We must match the FunctionDecl's type to the hack introduced in
18618       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18619       // type. See the lengthy commentary in that routine.
18620       QualType FDT = FD->getType();
18621       const FunctionType *FnType = FDT->castAs<FunctionType>();
18622       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18623       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18624       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18625         SourceLocation Loc = FD->getLocation();
18626         FunctionDecl *NewFD = FunctionDecl::Create(
18627             S.Context, FD->getDeclContext(), Loc, Loc,
18628             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18629             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18630             /*ConstexprKind*/ CSK_unspecified);
18631 
18632         if (FD->getQualifier())
18633           NewFD->setQualifierInfo(FD->getQualifierLoc());
18634 
18635         SmallVector<ParmVarDecl*, 16> Params;
18636         for (const auto &AI : FT->param_types()) {
18637           ParmVarDecl *Param =
18638             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18639           Param->setScopeInfo(0, Params.size());
18640           Params.push_back(Param);
18641         }
18642         NewFD->setParams(Params);
18643         DRE->setDecl(NewFD);
18644         VD = DRE->getDecl();
18645       }
18646     }
18647 
18648     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18649       if (MD->isInstance()) {
18650         ValueKind = VK_RValue;
18651         Type = S.Context.BoundMemberTy;
18652       }
18653 
18654     // Function references aren't l-values in C.
18655     if (!S.getLangOpts().CPlusPlus)
18656       ValueKind = VK_RValue;
18657 
18658   //  - variables
18659   } else if (isa<VarDecl>(VD)) {
18660     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18661       Type = RefTy->getPointeeType();
18662     } else if (Type->isFunctionType()) {
18663       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18664         << VD << E->getSourceRange();
18665       return ExprError();
18666     }
18667 
18668   //  - nothing else
18669   } else {
18670     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18671       << VD << E->getSourceRange();
18672     return ExprError();
18673   }
18674 
18675   // Modifying the declaration like this is friendly to IR-gen but
18676   // also really dangerous.
18677   VD->setType(DestType);
18678   E->setType(Type);
18679   E->setValueKind(ValueKind);
18680   return E;
18681 }
18682 
18683 /// Check a cast of an unknown-any type.  We intentionally only
18684 /// trigger this for C-style casts.
18685 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18686                                      Expr *CastExpr, CastKind &CastKind,
18687                                      ExprValueKind &VK, CXXCastPath &Path) {
18688   // The type we're casting to must be either void or complete.
18689   if (!CastType->isVoidType() &&
18690       RequireCompleteType(TypeRange.getBegin(), CastType,
18691                           diag::err_typecheck_cast_to_incomplete))
18692     return ExprError();
18693 
18694   // Rewrite the casted expression from scratch.
18695   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18696   if (!result.isUsable()) return ExprError();
18697 
18698   CastExpr = result.get();
18699   VK = CastExpr->getValueKind();
18700   CastKind = CK_NoOp;
18701 
18702   return CastExpr;
18703 }
18704 
18705 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18706   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18707 }
18708 
18709 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18710                                     Expr *arg, QualType &paramType) {
18711   // If the syntactic form of the argument is not an explicit cast of
18712   // any sort, just do default argument promotion.
18713   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18714   if (!castArg) {
18715     ExprResult result = DefaultArgumentPromotion(arg);
18716     if (result.isInvalid()) return ExprError();
18717     paramType = result.get()->getType();
18718     return result;
18719   }
18720 
18721   // Otherwise, use the type that was written in the explicit cast.
18722   assert(!arg->hasPlaceholderType());
18723   paramType = castArg->getTypeAsWritten();
18724 
18725   // Copy-initialize a parameter of that type.
18726   InitializedEntity entity =
18727     InitializedEntity::InitializeParameter(Context, paramType,
18728                                            /*consumed*/ false);
18729   return PerformCopyInitialization(entity, callLoc, arg);
18730 }
18731 
18732 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18733   Expr *orig = E;
18734   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18735   while (true) {
18736     E = E->IgnoreParenImpCasts();
18737     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18738       E = call->getCallee();
18739       diagID = diag::err_uncasted_call_of_unknown_any;
18740     } else {
18741       break;
18742     }
18743   }
18744 
18745   SourceLocation loc;
18746   NamedDecl *d;
18747   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18748     loc = ref->getLocation();
18749     d = ref->getDecl();
18750   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18751     loc = mem->getMemberLoc();
18752     d = mem->getMemberDecl();
18753   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18754     diagID = diag::err_uncasted_call_of_unknown_any;
18755     loc = msg->getSelectorStartLoc();
18756     d = msg->getMethodDecl();
18757     if (!d) {
18758       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18759         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18760         << orig->getSourceRange();
18761       return ExprError();
18762     }
18763   } else {
18764     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18765       << E->getSourceRange();
18766     return ExprError();
18767   }
18768 
18769   S.Diag(loc, diagID) << d << orig->getSourceRange();
18770 
18771   // Never recoverable.
18772   return ExprError();
18773 }
18774 
18775 /// Check for operands with placeholder types and complain if found.
18776 /// Returns ExprError() if there was an error and no recovery was possible.
18777 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18778   if (!getLangOpts().CPlusPlus) {
18779     // C cannot handle TypoExpr nodes on either side of a binop because it
18780     // doesn't handle dependent types properly, so make sure any TypoExprs have
18781     // been dealt with before checking the operands.
18782     ExprResult Result = CorrectDelayedTyposInExpr(E);
18783     if (!Result.isUsable()) return ExprError();
18784     E = Result.get();
18785   }
18786 
18787   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18788   if (!placeholderType) return E;
18789 
18790   switch (placeholderType->getKind()) {
18791 
18792   // Overloaded expressions.
18793   case BuiltinType::Overload: {
18794     // Try to resolve a single function template specialization.
18795     // This is obligatory.
18796     ExprResult Result = E;
18797     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18798       return Result;
18799 
18800     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18801     // leaves Result unchanged on failure.
18802     Result = E;
18803     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18804       return Result;
18805 
18806     // If that failed, try to recover with a call.
18807     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18808                          /*complain*/ true);
18809     return Result;
18810   }
18811 
18812   // Bound member functions.
18813   case BuiltinType::BoundMember: {
18814     ExprResult result = E;
18815     const Expr *BME = E->IgnoreParens();
18816     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18817     // Try to give a nicer diagnostic if it is a bound member that we recognize.
18818     if (isa<CXXPseudoDestructorExpr>(BME)) {
18819       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18820     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18821       if (ME->getMemberNameInfo().getName().getNameKind() ==
18822           DeclarationName::CXXDestructorName)
18823         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18824     }
18825     tryToRecoverWithCall(result, PD,
18826                          /*complain*/ true);
18827     return result;
18828   }
18829 
18830   // ARC unbridged casts.
18831   case BuiltinType::ARCUnbridgedCast: {
18832     Expr *realCast = stripARCUnbridgedCast(E);
18833     diagnoseARCUnbridgedCast(realCast);
18834     return realCast;
18835   }
18836 
18837   // Expressions of unknown type.
18838   case BuiltinType::UnknownAny:
18839     return diagnoseUnknownAnyExpr(*this, E);
18840 
18841   // Pseudo-objects.
18842   case BuiltinType::PseudoObject:
18843     return checkPseudoObjectRValue(E);
18844 
18845   case BuiltinType::BuiltinFn: {
18846     // Accept __noop without parens by implicitly converting it to a call expr.
18847     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18848     if (DRE) {
18849       auto *FD = cast<FunctionDecl>(DRE->getDecl());
18850       if (FD->getBuiltinID() == Builtin::BI__noop) {
18851         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18852                               CK_BuiltinFnToFnPtr)
18853                 .get();
18854         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18855                                 VK_RValue, SourceLocation());
18856       }
18857     }
18858 
18859     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18860     return ExprError();
18861   }
18862 
18863   // Expressions of unknown type.
18864   case BuiltinType::OMPArraySection:
18865     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18866     return ExprError();
18867 
18868   // Expressions of unknown type.
18869   case BuiltinType::OMPArrayShaping:
18870     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
18871 
18872   case BuiltinType::OMPIterator:
18873     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
18874 
18875   // Everything else should be impossible.
18876 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18877   case BuiltinType::Id:
18878 #include "clang/Basic/OpenCLImageTypes.def"
18879 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18880   case BuiltinType::Id:
18881 #include "clang/Basic/OpenCLExtensionTypes.def"
18882 #define SVE_TYPE(Name, Id, SingletonId) \
18883   case BuiltinType::Id:
18884 #include "clang/Basic/AArch64SVEACLETypes.def"
18885 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18886 #define PLACEHOLDER_TYPE(Id, SingletonId)
18887 #include "clang/AST/BuiltinTypes.def"
18888     break;
18889   }
18890 
18891   llvm_unreachable("invalid placeholder type!");
18892 }
18893 
18894 bool Sema::CheckCaseExpression(Expr *E) {
18895   if (E->isTypeDependent())
18896     return true;
18897   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18898     return E->getType()->isIntegralOrEnumerationType();
18899   return false;
18900 }
18901 
18902 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18903 ExprResult
18904 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18905   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18906          "Unknown Objective-C Boolean value!");
18907   QualType BoolT = Context.ObjCBuiltinBoolTy;
18908   if (!Context.getBOOLDecl()) {
18909     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18910                         Sema::LookupOrdinaryName);
18911     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18912       NamedDecl *ND = Result.getFoundDecl();
18913       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18914         Context.setBOOLDecl(TD);
18915     }
18916   }
18917   if (Context.getBOOLDecl())
18918     BoolT = Context.getBOOLType();
18919   return new (Context)
18920       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18921 }
18922 
18923 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18924     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18925     SourceLocation RParen) {
18926 
18927   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18928 
18929   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18930     return Spec.getPlatform() == Platform;
18931   });
18932 
18933   VersionTuple Version;
18934   if (Spec != AvailSpecs.end())
18935     Version = Spec->getVersion();
18936 
18937   // The use of `@available` in the enclosing function should be analyzed to
18938   // warn when it's used inappropriately (i.e. not if(@available)).
18939   if (getCurFunctionOrMethodDecl())
18940     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18941   else if (getCurBlock() || getCurLambda())
18942     getCurFunction()->HasPotentialAvailabilityViolations = true;
18943 
18944   return new (Context)
18945       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18946 }
18947 
18948 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
18949                                     ArrayRef<Expr *> SubExprs, QualType T) {
18950   // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
18951   // bogus diagnostics and this trick does not work in C.
18952   // FIXME: use containsErrors() to suppress unwanted diags in C.
18953   if (!Context.getLangOpts().RecoveryAST)
18954     return ExprError();
18955 
18956   if (isSFINAEContext())
18957     return ExprError();
18958 
18959   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
18960     // We don't know the concrete type, fallback to dependent type.
18961     T = Context.DependentTy;
18962   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
18963 }
18964