1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/DiagnosticSema.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/LiteralSupport.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/AnalysisBasedWarnings.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Designator.h"
42 #include "clang/Sema/Initialization.h"
43 #include "clang/Sema/Lookup.h"
44 #include "clang/Sema/Overload.h"
45 #include "clang/Sema/ParsedTemplate.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaFixItUtils.h"
49 #include "clang/Sema/SemaInternal.h"
50 #include "clang/Sema/Template.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/Support/ConvertUTF.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 
56 using namespace clang;
57 using namespace sema;
58 
59 /// Determine whether the use of this declaration is valid, without
60 /// emitting diagnostics.
61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
62   // See if this is an auto-typed variable whose initializer we are parsing.
63   if (ParsingInitForAutoVars.count(D))
64     return false;
65 
66   // See if this is a deleted function.
67   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
68     if (FD->isDeleted())
69       return false;
70 
71     // If the function has a deduced return type, and we can't deduce it,
72     // then we can't use it either.
73     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
74         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
75       return false;
76 
77     // See if this is an aligned allocation/deallocation function that is
78     // unavailable.
79     if (TreatUnavailableAsInvalid &&
80         isUnavailableAlignedAllocationFunction(*FD))
81       return false;
82   }
83 
84   // See if this function is unavailable.
85   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
86       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
87     return false;
88 
89   if (isa<UnresolvedUsingIfExistsDecl>(D))
90     return false;
91 
92   return true;
93 }
94 
95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
96   // Warn if this is used but marked unused.
97   if (const auto *A = D->getAttr<UnusedAttr>()) {
98     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
99     // should diagnose them.
100     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
101         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
102       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
103       if (DC && !DC->hasAttr<UnusedAttr>())
104         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
105     }
106   }
107 }
108 
109 /// Emit a note explaining that this function is deleted.
110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
111   assert(Decl && Decl->isDeleted());
112 
113   if (Decl->isDefaulted()) {
114     // If the method was explicitly defaulted, point at that declaration.
115     if (!Decl->isImplicit())
116       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
117 
118     // Try to diagnose why this special member function was implicitly
119     // deleted. This might fail, if that reason no longer applies.
120     DiagnoseDeletedDefaultedFunction(Decl);
121     return;
122   }
123 
124   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
125   if (Ctor && Ctor->isInheritingConstructor())
126     return NoteDeletedInheritingConstructor(Ctor);
127 
128   Diag(Decl->getLocation(), diag::note_availability_specified_here)
129     << Decl << 1;
130 }
131 
132 /// Determine whether a FunctionDecl was ever declared with an
133 /// explicit storage class.
134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
135   for (auto I : D->redecls()) {
136     if (I->getStorageClass() != SC_None)
137       return true;
138   }
139   return false;
140 }
141 
142 /// Check whether we're in an extern inline function and referring to a
143 /// variable or function with internal linkage (C11 6.7.4p3).
144 ///
145 /// This is only a warning because we used to silently accept this code, but
146 /// in many cases it will not behave correctly. This is not enabled in C++ mode
147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
148 /// and so while there may still be user mistakes, most of the time we can't
149 /// prove that there are errors.
150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
151                                                       const NamedDecl *D,
152                                                       SourceLocation Loc) {
153   // This is disabled under C++; there are too many ways for this to fire in
154   // contexts where the warning is a false positive, or where it is technically
155   // correct but benign.
156   if (S.getLangOpts().CPlusPlus)
157     return;
158 
159   // Check if this is an inlined function or method.
160   FunctionDecl *Current = S.getCurFunctionDecl();
161   if (!Current)
162     return;
163   if (!Current->isInlined())
164     return;
165   if (!Current->isExternallyVisible())
166     return;
167 
168   // Check if the decl has internal linkage.
169   if (D->getFormalLinkage() != InternalLinkage)
170     return;
171 
172   // Downgrade from ExtWarn to Extension if
173   //  (1) the supposedly external inline function is in the main file,
174   //      and probably won't be included anywhere else.
175   //  (2) the thing we're referencing is a pure function.
176   //  (3) the thing we're referencing is another inline function.
177   // This last can give us false negatives, but it's better than warning on
178   // wrappers for simple C library functions.
179   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
180   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
181   if (!DowngradeWarning && UsedFn)
182     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
183 
184   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
185                                : diag::ext_internal_in_extern_inline)
186     << /*IsVar=*/!UsedFn << D;
187 
188   S.MaybeSuggestAddingStaticToDecl(Current);
189 
190   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
191       << D;
192 }
193 
194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
195   const FunctionDecl *First = Cur->getFirstDecl();
196 
197   // Suggest "static" on the function, if possible.
198   if (!hasAnyExplicitStorageClass(First)) {
199     SourceLocation DeclBegin = First->getSourceRange().getBegin();
200     Diag(DeclBegin, diag::note_convert_inline_to_static)
201       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
202   }
203 }
204 
205 /// Determine whether the use of this declaration is valid, and
206 /// emit any corresponding diagnostics.
207 ///
208 /// This routine diagnoses various problems with referencing
209 /// declarations that can occur when using a declaration. For example,
210 /// it might warn if a deprecated or unavailable declaration is being
211 /// used, or produce an error (and return true) if a C++0x deleted
212 /// function is being used.
213 ///
214 /// \returns true if there was an error (this declaration cannot be
215 /// referenced), false otherwise.
216 ///
217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
218                              const ObjCInterfaceDecl *UnknownObjCClass,
219                              bool ObjCPropertyAccess,
220                              bool AvoidPartialAvailabilityChecks,
221                              ObjCInterfaceDecl *ClassReceiver) {
222   SourceLocation Loc = Locs.front();
223   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224     // If there were any diagnostics suppressed by template argument deduction,
225     // emit them now.
226     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227     if (Pos != SuppressedDiagnostics.end()) {
228       for (const PartialDiagnosticAt &Suppressed : Pos->second)
229         Diag(Suppressed.first, Suppressed.second);
230 
231       // Clear out the list of suppressed diagnostics, so that we don't emit
232       // them again for this specialization. However, we don't obsolete this
233       // entry from the table, because we want to avoid ever emitting these
234       // diagnostics again.
235       Pos->second.clear();
236     }
237 
238     // C++ [basic.start.main]p3:
239     //   The function 'main' shall not be used within a program.
240     if (cast<FunctionDecl>(D)->isMain())
241       Diag(Loc, diag::ext_main_used);
242 
243     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244   }
245 
246   // See if this is an auto-typed variable whose initializer we are parsing.
247   if (ParsingInitForAutoVars.count(D)) {
248     if (isa<BindingDecl>(D)) {
249       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250         << D->getDeclName();
251     } else {
252       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253         << D->getDeclName() << cast<VarDecl>(D)->getType();
254     }
255     return true;
256   }
257 
258   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259     // See if this is a deleted function.
260     if (FD->isDeleted()) {
261       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262       if (Ctor && Ctor->isInheritingConstructor())
263         Diag(Loc, diag::err_deleted_inherited_ctor_use)
264             << Ctor->getParent()
265             << Ctor->getInheritedConstructor().getConstructor()->getParent();
266       else
267         Diag(Loc, diag::err_deleted_function_use);
268       NoteDeletedFunction(FD);
269       return true;
270     }
271 
272     // [expr.prim.id]p4
273     //   A program that refers explicitly or implicitly to a function with a
274     //   trailing requires-clause whose constraint-expression is not satisfied,
275     //   other than to declare it, is ill-formed. [...]
276     //
277     // See if this is a function with constraints that need to be satisfied.
278     // Check this before deducing the return type, as it might instantiate the
279     // definition.
280     if (FD->getTrailingRequiresClause()) {
281       ConstraintSatisfaction Satisfaction;
282       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
283         // A diagnostic will have already been generated (non-constant
284         // constraint expression, for example)
285         return true;
286       if (!Satisfaction.IsSatisfied) {
287         Diag(Loc,
288              diag::err_reference_to_function_with_unsatisfied_constraints)
289             << D;
290         DiagnoseUnsatisfiedConstraint(Satisfaction);
291         return true;
292       }
293     }
294 
295     // If the function has a deduced return type, and we can't deduce it,
296     // then we can't use it either.
297     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
298         DeduceReturnType(FD, Loc))
299       return true;
300 
301     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
302       return true;
303 
304     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
305       return true;
306   }
307 
308   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
309     // Lambdas are only default-constructible or assignable in C++2a onwards.
310     if (MD->getParent()->isLambda() &&
311         ((isa<CXXConstructorDecl>(MD) &&
312           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
313          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
314       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
315         << !isa<CXXConstructorDecl>(MD);
316     }
317   }
318 
319   auto getReferencedObjCProp = [](const NamedDecl *D) ->
320                                       const ObjCPropertyDecl * {
321     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
322       return MD->findPropertyDecl();
323     return nullptr;
324   };
325   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
326     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
327       return true;
328   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
329       return true;
330   }
331 
332   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
333   // Only the variables omp_in and omp_out are allowed in the combiner.
334   // Only the variables omp_priv and omp_orig are allowed in the
335   // initializer-clause.
336   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
337   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
338       isa<VarDecl>(D)) {
339     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
340         << getCurFunction()->HasOMPDeclareReductionCombiner;
341     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
342     return true;
343   }
344 
345   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
346   //  List-items in map clauses on this construct may only refer to the declared
347   //  variable var and entities that could be referenced by a procedure defined
348   //  at the same location
349   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
350       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
351     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
352         << getOpenMPDeclareMapperVarName();
353     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
354     return true;
355   }
356 
357   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
358     Diag(Loc, diag::err_use_of_empty_using_if_exists);
359     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
360     return true;
361   }
362 
363   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
364                              AvoidPartialAvailabilityChecks, ClassReceiver);
365 
366   DiagnoseUnusedOfDecl(*this, D, Loc);
367 
368   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
369 
370   if (auto *VD = dyn_cast<ValueDecl>(D))
371     checkTypeSupport(VD->getType(), Loc, VD);
372 
373   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
374     if (!Context.getTargetInfo().isTLSSupported())
375       if (const auto *VD = dyn_cast<VarDecl>(D))
376         if (VD->getTLSKind() != VarDecl::TLS_None)
377           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
378   }
379 
380   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
381       !isUnevaluatedContext()) {
382     // C++ [expr.prim.req.nested] p3
383     //   A local parameter shall only appear as an unevaluated operand
384     //   (Clause 8) within the constraint-expression.
385     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
386         << D;
387     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
388     return true;
389   }
390 
391   return false;
392 }
393 
394 /// DiagnoseSentinelCalls - This routine checks whether a call or
395 /// message-send is to a declaration with the sentinel attribute, and
396 /// if so, it checks that the requirements of the sentinel are
397 /// satisfied.
398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
399                                  ArrayRef<Expr *> Args) {
400   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
401   if (!attr)
402     return;
403 
404   // The number of formal parameters of the declaration.
405   unsigned numFormalParams;
406 
407   // The kind of declaration.  This is also an index into a %select in
408   // the diagnostic.
409   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
410 
411   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
412     numFormalParams = MD->param_size();
413     calleeType = CT_Method;
414   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415     numFormalParams = FD->param_size();
416     calleeType = CT_Function;
417   } else if (isa<VarDecl>(D)) {
418     QualType type = cast<ValueDecl>(D)->getType();
419     const FunctionType *fn = nullptr;
420     if (const PointerType *ptr = type->getAs<PointerType>()) {
421       fn = ptr->getPointeeType()->getAs<FunctionType>();
422       if (!fn) return;
423       calleeType = CT_Function;
424     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
425       fn = ptr->getPointeeType()->castAs<FunctionType>();
426       calleeType = CT_Block;
427     } else {
428       return;
429     }
430 
431     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
432       numFormalParams = proto->getNumParams();
433     } else {
434       numFormalParams = 0;
435     }
436   } else {
437     return;
438   }
439 
440   // "nullPos" is the number of formal parameters at the end which
441   // effectively count as part of the variadic arguments.  This is
442   // useful if you would prefer to not have *any* formal parameters,
443   // but the language forces you to have at least one.
444   unsigned nullPos = attr->getNullPos();
445   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
446   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
447 
448   // The number of arguments which should follow the sentinel.
449   unsigned numArgsAfterSentinel = attr->getSentinel();
450 
451   // If there aren't enough arguments for all the formal parameters,
452   // the sentinel, and the args after the sentinel, complain.
453   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
454     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
455     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
456     return;
457   }
458 
459   // Otherwise, find the sentinel expression.
460   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
461   if (!sentinelExpr) return;
462   if (sentinelExpr->isValueDependent()) return;
463   if (Context.isSentinelNullExpr(sentinelExpr)) return;
464 
465   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
466   // or 'NULL' if those are actually defined in the context.  Only use
467   // 'nil' for ObjC methods, where it's much more likely that the
468   // variadic arguments form a list of object pointers.
469   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
470   std::string NullValue;
471   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
472     NullValue = "nil";
473   else if (getLangOpts().CPlusPlus11)
474     NullValue = "nullptr";
475   else if (PP.isMacroDefined("NULL"))
476     NullValue = "NULL";
477   else
478     NullValue = "(void*) 0";
479 
480   if (MissingNilLoc.isInvalid())
481     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
482   else
483     Diag(MissingNilLoc, diag::warn_missing_sentinel)
484       << int(calleeType)
485       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
486   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
487 }
488 
489 SourceRange Sema::getExprRange(Expr *E) const {
490   return E ? E->getSourceRange() : SourceRange();
491 }
492 
493 //===----------------------------------------------------------------------===//
494 //  Standard Promotions and Conversions
495 //===----------------------------------------------------------------------===//
496 
497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
499   // Handle any placeholder expressions which made it here.
500   if (E->hasPlaceholderType()) {
501     ExprResult result = CheckPlaceholderExpr(E);
502     if (result.isInvalid()) return ExprError();
503     E = result.get();
504   }
505 
506   QualType Ty = E->getType();
507   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
508 
509   if (Ty->isFunctionType()) {
510     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
511       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
512         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
513           return ExprError();
514 
515     E = ImpCastExprToType(E, Context.getPointerType(Ty),
516                           CK_FunctionToPointerDecay).get();
517   } else if (Ty->isArrayType()) {
518     // In C90 mode, arrays only promote to pointers if the array expression is
519     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
520     // type 'array of type' is converted to an expression that has type 'pointer
521     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
522     // that has type 'array of type' ...".  The relevant change is "an lvalue"
523     // (C90) to "an expression" (C99).
524     //
525     // C++ 4.2p1:
526     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
527     // T" can be converted to an rvalue of type "pointer to T".
528     //
529     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
530       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
531                                          CK_ArrayToPointerDecay);
532       if (Res.isInvalid())
533         return ExprError();
534       E = Res.get();
535     }
536   }
537   return E;
538 }
539 
540 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
541   // Check to see if we are dereferencing a null pointer.  If so,
542   // and if not volatile-qualified, this is undefined behavior that the
543   // optimizer will delete, so warn about it.  People sometimes try to use this
544   // to get a deterministic trap and are surprised by clang's behavior.  This
545   // only handles the pattern "*null", which is a very syntactic check.
546   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
547   if (UO && UO->getOpcode() == UO_Deref &&
548       UO->getSubExpr()->getType()->isPointerType()) {
549     const LangAS AS =
550         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
551     if ((!isTargetAddressSpace(AS) ||
552          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
553         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
554             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
555         !UO->getType().isVolatileQualified()) {
556       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
557                             S.PDiag(diag::warn_indirection_through_null)
558                                 << UO->getSubExpr()->getSourceRange());
559       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
560                             S.PDiag(diag::note_indirection_through_null));
561     }
562   }
563 }
564 
565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
566                                     SourceLocation AssignLoc,
567                                     const Expr* RHS) {
568   const ObjCIvarDecl *IV = OIRE->getDecl();
569   if (!IV)
570     return;
571 
572   DeclarationName MemberName = IV->getDeclName();
573   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
574   if (!Member || !Member->isStr("isa"))
575     return;
576 
577   const Expr *Base = OIRE->getBase();
578   QualType BaseType = Base->getType();
579   if (OIRE->isArrow())
580     BaseType = BaseType->getPointeeType();
581   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
582     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
583       ObjCInterfaceDecl *ClassDeclared = nullptr;
584       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
585       if (!ClassDeclared->getSuperClass()
586           && (*ClassDeclared->ivar_begin()) == IV) {
587         if (RHS) {
588           NamedDecl *ObjectSetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_setClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectSetClass) {
593             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
594             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
595                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
596                                               "object_setClass(")
597                 << FixItHint::CreateReplacement(
598                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
599                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
600           }
601           else
602             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
603         } else {
604           NamedDecl *ObjectGetClass =
605             S.LookupSingleName(S.TUScope,
606                                &S.Context.Idents.get("object_getClass"),
607                                SourceLocation(), S.LookupOrdinaryName);
608           if (ObjectGetClass)
609             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
610                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
611                                               "object_getClass(")
612                 << FixItHint::CreateReplacement(
613                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
614           else
615             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
616         }
617         S.Diag(IV->getLocation(), diag::note_ivar_decl);
618       }
619     }
620 }
621 
622 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
623   // Handle any placeholder expressions which made it here.
624   if (E->hasPlaceholderType()) {
625     ExprResult result = CheckPlaceholderExpr(E);
626     if (result.isInvalid()) return ExprError();
627     E = result.get();
628   }
629 
630   // C++ [conv.lval]p1:
631   //   A glvalue of a non-function, non-array type T can be
632   //   converted to a prvalue.
633   if (!E->isGLValue()) return E;
634 
635   QualType T = E->getType();
636   assert(!T.isNull() && "r-value conversion on typeless expression?");
637 
638   // lvalue-to-rvalue conversion cannot be applied to function or array types.
639   if (T->isFunctionType() || T->isArrayType())
640     return E;
641 
642   // We don't want to throw lvalue-to-rvalue casts on top of
643   // expressions of certain types in C++.
644   if (getLangOpts().CPlusPlus &&
645       (E->getType() == Context.OverloadTy ||
646        T->isDependentType() ||
647        T->isRecordType()))
648     return E;
649 
650   // The C standard is actually really unclear on this point, and
651   // DR106 tells us what the result should be but not why.  It's
652   // generally best to say that void types just doesn't undergo
653   // lvalue-to-rvalue at all.  Note that expressions of unqualified
654   // 'void' type are never l-values, but qualified void can be.
655   if (T->isVoidType())
656     return E;
657 
658   // OpenCL usually rejects direct accesses to values of 'half' type.
659   if (getLangOpts().OpenCL &&
660       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666 
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
674           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
675           << FixItHint::CreateReplacement(
676                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683 
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695 
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700 
701   ExprResult Res = CheckLValueToRValueConversionOperand(E);
702   if (Res.isInvalid())
703     return Res;
704   E = Res.get();
705 
706   // Loading a __weak object implicitly retains the value, so we need a cleanup to
707   // balance that.
708   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709     Cleanup.setExprNeedsCleanups(true);
710 
711   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712     Cleanup.setExprNeedsCleanups(true);
713 
714   // C++ [conv.lval]p3:
715   //   If T is cv std::nullptr_t, the result is a null pointer constant.
716   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
717   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
718                                  CurFPFeatureOverrides());
719 
720   // C11 6.3.2.1p2:
721   //   ... if the lvalue has atomic type, the value has the non-atomic version
722   //   of the type of the lvalue ...
723   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724     T = Atomic->getValueType().getUnqualifiedType();
725     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726                                    nullptr, VK_PRValue, FPOptionsOverride());
727   }
728 
729   return Res;
730 }
731 
732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734   if (Res.isInvalid())
735     return ExprError();
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res;
740 }
741 
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745   QualType Ty = E->getType();
746   ExprResult Res = E;
747   // Only do implicit cast for a function type, but not for a pointer
748   // to function type.
749   if (Ty->isFunctionType()) {
750     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751                             CK_FunctionToPointerDecay);
752     if (Res.isInvalid())
753       return ExprError();
754   }
755   Res = DefaultLvalueConversion(Res.get());
756   if (Res.isInvalid())
757     return ExprError();
758   return Res.get();
759 }
760 
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767   // First, convert to an r-value.
768   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769   if (Res.isInvalid())
770     return ExprError();
771   E = Res.get();
772 
773   QualType Ty = E->getType();
774   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775 
776   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
777   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
778       (getLangOpts().getFPEvalMethod() !=
779            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
780        PP.getLastFPEvalPragmaLocation().isValid())) {
781     switch (EvalMethod) {
782     default:
783       llvm_unreachable("Unrecognized float evaluation method");
784       break;
785     case LangOptions::FEM_UnsetOnCommandLine:
786       llvm_unreachable("Float evaluation method should be set by now");
787       break;
788     case LangOptions::FEM_Double:
789       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
790         // Widen the expression to double.
791         return Ty->isComplexType()
792                    ? ImpCastExprToType(E,
793                                        Context.getComplexType(Context.DoubleTy),
794                                        CK_FloatingComplexCast)
795                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
796       break;
797     case LangOptions::FEM_Extended:
798       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
799         // Widen the expression to long double.
800         return Ty->isComplexType()
801                    ? ImpCastExprToType(
802                          E, Context.getComplexType(Context.LongDoubleTy),
803                          CK_FloatingComplexCast)
804                    : ImpCastExprToType(E, Context.LongDoubleTy,
805                                        CK_FloatingCast);
806       break;
807     }
808   }
809 
810   // Half FP have to be promoted to float unless it is natively supported
811   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
812     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
813 
814   // Try to perform integral promotions if the object has a theoretically
815   // promotable type.
816   if (Ty->isIntegralOrUnscopedEnumerationType()) {
817     // C99 6.3.1.1p2:
818     //
819     //   The following may be used in an expression wherever an int or
820     //   unsigned int may be used:
821     //     - an object or expression with an integer type whose integer
822     //       conversion rank is less than or equal to the rank of int
823     //       and unsigned int.
824     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
825     //
826     //   If an int can represent all values of the original type, the
827     //   value is converted to an int; otherwise, it is converted to an
828     //   unsigned int. These are called the integer promotions. All
829     //   other types are unchanged by the integer promotions.
830 
831     QualType PTy = Context.isPromotableBitField(E);
832     if (!PTy.isNull()) {
833       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
834       return E;
835     }
836     if (Ty->isPromotableIntegerType()) {
837       QualType PT = Context.getPromotedIntegerType(Ty);
838       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
839       return E;
840     }
841   }
842   return E;
843 }
844 
845 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
846 /// do not have a prototype. Arguments that have type float or __fp16
847 /// are promoted to double. All other argument types are converted by
848 /// UsualUnaryConversions().
849 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
850   QualType Ty = E->getType();
851   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
852 
853   ExprResult Res = UsualUnaryConversions(E);
854   if (Res.isInvalid())
855     return ExprError();
856   E = Res.get();
857 
858   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
859   // promote to double.
860   // Note that default argument promotion applies only to float (and
861   // half/fp16); it does not apply to _Float16.
862   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
863   if (BTy && (BTy->getKind() == BuiltinType::Half ||
864               BTy->getKind() == BuiltinType::Float)) {
865     if (getLangOpts().OpenCL &&
866         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
867       if (BTy->getKind() == BuiltinType::Half) {
868         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
869       }
870     } else {
871       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
872     }
873   }
874   if (BTy &&
875       getLangOpts().getExtendIntArgs() ==
876           LangOptions::ExtendArgsKind::ExtendTo64 &&
877       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
878       Context.getTypeSizeInChars(BTy) <
879           Context.getTypeSizeInChars(Context.LongLongTy)) {
880     E = (Ty->isUnsignedIntegerType())
881             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
882                   .get()
883             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
884     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
885            "Unexpected typesize for LongLongTy");
886   }
887 
888   // C++ performs lvalue-to-rvalue conversion as a default argument
889   // promotion, even on class types, but note:
890   //   C++11 [conv.lval]p2:
891   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
892   //     operand or a subexpression thereof the value contained in the
893   //     referenced object is not accessed. Otherwise, if the glvalue
894   //     has a class type, the conversion copy-initializes a temporary
895   //     of type T from the glvalue and the result of the conversion
896   //     is a prvalue for the temporary.
897   // FIXME: add some way to gate this entire thing for correctness in
898   // potentially potentially evaluated contexts.
899   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
900     ExprResult Temp = PerformCopyInitialization(
901                        InitializedEntity::InitializeTemporary(E->getType()),
902                                                 E->getExprLoc(), E);
903     if (Temp.isInvalid())
904       return ExprError();
905     E = Temp.get();
906   }
907 
908   return E;
909 }
910 
911 /// Determine the degree of POD-ness for an expression.
912 /// Incomplete types are considered POD, since this check can be performed
913 /// when we're in an unevaluated context.
914 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
915   if (Ty->isIncompleteType()) {
916     // C++11 [expr.call]p7:
917     //   After these conversions, if the argument does not have arithmetic,
918     //   enumeration, pointer, pointer to member, or class type, the program
919     //   is ill-formed.
920     //
921     // Since we've already performed array-to-pointer and function-to-pointer
922     // decay, the only such type in C++ is cv void. This also handles
923     // initializer lists as variadic arguments.
924     if (Ty->isVoidType())
925       return VAK_Invalid;
926 
927     if (Ty->isObjCObjectType())
928       return VAK_Invalid;
929     return VAK_Valid;
930   }
931 
932   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
933     return VAK_Invalid;
934 
935   if (Ty.isCXX98PODType(Context))
936     return VAK_Valid;
937 
938   // C++11 [expr.call]p7:
939   //   Passing a potentially-evaluated argument of class type (Clause 9)
940   //   having a non-trivial copy constructor, a non-trivial move constructor,
941   //   or a non-trivial destructor, with no corresponding parameter,
942   //   is conditionally-supported with implementation-defined semantics.
943   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
944     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
945       if (!Record->hasNonTrivialCopyConstructor() &&
946           !Record->hasNonTrivialMoveConstructor() &&
947           !Record->hasNonTrivialDestructor())
948         return VAK_ValidInCXX11;
949 
950   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
951     return VAK_Valid;
952 
953   if (Ty->isObjCObjectType())
954     return VAK_Invalid;
955 
956   if (getLangOpts().MSVCCompat)
957     return VAK_MSVCUndefined;
958 
959   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
960   // permitted to reject them. We should consider doing so.
961   return VAK_Undefined;
962 }
963 
964 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
965   // Don't allow one to pass an Objective-C interface to a vararg.
966   const QualType &Ty = E->getType();
967   VarArgKind VAK = isValidVarArgType(Ty);
968 
969   // Complain about passing non-POD types through varargs.
970   switch (VAK) {
971   case VAK_ValidInCXX11:
972     DiagRuntimeBehavior(
973         E->getBeginLoc(), nullptr,
974         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
975     LLVM_FALLTHROUGH;
976   case VAK_Valid:
977     if (Ty->isRecordType()) {
978       // This is unlikely to be what the user intended. If the class has a
979       // 'c_str' member function, the user probably meant to call that.
980       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
981                           PDiag(diag::warn_pass_class_arg_to_vararg)
982                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
983     }
984     break;
985 
986   case VAK_Undefined:
987   case VAK_MSVCUndefined:
988     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
989                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
990                             << getLangOpts().CPlusPlus11 << Ty << CT);
991     break;
992 
993   case VAK_Invalid:
994     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
995       Diag(E->getBeginLoc(),
996            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
997           << Ty << CT;
998     else if (Ty->isObjCObjectType())
999       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1000                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1001                               << Ty << CT);
1002     else
1003       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1004           << isa<InitListExpr>(E) << Ty << CT;
1005     break;
1006   }
1007 }
1008 
1009 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1010 /// will create a trap if the resulting type is not a POD type.
1011 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1012                                                   FunctionDecl *FDecl) {
1013   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1014     // Strip the unbridged-cast placeholder expression off, if applicable.
1015     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1016         (CT == VariadicMethod ||
1017          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1018       E = stripARCUnbridgedCast(E);
1019 
1020     // Otherwise, do normal placeholder checking.
1021     } else {
1022       ExprResult ExprRes = CheckPlaceholderExpr(E);
1023       if (ExprRes.isInvalid())
1024         return ExprError();
1025       E = ExprRes.get();
1026     }
1027   }
1028 
1029   ExprResult ExprRes = DefaultArgumentPromotion(E);
1030   if (ExprRes.isInvalid())
1031     return ExprError();
1032 
1033   // Copy blocks to the heap.
1034   if (ExprRes.get()->getType()->isBlockPointerType())
1035     maybeExtendBlockObject(ExprRes);
1036 
1037   E = ExprRes.get();
1038 
1039   // Diagnostics regarding non-POD argument types are
1040   // emitted along with format string checking in Sema::CheckFunctionCall().
1041   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1042     // Turn this into a trap.
1043     CXXScopeSpec SS;
1044     SourceLocation TemplateKWLoc;
1045     UnqualifiedId Name;
1046     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1047                        E->getBeginLoc());
1048     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1049                                           /*HasTrailingLParen=*/true,
1050                                           /*IsAddressOfOperand=*/false);
1051     if (TrapFn.isInvalid())
1052       return ExprError();
1053 
1054     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1055                                     None, E->getEndLoc());
1056     if (Call.isInvalid())
1057       return ExprError();
1058 
1059     ExprResult Comma =
1060         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1061     if (Comma.isInvalid())
1062       return ExprError();
1063     return Comma.get();
1064   }
1065 
1066   if (!getLangOpts().CPlusPlus &&
1067       RequireCompleteType(E->getExprLoc(), E->getType(),
1068                           diag::err_call_incomplete_argument))
1069     return ExprError();
1070 
1071   return E;
1072 }
1073 
1074 /// Converts an integer to complex float type.  Helper function of
1075 /// UsualArithmeticConversions()
1076 ///
1077 /// \return false if the integer expression is an integer type and is
1078 /// successfully converted to the complex type.
1079 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1080                                                   ExprResult &ComplexExpr,
1081                                                   QualType IntTy,
1082                                                   QualType ComplexTy,
1083                                                   bool SkipCast) {
1084   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1085   if (SkipCast) return false;
1086   if (IntTy->isIntegerType()) {
1087     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1088     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1089     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1090                                   CK_FloatingRealToComplex);
1091   } else {
1092     assert(IntTy->isComplexIntegerType());
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094                                   CK_IntegralComplexToFloatingComplex);
1095   }
1096   return false;
1097 }
1098 
1099 /// Handle arithmetic conversion with complex types.  Helper function of
1100 /// UsualArithmeticConversions()
1101 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1102                                              ExprResult &RHS, QualType LHSType,
1103                                              QualType RHSType,
1104                                              bool IsCompAssign) {
1105   // if we have an integer operand, the result is the complex type.
1106   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1107                                              /*skipCast*/false))
1108     return LHSType;
1109   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1110                                              /*skipCast*/IsCompAssign))
1111     return RHSType;
1112 
1113   // This handles complex/complex, complex/float, or float/complex.
1114   // When both operands are complex, the shorter operand is converted to the
1115   // type of the longer, and that is the type of the result. This corresponds
1116   // to what is done when combining two real floating-point operands.
1117   // The fun begins when size promotion occur across type domains.
1118   // From H&S 6.3.4: When one operand is complex and the other is a real
1119   // floating-point type, the less precise type is converted, within it's
1120   // real or complex domain, to the precision of the other type. For example,
1121   // when combining a "long double" with a "double _Complex", the
1122   // "double _Complex" is promoted to "long double _Complex".
1123 
1124   // Compute the rank of the two types, regardless of whether they are complex.
1125   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1126 
1127   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1128   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1129   QualType LHSElementType =
1130       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1131   QualType RHSElementType =
1132       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1133 
1134   QualType ResultType = S.Context.getComplexType(LHSElementType);
1135   if (Order < 0) {
1136     // Promote the precision of the LHS if not an assignment.
1137     ResultType = S.Context.getComplexType(RHSElementType);
1138     if (!IsCompAssign) {
1139       if (LHSComplexType)
1140         LHS =
1141             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1142       else
1143         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1144     }
1145   } else if (Order > 0) {
1146     // Promote the precision of the RHS.
1147     if (RHSComplexType)
1148       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1149     else
1150       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1151   }
1152   return ResultType;
1153 }
1154 
1155 /// Handle arithmetic conversion from integer to float.  Helper function
1156 /// of UsualArithmeticConversions()
1157 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1158                                            ExprResult &IntExpr,
1159                                            QualType FloatTy, QualType IntTy,
1160                                            bool ConvertFloat, bool ConvertInt) {
1161   if (IntTy->isIntegerType()) {
1162     if (ConvertInt)
1163       // Convert intExpr to the lhs floating point type.
1164       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1165                                     CK_IntegralToFloating);
1166     return FloatTy;
1167   }
1168 
1169   // Convert both sides to the appropriate complex float.
1170   assert(IntTy->isComplexIntegerType());
1171   QualType result = S.Context.getComplexType(FloatTy);
1172 
1173   // _Complex int -> _Complex float
1174   if (ConvertInt)
1175     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1176                                   CK_IntegralComplexToFloatingComplex);
1177 
1178   // float -> _Complex float
1179   if (ConvertFloat)
1180     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1181                                     CK_FloatingRealToComplex);
1182 
1183   return result;
1184 }
1185 
1186 /// Handle arithmethic conversion with floating point types.  Helper
1187 /// function of UsualArithmeticConversions()
1188 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1189                                       ExprResult &RHS, QualType LHSType,
1190                                       QualType RHSType, bool IsCompAssign) {
1191   bool LHSFloat = LHSType->isRealFloatingType();
1192   bool RHSFloat = RHSType->isRealFloatingType();
1193 
1194   // N1169 4.1.4: If one of the operands has a floating type and the other
1195   //              operand has a fixed-point type, the fixed-point operand
1196   //              is converted to the floating type [...]
1197   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1198     if (LHSFloat)
1199       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1200     else if (!IsCompAssign)
1201       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1202     return LHSFloat ? LHSType : RHSType;
1203   }
1204 
1205   // If we have two real floating types, convert the smaller operand
1206   // to the bigger result.
1207   if (LHSFloat && RHSFloat) {
1208     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1209     if (order > 0) {
1210       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1211       return LHSType;
1212     }
1213 
1214     assert(order < 0 && "illegal float comparison");
1215     if (!IsCompAssign)
1216       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1217     return RHSType;
1218   }
1219 
1220   if (LHSFloat) {
1221     // Half FP has to be promoted to float unless it is natively supported
1222     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1223       LHSType = S.Context.FloatTy;
1224 
1225     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1226                                       /*ConvertFloat=*/!IsCompAssign,
1227                                       /*ConvertInt=*/ true);
1228   }
1229   assert(RHSFloat);
1230   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1231                                     /*ConvertFloat=*/ true,
1232                                     /*ConvertInt=*/!IsCompAssign);
1233 }
1234 
1235 /// Diagnose attempts to convert between __float128, __ibm128 and
1236 /// long double if there is no support for such conversion.
1237 /// Helper function of UsualArithmeticConversions().
1238 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1239                                       QualType RHSType) {
1240   // No issue if either is not a floating point type.
1241   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1242     return false;
1243 
1244   // No issue if both have the same 128-bit float semantics.
1245   auto *LHSComplex = LHSType->getAs<ComplexType>();
1246   auto *RHSComplex = RHSType->getAs<ComplexType>();
1247 
1248   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1249   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1250 
1251   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1252   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1253 
1254   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1255        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1256       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1257        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1258     return false;
1259 
1260   return true;
1261 }
1262 
1263 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1264 
1265 namespace {
1266 /// These helper callbacks are placed in an anonymous namespace to
1267 /// permit their use as function template parameters.
1268 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1269   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1270 }
1271 
1272 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1273   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1274                              CK_IntegralComplexCast);
1275 }
1276 }
1277 
1278 /// Handle integer arithmetic conversions.  Helper function of
1279 /// UsualArithmeticConversions()
1280 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1281 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1282                                         ExprResult &RHS, QualType LHSType,
1283                                         QualType RHSType, bool IsCompAssign) {
1284   // The rules for this case are in C99 6.3.1.8
1285   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1286   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1287   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1288   if (LHSSigned == RHSSigned) {
1289     // Same signedness; use the higher-ranked type
1290     if (order >= 0) {
1291       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1292       return LHSType;
1293     } else if (!IsCompAssign)
1294       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1295     return RHSType;
1296   } else if (order != (LHSSigned ? 1 : -1)) {
1297     // The unsigned type has greater than or equal rank to the
1298     // signed type, so use the unsigned type
1299     if (RHSSigned) {
1300       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1301       return LHSType;
1302     } else if (!IsCompAssign)
1303       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1304     return RHSType;
1305   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1306     // The two types are different widths; if we are here, that
1307     // means the signed type is larger than the unsigned type, so
1308     // use the signed type.
1309     if (LHSSigned) {
1310       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1311       return LHSType;
1312     } else if (!IsCompAssign)
1313       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1314     return RHSType;
1315   } else {
1316     // The signed type is higher-ranked than the unsigned type,
1317     // but isn't actually any bigger (like unsigned int and long
1318     // on most 32-bit systems).  Use the unsigned type corresponding
1319     // to the signed type.
1320     QualType result =
1321       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1322     RHS = (*doRHSCast)(S, RHS.get(), result);
1323     if (!IsCompAssign)
1324       LHS = (*doLHSCast)(S, LHS.get(), result);
1325     return result;
1326   }
1327 }
1328 
1329 /// Handle conversions with GCC complex int extension.  Helper function
1330 /// of UsualArithmeticConversions()
1331 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1332                                            ExprResult &RHS, QualType LHSType,
1333                                            QualType RHSType,
1334                                            bool IsCompAssign) {
1335   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1336   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1337 
1338   if (LHSComplexInt && RHSComplexInt) {
1339     QualType LHSEltType = LHSComplexInt->getElementType();
1340     QualType RHSEltType = RHSComplexInt->getElementType();
1341     QualType ScalarType =
1342       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1343         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1344 
1345     return S.Context.getComplexType(ScalarType);
1346   }
1347 
1348   if (LHSComplexInt) {
1349     QualType LHSEltType = LHSComplexInt->getElementType();
1350     QualType ScalarType =
1351       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1352         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1353     QualType ComplexType = S.Context.getComplexType(ScalarType);
1354     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1355                               CK_IntegralRealToComplex);
1356 
1357     return ComplexType;
1358   }
1359 
1360   assert(RHSComplexInt);
1361 
1362   QualType RHSEltType = RHSComplexInt->getElementType();
1363   QualType ScalarType =
1364     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1365       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1366   QualType ComplexType = S.Context.getComplexType(ScalarType);
1367 
1368   if (!IsCompAssign)
1369     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1370                               CK_IntegralRealToComplex);
1371   return ComplexType;
1372 }
1373 
1374 /// Return the rank of a given fixed point or integer type. The value itself
1375 /// doesn't matter, but the values must be increasing with proper increasing
1376 /// rank as described in N1169 4.1.1.
1377 static unsigned GetFixedPointRank(QualType Ty) {
1378   const auto *BTy = Ty->getAs<BuiltinType>();
1379   assert(BTy && "Expected a builtin type.");
1380 
1381   switch (BTy->getKind()) {
1382   case BuiltinType::ShortFract:
1383   case BuiltinType::UShortFract:
1384   case BuiltinType::SatShortFract:
1385   case BuiltinType::SatUShortFract:
1386     return 1;
1387   case BuiltinType::Fract:
1388   case BuiltinType::UFract:
1389   case BuiltinType::SatFract:
1390   case BuiltinType::SatUFract:
1391     return 2;
1392   case BuiltinType::LongFract:
1393   case BuiltinType::ULongFract:
1394   case BuiltinType::SatLongFract:
1395   case BuiltinType::SatULongFract:
1396     return 3;
1397   case BuiltinType::ShortAccum:
1398   case BuiltinType::UShortAccum:
1399   case BuiltinType::SatShortAccum:
1400   case BuiltinType::SatUShortAccum:
1401     return 4;
1402   case BuiltinType::Accum:
1403   case BuiltinType::UAccum:
1404   case BuiltinType::SatAccum:
1405   case BuiltinType::SatUAccum:
1406     return 5;
1407   case BuiltinType::LongAccum:
1408   case BuiltinType::ULongAccum:
1409   case BuiltinType::SatLongAccum:
1410   case BuiltinType::SatULongAccum:
1411     return 6;
1412   default:
1413     if (BTy->isInteger())
1414       return 0;
1415     llvm_unreachable("Unexpected fixed point or integer type");
1416   }
1417 }
1418 
1419 /// handleFixedPointConversion - Fixed point operations between fixed
1420 /// point types and integers or other fixed point types do not fall under
1421 /// usual arithmetic conversion since these conversions could result in loss
1422 /// of precsision (N1169 4.1.4). These operations should be calculated with
1423 /// the full precision of their result type (N1169 4.1.6.2.1).
1424 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1425                                            QualType RHSTy) {
1426   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1427          "Expected at least one of the operands to be a fixed point type");
1428   assert((LHSTy->isFixedPointOrIntegerType() ||
1429           RHSTy->isFixedPointOrIntegerType()) &&
1430          "Special fixed point arithmetic operation conversions are only "
1431          "applied to ints or other fixed point types");
1432 
1433   // If one operand has signed fixed-point type and the other operand has
1434   // unsigned fixed-point type, then the unsigned fixed-point operand is
1435   // converted to its corresponding signed fixed-point type and the resulting
1436   // type is the type of the converted operand.
1437   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1438     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1439   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1440     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1441 
1442   // The result type is the type with the highest rank, whereby a fixed-point
1443   // conversion rank is always greater than an integer conversion rank; if the
1444   // type of either of the operands is a saturating fixedpoint type, the result
1445   // type shall be the saturating fixed-point type corresponding to the type
1446   // with the highest rank; the resulting value is converted (taking into
1447   // account rounding and overflow) to the precision of the resulting type.
1448   // Same ranks between signed and unsigned types are resolved earlier, so both
1449   // types are either signed or both unsigned at this point.
1450   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1451   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1452 
1453   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1454 
1455   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1456     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1457 
1458   return ResultTy;
1459 }
1460 
1461 /// Check that the usual arithmetic conversions can be performed on this pair of
1462 /// expressions that might be of enumeration type.
1463 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1464                                            SourceLocation Loc,
1465                                            Sema::ArithConvKind ACK) {
1466   // C++2a [expr.arith.conv]p1:
1467   //   If one operand is of enumeration type and the other operand is of a
1468   //   different enumeration type or a floating-point type, this behavior is
1469   //   deprecated ([depr.arith.conv.enum]).
1470   //
1471   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1472   // Eventually we will presumably reject these cases (in C++23 onwards?).
1473   QualType L = LHS->getType(), R = RHS->getType();
1474   bool LEnum = L->isUnscopedEnumerationType(),
1475        REnum = R->isUnscopedEnumerationType();
1476   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1477   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1478       (REnum && L->isFloatingType())) {
1479     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1480                     ? diag::warn_arith_conv_enum_float_cxx20
1481                     : diag::warn_arith_conv_enum_float)
1482         << LHS->getSourceRange() << RHS->getSourceRange()
1483         << (int)ACK << LEnum << L << R;
1484   } else if (!IsCompAssign && LEnum && REnum &&
1485              !S.Context.hasSameUnqualifiedType(L, R)) {
1486     unsigned DiagID;
1487     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1488         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1489       // If either enumeration type is unnamed, it's less likely that the
1490       // user cares about this, but this situation is still deprecated in
1491       // C++2a. Use a different warning group.
1492       DiagID = S.getLangOpts().CPlusPlus20
1493                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1494                     : diag::warn_arith_conv_mixed_anon_enum_types;
1495     } else if (ACK == Sema::ACK_Conditional) {
1496       // Conditional expressions are separated out because they have
1497       // historically had a different warning flag.
1498       DiagID = S.getLangOpts().CPlusPlus20
1499                    ? diag::warn_conditional_mixed_enum_types_cxx20
1500                    : diag::warn_conditional_mixed_enum_types;
1501     } else if (ACK == Sema::ACK_Comparison) {
1502       // Comparison expressions are separated out because they have
1503       // historically had a different warning flag.
1504       DiagID = S.getLangOpts().CPlusPlus20
1505                    ? diag::warn_comparison_mixed_enum_types_cxx20
1506                    : diag::warn_comparison_mixed_enum_types;
1507     } else {
1508       DiagID = S.getLangOpts().CPlusPlus20
1509                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1510                    : diag::warn_arith_conv_mixed_enum_types;
1511     }
1512     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1513                         << (int)ACK << L << R;
1514   }
1515 }
1516 
1517 /// UsualArithmeticConversions - Performs various conversions that are common to
1518 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1519 /// routine returns the first non-arithmetic type found. The client is
1520 /// responsible for emitting appropriate error diagnostics.
1521 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1522                                           SourceLocation Loc,
1523                                           ArithConvKind ACK) {
1524   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1525 
1526   if (ACK != ACK_CompAssign) {
1527     LHS = UsualUnaryConversions(LHS.get());
1528     if (LHS.isInvalid())
1529       return QualType();
1530   }
1531 
1532   RHS = UsualUnaryConversions(RHS.get());
1533   if (RHS.isInvalid())
1534     return QualType();
1535 
1536   // For conversion purposes, we ignore any qualifiers.
1537   // For example, "const float" and "float" are equivalent.
1538   QualType LHSType =
1539     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1540   QualType RHSType =
1541     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1542 
1543   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1544   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1545     LHSType = AtomicLHS->getValueType();
1546 
1547   // If both types are identical, no conversion is needed.
1548   if (LHSType == RHSType)
1549     return LHSType;
1550 
1551   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1552   // The caller can deal with this (e.g. pointer + int).
1553   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1554     return QualType();
1555 
1556   // Apply unary and bitfield promotions to the LHS's type.
1557   QualType LHSUnpromotedType = LHSType;
1558   if (LHSType->isPromotableIntegerType())
1559     LHSType = Context.getPromotedIntegerType(LHSType);
1560   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1561   if (!LHSBitfieldPromoteTy.isNull())
1562     LHSType = LHSBitfieldPromoteTy;
1563   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1564     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1565 
1566   // If both types are identical, no conversion is needed.
1567   if (LHSType == RHSType)
1568     return LHSType;
1569 
1570   // At this point, we have two different arithmetic types.
1571 
1572   // Diagnose attempts to convert between __ibm128, __float128 and long double
1573   // where such conversions currently can't be handled.
1574   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1575     return QualType();
1576 
1577   // Handle complex types first (C99 6.3.1.8p1).
1578   if (LHSType->isComplexType() || RHSType->isComplexType())
1579     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1580                                         ACK == ACK_CompAssign);
1581 
1582   // Now handle "real" floating types (i.e. float, double, long double).
1583   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1584     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1585                                  ACK == ACK_CompAssign);
1586 
1587   // Handle GCC complex int extension.
1588   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1589     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1590                                       ACK == ACK_CompAssign);
1591 
1592   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1593     return handleFixedPointConversion(*this, LHSType, RHSType);
1594 
1595   // Finally, we have two differing integer types.
1596   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1597            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1598 }
1599 
1600 //===----------------------------------------------------------------------===//
1601 //  Semantic Analysis for various Expression Types
1602 //===----------------------------------------------------------------------===//
1603 
1604 
1605 ExprResult
1606 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1607                                 SourceLocation DefaultLoc,
1608                                 SourceLocation RParenLoc,
1609                                 Expr *ControllingExpr,
1610                                 ArrayRef<ParsedType> ArgTypes,
1611                                 ArrayRef<Expr *> ArgExprs) {
1612   unsigned NumAssocs = ArgTypes.size();
1613   assert(NumAssocs == ArgExprs.size());
1614 
1615   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1616   for (unsigned i = 0; i < NumAssocs; ++i) {
1617     if (ArgTypes[i])
1618       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1619     else
1620       Types[i] = nullptr;
1621   }
1622 
1623   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1624                                              ControllingExpr,
1625                                              llvm::makeArrayRef(Types, NumAssocs),
1626                                              ArgExprs);
1627   delete [] Types;
1628   return ER;
1629 }
1630 
1631 ExprResult
1632 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1633                                  SourceLocation DefaultLoc,
1634                                  SourceLocation RParenLoc,
1635                                  Expr *ControllingExpr,
1636                                  ArrayRef<TypeSourceInfo *> Types,
1637                                  ArrayRef<Expr *> Exprs) {
1638   unsigned NumAssocs = Types.size();
1639   assert(NumAssocs == Exprs.size());
1640 
1641   // Decay and strip qualifiers for the controlling expression type, and handle
1642   // placeholder type replacement. See committee discussion from WG14 DR423.
1643   {
1644     EnterExpressionEvaluationContext Unevaluated(
1645         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1646     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1647     if (R.isInvalid())
1648       return ExprError();
1649     ControllingExpr = R.get();
1650   }
1651 
1652   // The controlling expression is an unevaluated operand, so side effects are
1653   // likely unintended.
1654   if (!inTemplateInstantiation() &&
1655       ControllingExpr->HasSideEffects(Context, false))
1656     Diag(ControllingExpr->getExprLoc(),
1657          diag::warn_side_effects_unevaluated_context);
1658 
1659   bool TypeErrorFound = false,
1660        IsResultDependent = ControllingExpr->isTypeDependent(),
1661        ContainsUnexpandedParameterPack
1662          = ControllingExpr->containsUnexpandedParameterPack();
1663 
1664   for (unsigned i = 0; i < NumAssocs; ++i) {
1665     if (Exprs[i]->containsUnexpandedParameterPack())
1666       ContainsUnexpandedParameterPack = true;
1667 
1668     if (Types[i]) {
1669       if (Types[i]->getType()->containsUnexpandedParameterPack())
1670         ContainsUnexpandedParameterPack = true;
1671 
1672       if (Types[i]->getType()->isDependentType()) {
1673         IsResultDependent = true;
1674       } else {
1675         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1676         // complete object type other than a variably modified type."
1677         unsigned D = 0;
1678         if (Types[i]->getType()->isIncompleteType())
1679           D = diag::err_assoc_type_incomplete;
1680         else if (!Types[i]->getType()->isObjectType())
1681           D = diag::err_assoc_type_nonobject;
1682         else if (Types[i]->getType()->isVariablyModifiedType())
1683           D = diag::err_assoc_type_variably_modified;
1684 
1685         if (D != 0) {
1686           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1687             << Types[i]->getTypeLoc().getSourceRange()
1688             << Types[i]->getType();
1689           TypeErrorFound = true;
1690         }
1691 
1692         // C11 6.5.1.1p2 "No two generic associations in the same generic
1693         // selection shall specify compatible types."
1694         for (unsigned j = i+1; j < NumAssocs; ++j)
1695           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1696               Context.typesAreCompatible(Types[i]->getType(),
1697                                          Types[j]->getType())) {
1698             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1699                  diag::err_assoc_compatible_types)
1700               << Types[j]->getTypeLoc().getSourceRange()
1701               << Types[j]->getType()
1702               << Types[i]->getType();
1703             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1704                  diag::note_compat_assoc)
1705               << Types[i]->getTypeLoc().getSourceRange()
1706               << Types[i]->getType();
1707             TypeErrorFound = true;
1708           }
1709       }
1710     }
1711   }
1712   if (TypeErrorFound)
1713     return ExprError();
1714 
1715   // If we determined that the generic selection is result-dependent, don't
1716   // try to compute the result expression.
1717   if (IsResultDependent)
1718     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1719                                         Exprs, DefaultLoc, RParenLoc,
1720                                         ContainsUnexpandedParameterPack);
1721 
1722   SmallVector<unsigned, 1> CompatIndices;
1723   unsigned DefaultIndex = -1U;
1724   for (unsigned i = 0; i < NumAssocs; ++i) {
1725     if (!Types[i])
1726       DefaultIndex = i;
1727     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1728                                         Types[i]->getType()))
1729       CompatIndices.push_back(i);
1730   }
1731 
1732   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1733   // type compatible with at most one of the types named in its generic
1734   // association list."
1735   if (CompatIndices.size() > 1) {
1736     // We strip parens here because the controlling expression is typically
1737     // parenthesized in macro definitions.
1738     ControllingExpr = ControllingExpr->IgnoreParens();
1739     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1740         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1741         << (unsigned)CompatIndices.size();
1742     for (unsigned I : CompatIndices) {
1743       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1744            diag::note_compat_assoc)
1745         << Types[I]->getTypeLoc().getSourceRange()
1746         << Types[I]->getType();
1747     }
1748     return ExprError();
1749   }
1750 
1751   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1752   // its controlling expression shall have type compatible with exactly one of
1753   // the types named in its generic association list."
1754   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1755     // We strip parens here because the controlling expression is typically
1756     // parenthesized in macro definitions.
1757     ControllingExpr = ControllingExpr->IgnoreParens();
1758     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1759         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1760     return ExprError();
1761   }
1762 
1763   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1764   // type name that is compatible with the type of the controlling expression,
1765   // then the result expression of the generic selection is the expression
1766   // in that generic association. Otherwise, the result expression of the
1767   // generic selection is the expression in the default generic association."
1768   unsigned ResultIndex =
1769     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1770 
1771   return GenericSelectionExpr::Create(
1772       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1773       ContainsUnexpandedParameterPack, ResultIndex);
1774 }
1775 
1776 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1777 /// location of the token and the offset of the ud-suffix within it.
1778 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1779                                      unsigned Offset) {
1780   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1781                                         S.getLangOpts());
1782 }
1783 
1784 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1785 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1786 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1787                                                  IdentifierInfo *UDSuffix,
1788                                                  SourceLocation UDSuffixLoc,
1789                                                  ArrayRef<Expr*> Args,
1790                                                  SourceLocation LitEndLoc) {
1791   assert(Args.size() <= 2 && "too many arguments for literal operator");
1792 
1793   QualType ArgTy[2];
1794   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1795     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1796     if (ArgTy[ArgIdx]->isArrayType())
1797       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1798   }
1799 
1800   DeclarationName OpName =
1801     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1802   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1803   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1804 
1805   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1806   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1807                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1808                               /*AllowStringTemplatePack*/ false,
1809                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1810     return ExprError();
1811 
1812   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1813 }
1814 
1815 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1816 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1817 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1818 /// multiple tokens.  However, the common case is that StringToks points to one
1819 /// string.
1820 ///
1821 ExprResult
1822 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1823   assert(!StringToks.empty() && "Must have at least one string!");
1824 
1825   StringLiteralParser Literal(StringToks, PP);
1826   if (Literal.hadError)
1827     return ExprError();
1828 
1829   SmallVector<SourceLocation, 4> StringTokLocs;
1830   for (const Token &Tok : StringToks)
1831     StringTokLocs.push_back(Tok.getLocation());
1832 
1833   QualType CharTy = Context.CharTy;
1834   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1835   if (Literal.isWide()) {
1836     CharTy = Context.getWideCharType();
1837     Kind = StringLiteral::Wide;
1838   } else if (Literal.isUTF8()) {
1839     if (getLangOpts().Char8)
1840       CharTy = Context.Char8Ty;
1841     Kind = StringLiteral::UTF8;
1842   } else if (Literal.isUTF16()) {
1843     CharTy = Context.Char16Ty;
1844     Kind = StringLiteral::UTF16;
1845   } else if (Literal.isUTF32()) {
1846     CharTy = Context.Char32Ty;
1847     Kind = StringLiteral::UTF32;
1848   } else if (Literal.isPascal()) {
1849     CharTy = Context.UnsignedCharTy;
1850   }
1851 
1852   // Warn on initializing an array of char from a u8 string literal; this
1853   // becomes ill-formed in C++2a.
1854   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1855       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1856     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1857 
1858     // Create removals for all 'u8' prefixes in the string literal(s). This
1859     // ensures C++2a compatibility (but may change the program behavior when
1860     // built by non-Clang compilers for which the execution character set is
1861     // not always UTF-8).
1862     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1863     SourceLocation RemovalDiagLoc;
1864     for (const Token &Tok : StringToks) {
1865       if (Tok.getKind() == tok::utf8_string_literal) {
1866         if (RemovalDiagLoc.isInvalid())
1867           RemovalDiagLoc = Tok.getLocation();
1868         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1869             Tok.getLocation(),
1870             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1871                                            getSourceManager(), getLangOpts())));
1872       }
1873     }
1874     Diag(RemovalDiagLoc, RemovalDiag);
1875   }
1876 
1877   QualType StrTy =
1878       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1879 
1880   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1881   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1882                                              Kind, Literal.Pascal, StrTy,
1883                                              &StringTokLocs[0],
1884                                              StringTokLocs.size());
1885   if (Literal.getUDSuffix().empty())
1886     return Lit;
1887 
1888   // We're building a user-defined literal.
1889   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1890   SourceLocation UDSuffixLoc =
1891     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1892                    Literal.getUDSuffixOffset());
1893 
1894   // Make sure we're allowed user-defined literals here.
1895   if (!UDLScope)
1896     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1897 
1898   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1899   //   operator "" X (str, len)
1900   QualType SizeType = Context.getSizeType();
1901 
1902   DeclarationName OpName =
1903     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1904   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1905   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1906 
1907   QualType ArgTy[] = {
1908     Context.getArrayDecayedType(StrTy), SizeType
1909   };
1910 
1911   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1912   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1913                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1914                                 /*AllowStringTemplatePack*/ true,
1915                                 /*DiagnoseMissing*/ true, Lit)) {
1916 
1917   case LOLR_Cooked: {
1918     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1919     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1920                                                     StringTokLocs[0]);
1921     Expr *Args[] = { Lit, LenArg };
1922 
1923     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1924   }
1925 
1926   case LOLR_Template: {
1927     TemplateArgumentListInfo ExplicitArgs;
1928     TemplateArgument Arg(Lit);
1929     TemplateArgumentLocInfo ArgInfo(Lit);
1930     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1931     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1932                                     &ExplicitArgs);
1933   }
1934 
1935   case LOLR_StringTemplatePack: {
1936     TemplateArgumentListInfo ExplicitArgs;
1937 
1938     unsigned CharBits = Context.getIntWidth(CharTy);
1939     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1940     llvm::APSInt Value(CharBits, CharIsUnsigned);
1941 
1942     TemplateArgument TypeArg(CharTy);
1943     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1944     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1945 
1946     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1947       Value = Lit->getCodeUnit(I);
1948       TemplateArgument Arg(Context, Value, CharTy);
1949       TemplateArgumentLocInfo ArgInfo;
1950       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1951     }
1952     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1953                                     &ExplicitArgs);
1954   }
1955   case LOLR_Raw:
1956   case LOLR_ErrorNoDiagnostic:
1957     llvm_unreachable("unexpected literal operator lookup result");
1958   case LOLR_Error:
1959     return ExprError();
1960   }
1961   llvm_unreachable("unexpected literal operator lookup result");
1962 }
1963 
1964 DeclRefExpr *
1965 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1966                        SourceLocation Loc,
1967                        const CXXScopeSpec *SS) {
1968   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1969   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1970 }
1971 
1972 DeclRefExpr *
1973 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1974                        const DeclarationNameInfo &NameInfo,
1975                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1976                        SourceLocation TemplateKWLoc,
1977                        const TemplateArgumentListInfo *TemplateArgs) {
1978   NestedNameSpecifierLoc NNS =
1979       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1980   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1981                           TemplateArgs);
1982 }
1983 
1984 // CUDA/HIP: Check whether a captured reference variable is referencing a
1985 // host variable in a device or host device lambda.
1986 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1987                                                             VarDecl *VD) {
1988   if (!S.getLangOpts().CUDA || !VD->hasInit())
1989     return false;
1990   assert(VD->getType()->isReferenceType());
1991 
1992   // Check whether the reference variable is referencing a host variable.
1993   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1994   if (!DRE)
1995     return false;
1996   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1997   if (!Referee || !Referee->hasGlobalStorage() ||
1998       Referee->hasAttr<CUDADeviceAttr>())
1999     return false;
2000 
2001   // Check whether the current function is a device or host device lambda.
2002   // Check whether the reference variable is a capture by getDeclContext()
2003   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2004   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2005   if (MD && MD->getParent()->isLambda() &&
2006       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2007       VD->getDeclContext() != MD)
2008     return true;
2009 
2010   return false;
2011 }
2012 
2013 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2014   // A declaration named in an unevaluated operand never constitutes an odr-use.
2015   if (isUnevaluatedContext())
2016     return NOUR_Unevaluated;
2017 
2018   // C++2a [basic.def.odr]p4:
2019   //   A variable x whose name appears as a potentially-evaluated expression e
2020   //   is odr-used by e unless [...] x is a reference that is usable in
2021   //   constant expressions.
2022   // CUDA/HIP:
2023   //   If a reference variable referencing a host variable is captured in a
2024   //   device or host device lambda, the value of the referee must be copied
2025   //   to the capture and the reference variable must be treated as odr-use
2026   //   since the value of the referee is not known at compile time and must
2027   //   be loaded from the captured.
2028   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2029     if (VD->getType()->isReferenceType() &&
2030         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2031         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2032         VD->isUsableInConstantExpressions(Context))
2033       return NOUR_Constant;
2034   }
2035 
2036   // All remaining non-variable cases constitute an odr-use. For variables, we
2037   // need to wait and see how the expression is used.
2038   return NOUR_None;
2039 }
2040 
2041 /// BuildDeclRefExpr - Build an expression that references a
2042 /// declaration that does not require a closure capture.
2043 DeclRefExpr *
2044 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2045                        const DeclarationNameInfo &NameInfo,
2046                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2047                        SourceLocation TemplateKWLoc,
2048                        const TemplateArgumentListInfo *TemplateArgs) {
2049   bool RefersToCapturedVariable =
2050       isa<VarDecl>(D) &&
2051       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2052 
2053   DeclRefExpr *E = DeclRefExpr::Create(
2054       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2055       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2056   MarkDeclRefReferenced(E);
2057 
2058   // C++ [except.spec]p17:
2059   //   An exception-specification is considered to be needed when:
2060   //   - in an expression, the function is the unique lookup result or
2061   //     the selected member of a set of overloaded functions.
2062   //
2063   // We delay doing this until after we've built the function reference and
2064   // marked it as used so that:
2065   //  a) if the function is defaulted, we get errors from defining it before /
2066   //     instead of errors from computing its exception specification, and
2067   //  b) if the function is a defaulted comparison, we can use the body we
2068   //     build when defining it as input to the exception specification
2069   //     computation rather than computing a new body.
2070   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2071     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2072       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2073         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2074     }
2075   }
2076 
2077   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2078       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2079       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2080     getCurFunction()->recordUseOfWeak(E);
2081 
2082   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2083   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2084     FD = IFD->getAnonField();
2085   if (FD) {
2086     UnusedPrivateFields.remove(FD);
2087     // Just in case we're building an illegal pointer-to-member.
2088     if (FD->isBitField())
2089       E->setObjectKind(OK_BitField);
2090   }
2091 
2092   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2093   // designates a bit-field.
2094   if (auto *BD = dyn_cast<BindingDecl>(D))
2095     if (auto *BE = BD->getBinding())
2096       E->setObjectKind(BE->getObjectKind());
2097 
2098   return E;
2099 }
2100 
2101 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2102 /// possibly a list of template arguments.
2103 ///
2104 /// If this produces template arguments, it is permitted to call
2105 /// DecomposeTemplateName.
2106 ///
2107 /// This actually loses a lot of source location information for
2108 /// non-standard name kinds; we should consider preserving that in
2109 /// some way.
2110 void
2111 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2112                              TemplateArgumentListInfo &Buffer,
2113                              DeclarationNameInfo &NameInfo,
2114                              const TemplateArgumentListInfo *&TemplateArgs) {
2115   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2116     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2117     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2118 
2119     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2120                                        Id.TemplateId->NumArgs);
2121     translateTemplateArguments(TemplateArgsPtr, Buffer);
2122 
2123     TemplateName TName = Id.TemplateId->Template.get();
2124     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2125     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2126     TemplateArgs = &Buffer;
2127   } else {
2128     NameInfo = GetNameFromUnqualifiedId(Id);
2129     TemplateArgs = nullptr;
2130   }
2131 }
2132 
2133 static void emitEmptyLookupTypoDiagnostic(
2134     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2135     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2136     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2137   DeclContext *Ctx =
2138       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2139   if (!TC) {
2140     // Emit a special diagnostic for failed member lookups.
2141     // FIXME: computing the declaration context might fail here (?)
2142     if (Ctx)
2143       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2144                                                  << SS.getRange();
2145     else
2146       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2147     return;
2148   }
2149 
2150   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2151   bool DroppedSpecifier =
2152       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2153   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2154                         ? diag::note_implicit_param_decl
2155                         : diag::note_previous_decl;
2156   if (!Ctx)
2157     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2158                          SemaRef.PDiag(NoteID));
2159   else
2160     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2161                                  << Typo << Ctx << DroppedSpecifier
2162                                  << SS.getRange(),
2163                          SemaRef.PDiag(NoteID));
2164 }
2165 
2166 /// Diagnose a lookup that found results in an enclosing class during error
2167 /// recovery. This usually indicates that the results were found in a dependent
2168 /// base class that could not be searched as part of a template definition.
2169 /// Always issues a diagnostic (though this may be only a warning in MS
2170 /// compatibility mode).
2171 ///
2172 /// Return \c true if the error is unrecoverable, or \c false if the caller
2173 /// should attempt to recover using these lookup results.
2174 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2175   // During a default argument instantiation the CurContext points
2176   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2177   // function parameter list, hence add an explicit check.
2178   bool isDefaultArgument =
2179       !CodeSynthesisContexts.empty() &&
2180       CodeSynthesisContexts.back().Kind ==
2181           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2182   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2183   bool isInstance = CurMethod && CurMethod->isInstance() &&
2184                     R.getNamingClass() == CurMethod->getParent() &&
2185                     !isDefaultArgument;
2186 
2187   // There are two ways we can find a class-scope declaration during template
2188   // instantiation that we did not find in the template definition: if it is a
2189   // member of a dependent base class, or if it is declared after the point of
2190   // use in the same class. Distinguish these by comparing the class in which
2191   // the member was found to the naming class of the lookup.
2192   unsigned DiagID = diag::err_found_in_dependent_base;
2193   unsigned NoteID = diag::note_member_declared_at;
2194   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2195     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2196                                       : diag::err_found_later_in_class;
2197   } else if (getLangOpts().MSVCCompat) {
2198     DiagID = diag::ext_found_in_dependent_base;
2199     NoteID = diag::note_dependent_member_use;
2200   }
2201 
2202   if (isInstance) {
2203     // Give a code modification hint to insert 'this->'.
2204     Diag(R.getNameLoc(), DiagID)
2205         << R.getLookupName()
2206         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2207     CheckCXXThisCapture(R.getNameLoc());
2208   } else {
2209     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2210     // they're not shadowed).
2211     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2212   }
2213 
2214   for (NamedDecl *D : R)
2215     Diag(D->getLocation(), NoteID);
2216 
2217   // Return true if we are inside a default argument instantiation
2218   // and the found name refers to an instance member function, otherwise
2219   // the caller will try to create an implicit member call and this is wrong
2220   // for default arguments.
2221   //
2222   // FIXME: Is this special case necessary? We could allow the caller to
2223   // diagnose this.
2224   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2225     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2226     return true;
2227   }
2228 
2229   // Tell the callee to try to recover.
2230   return false;
2231 }
2232 
2233 /// Diagnose an empty lookup.
2234 ///
2235 /// \return false if new lookup candidates were found
2236 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2237                                CorrectionCandidateCallback &CCC,
2238                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2239                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2240   DeclarationName Name = R.getLookupName();
2241 
2242   unsigned diagnostic = diag::err_undeclared_var_use;
2243   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2244   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2245       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2246       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2247     diagnostic = diag::err_undeclared_use;
2248     diagnostic_suggest = diag::err_undeclared_use_suggest;
2249   }
2250 
2251   // If the original lookup was an unqualified lookup, fake an
2252   // unqualified lookup.  This is useful when (for example) the
2253   // original lookup would not have found something because it was a
2254   // dependent name.
2255   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2256   while (DC) {
2257     if (isa<CXXRecordDecl>(DC)) {
2258       LookupQualifiedName(R, DC);
2259 
2260       if (!R.empty()) {
2261         // Don't give errors about ambiguities in this lookup.
2262         R.suppressDiagnostics();
2263 
2264         // If there's a best viable function among the results, only mention
2265         // that one in the notes.
2266         OverloadCandidateSet Candidates(R.getNameLoc(),
2267                                         OverloadCandidateSet::CSK_Normal);
2268         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2269         OverloadCandidateSet::iterator Best;
2270         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2271             OR_Success) {
2272           R.clear();
2273           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2274           R.resolveKind();
2275         }
2276 
2277         return DiagnoseDependentMemberLookup(R);
2278       }
2279 
2280       R.clear();
2281     }
2282 
2283     DC = DC->getLookupParent();
2284   }
2285 
2286   // We didn't find anything, so try to correct for a typo.
2287   TypoCorrection Corrected;
2288   if (S && Out) {
2289     SourceLocation TypoLoc = R.getNameLoc();
2290     assert(!ExplicitTemplateArgs &&
2291            "Diagnosing an empty lookup with explicit template args!");
2292     *Out = CorrectTypoDelayed(
2293         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2294         [=](const TypoCorrection &TC) {
2295           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2296                                         diagnostic, diagnostic_suggest);
2297         },
2298         nullptr, CTK_ErrorRecovery);
2299     if (*Out)
2300       return true;
2301   } else if (S &&
2302              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2303                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2304     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2305     bool DroppedSpecifier =
2306         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2307     R.setLookupName(Corrected.getCorrection());
2308 
2309     bool AcceptableWithRecovery = false;
2310     bool AcceptableWithoutRecovery = false;
2311     NamedDecl *ND = Corrected.getFoundDecl();
2312     if (ND) {
2313       if (Corrected.isOverloaded()) {
2314         OverloadCandidateSet OCS(R.getNameLoc(),
2315                                  OverloadCandidateSet::CSK_Normal);
2316         OverloadCandidateSet::iterator Best;
2317         for (NamedDecl *CD : Corrected) {
2318           if (FunctionTemplateDecl *FTD =
2319                    dyn_cast<FunctionTemplateDecl>(CD))
2320             AddTemplateOverloadCandidate(
2321                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2322                 Args, OCS);
2323           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2324             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2325               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2326                                    Args, OCS);
2327         }
2328         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2329         case OR_Success:
2330           ND = Best->FoundDecl;
2331           Corrected.setCorrectionDecl(ND);
2332           break;
2333         default:
2334           // FIXME: Arbitrarily pick the first declaration for the note.
2335           Corrected.setCorrectionDecl(ND);
2336           break;
2337         }
2338       }
2339       R.addDecl(ND);
2340       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2341         CXXRecordDecl *Record = nullptr;
2342         if (Corrected.getCorrectionSpecifier()) {
2343           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2344           Record = Ty->getAsCXXRecordDecl();
2345         }
2346         if (!Record)
2347           Record = cast<CXXRecordDecl>(
2348               ND->getDeclContext()->getRedeclContext());
2349         R.setNamingClass(Record);
2350       }
2351 
2352       auto *UnderlyingND = ND->getUnderlyingDecl();
2353       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2354                                isa<FunctionTemplateDecl>(UnderlyingND);
2355       // FIXME: If we ended up with a typo for a type name or
2356       // Objective-C class name, we're in trouble because the parser
2357       // is in the wrong place to recover. Suggest the typo
2358       // correction, but don't make it a fix-it since we're not going
2359       // to recover well anyway.
2360       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2361                                   getAsTypeTemplateDecl(UnderlyingND) ||
2362                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2363     } else {
2364       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2365       // because we aren't able to recover.
2366       AcceptableWithoutRecovery = true;
2367     }
2368 
2369     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2370       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2371                             ? diag::note_implicit_param_decl
2372                             : diag::note_previous_decl;
2373       if (SS.isEmpty())
2374         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2375                      PDiag(NoteID), AcceptableWithRecovery);
2376       else
2377         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2378                                   << Name << computeDeclContext(SS, false)
2379                                   << DroppedSpecifier << SS.getRange(),
2380                      PDiag(NoteID), AcceptableWithRecovery);
2381 
2382       // Tell the callee whether to try to recover.
2383       return !AcceptableWithRecovery;
2384     }
2385   }
2386   R.clear();
2387 
2388   // Emit a special diagnostic for failed member lookups.
2389   // FIXME: computing the declaration context might fail here (?)
2390   if (!SS.isEmpty()) {
2391     Diag(R.getNameLoc(), diag::err_no_member)
2392       << Name << computeDeclContext(SS, false)
2393       << SS.getRange();
2394     return true;
2395   }
2396 
2397   // Give up, we can't recover.
2398   Diag(R.getNameLoc(), diagnostic) << Name;
2399   return true;
2400 }
2401 
2402 /// In Microsoft mode, if we are inside a template class whose parent class has
2403 /// dependent base classes, and we can't resolve an unqualified identifier, then
2404 /// assume the identifier is a member of a dependent base class.  We can only
2405 /// recover successfully in static methods, instance methods, and other contexts
2406 /// where 'this' is available.  This doesn't precisely match MSVC's
2407 /// instantiation model, but it's close enough.
2408 static Expr *
2409 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2410                                DeclarationNameInfo &NameInfo,
2411                                SourceLocation TemplateKWLoc,
2412                                const TemplateArgumentListInfo *TemplateArgs) {
2413   // Only try to recover from lookup into dependent bases in static methods or
2414   // contexts where 'this' is available.
2415   QualType ThisType = S.getCurrentThisType();
2416   const CXXRecordDecl *RD = nullptr;
2417   if (!ThisType.isNull())
2418     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2419   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2420     RD = MD->getParent();
2421   if (!RD || !RD->hasAnyDependentBases())
2422     return nullptr;
2423 
2424   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2425   // is available, suggest inserting 'this->' as a fixit.
2426   SourceLocation Loc = NameInfo.getLoc();
2427   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2428   DB << NameInfo.getName() << RD;
2429 
2430   if (!ThisType.isNull()) {
2431     DB << FixItHint::CreateInsertion(Loc, "this->");
2432     return CXXDependentScopeMemberExpr::Create(
2433         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2434         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2435         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2436   }
2437 
2438   // Synthesize a fake NNS that points to the derived class.  This will
2439   // perform name lookup during template instantiation.
2440   CXXScopeSpec SS;
2441   auto *NNS =
2442       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2443   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2444   return DependentScopeDeclRefExpr::Create(
2445       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2446       TemplateArgs);
2447 }
2448 
2449 ExprResult
2450 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2451                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2452                         bool HasTrailingLParen, bool IsAddressOfOperand,
2453                         CorrectionCandidateCallback *CCC,
2454                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2455   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2456          "cannot be direct & operand and have a trailing lparen");
2457   if (SS.isInvalid())
2458     return ExprError();
2459 
2460   TemplateArgumentListInfo TemplateArgsBuffer;
2461 
2462   // Decompose the UnqualifiedId into the following data.
2463   DeclarationNameInfo NameInfo;
2464   const TemplateArgumentListInfo *TemplateArgs;
2465   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2466 
2467   DeclarationName Name = NameInfo.getName();
2468   IdentifierInfo *II = Name.getAsIdentifierInfo();
2469   SourceLocation NameLoc = NameInfo.getLoc();
2470 
2471   if (II && II->isEditorPlaceholder()) {
2472     // FIXME: When typed placeholders are supported we can create a typed
2473     // placeholder expression node.
2474     return ExprError();
2475   }
2476 
2477   // C++ [temp.dep.expr]p3:
2478   //   An id-expression is type-dependent if it contains:
2479   //     -- an identifier that was declared with a dependent type,
2480   //        (note: handled after lookup)
2481   //     -- a template-id that is dependent,
2482   //        (note: handled in BuildTemplateIdExpr)
2483   //     -- a conversion-function-id that specifies a dependent type,
2484   //     -- a nested-name-specifier that contains a class-name that
2485   //        names a dependent type.
2486   // Determine whether this is a member of an unknown specialization;
2487   // we need to handle these differently.
2488   bool DependentID = false;
2489   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2490       Name.getCXXNameType()->isDependentType()) {
2491     DependentID = true;
2492   } else if (SS.isSet()) {
2493     if (DeclContext *DC = computeDeclContext(SS, false)) {
2494       if (RequireCompleteDeclContext(SS, DC))
2495         return ExprError();
2496     } else {
2497       DependentID = true;
2498     }
2499   }
2500 
2501   if (DependentID)
2502     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2503                                       IsAddressOfOperand, TemplateArgs);
2504 
2505   // Perform the required lookup.
2506   LookupResult R(*this, NameInfo,
2507                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2508                      ? LookupObjCImplicitSelfParam
2509                      : LookupOrdinaryName);
2510   if (TemplateKWLoc.isValid() || TemplateArgs) {
2511     // Lookup the template name again to correctly establish the context in
2512     // which it was found. This is really unfortunate as we already did the
2513     // lookup to determine that it was a template name in the first place. If
2514     // this becomes a performance hit, we can work harder to preserve those
2515     // results until we get here but it's likely not worth it.
2516     bool MemberOfUnknownSpecialization;
2517     AssumedTemplateKind AssumedTemplate;
2518     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2519                            MemberOfUnknownSpecialization, TemplateKWLoc,
2520                            &AssumedTemplate))
2521       return ExprError();
2522 
2523     if (MemberOfUnknownSpecialization ||
2524         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2525       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2526                                         IsAddressOfOperand, TemplateArgs);
2527   } else {
2528     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2529     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2530 
2531     // If the result might be in a dependent base class, this is a dependent
2532     // id-expression.
2533     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2534       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2535                                         IsAddressOfOperand, TemplateArgs);
2536 
2537     // If this reference is in an Objective-C method, then we need to do
2538     // some special Objective-C lookup, too.
2539     if (IvarLookupFollowUp) {
2540       ExprResult E(LookupInObjCMethod(R, S, II, true));
2541       if (E.isInvalid())
2542         return ExprError();
2543 
2544       if (Expr *Ex = E.getAs<Expr>())
2545         return Ex;
2546     }
2547   }
2548 
2549   if (R.isAmbiguous())
2550     return ExprError();
2551 
2552   // This could be an implicitly declared function reference (legal in C90,
2553   // extension in C99, forbidden in C++).
2554   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2555     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2556     if (D) R.addDecl(D);
2557   }
2558 
2559   // Determine whether this name might be a candidate for
2560   // argument-dependent lookup.
2561   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2562 
2563   if (R.empty() && !ADL) {
2564     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2565       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2566                                                    TemplateKWLoc, TemplateArgs))
2567         return E;
2568     }
2569 
2570     // Don't diagnose an empty lookup for inline assembly.
2571     if (IsInlineAsmIdentifier)
2572       return ExprError();
2573 
2574     // If this name wasn't predeclared and if this is not a function
2575     // call, diagnose the problem.
2576     TypoExpr *TE = nullptr;
2577     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2578                                                        : nullptr);
2579     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2580     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2581            "Typo correction callback misconfigured");
2582     if (CCC) {
2583       // Make sure the callback knows what the typo being diagnosed is.
2584       CCC->setTypoName(II);
2585       if (SS.isValid())
2586         CCC->setTypoNNS(SS.getScopeRep());
2587     }
2588     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2589     // a template name, but we happen to have always already looked up the name
2590     // before we get here if it must be a template name.
2591     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2592                             None, &TE)) {
2593       if (TE && KeywordReplacement) {
2594         auto &State = getTypoExprState(TE);
2595         auto BestTC = State.Consumer->getNextCorrection();
2596         if (BestTC.isKeyword()) {
2597           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2598           if (State.DiagHandler)
2599             State.DiagHandler(BestTC);
2600           KeywordReplacement->startToken();
2601           KeywordReplacement->setKind(II->getTokenID());
2602           KeywordReplacement->setIdentifierInfo(II);
2603           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2604           // Clean up the state associated with the TypoExpr, since it has
2605           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2606           clearDelayedTypo(TE);
2607           // Signal that a correction to a keyword was performed by returning a
2608           // valid-but-null ExprResult.
2609           return (Expr*)nullptr;
2610         }
2611         State.Consumer->resetCorrectionStream();
2612       }
2613       return TE ? TE : ExprError();
2614     }
2615 
2616     assert(!R.empty() &&
2617            "DiagnoseEmptyLookup returned false but added no results");
2618 
2619     // If we found an Objective-C instance variable, let
2620     // LookupInObjCMethod build the appropriate expression to
2621     // reference the ivar.
2622     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2623       R.clear();
2624       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2625       // In a hopelessly buggy code, Objective-C instance variable
2626       // lookup fails and no expression will be built to reference it.
2627       if (!E.isInvalid() && !E.get())
2628         return ExprError();
2629       return E;
2630     }
2631   }
2632 
2633   // This is guaranteed from this point on.
2634   assert(!R.empty() || ADL);
2635 
2636   // Check whether this might be a C++ implicit instance member access.
2637   // C++ [class.mfct.non-static]p3:
2638   //   When an id-expression that is not part of a class member access
2639   //   syntax and not used to form a pointer to member is used in the
2640   //   body of a non-static member function of class X, if name lookup
2641   //   resolves the name in the id-expression to a non-static non-type
2642   //   member of some class C, the id-expression is transformed into a
2643   //   class member access expression using (*this) as the
2644   //   postfix-expression to the left of the . operator.
2645   //
2646   // But we don't actually need to do this for '&' operands if R
2647   // resolved to a function or overloaded function set, because the
2648   // expression is ill-formed if it actually works out to be a
2649   // non-static member function:
2650   //
2651   // C++ [expr.ref]p4:
2652   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2653   //   [t]he expression can be used only as the left-hand operand of a
2654   //   member function call.
2655   //
2656   // There are other safeguards against such uses, but it's important
2657   // to get this right here so that we don't end up making a
2658   // spuriously dependent expression if we're inside a dependent
2659   // instance method.
2660   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2661     bool MightBeImplicitMember;
2662     if (!IsAddressOfOperand)
2663       MightBeImplicitMember = true;
2664     else if (!SS.isEmpty())
2665       MightBeImplicitMember = false;
2666     else if (R.isOverloadedResult())
2667       MightBeImplicitMember = false;
2668     else if (R.isUnresolvableResult())
2669       MightBeImplicitMember = true;
2670     else
2671       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2672                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2673                               isa<MSPropertyDecl>(R.getFoundDecl());
2674 
2675     if (MightBeImplicitMember)
2676       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2677                                              R, TemplateArgs, S);
2678   }
2679 
2680   if (TemplateArgs || TemplateKWLoc.isValid()) {
2681 
2682     // In C++1y, if this is a variable template id, then check it
2683     // in BuildTemplateIdExpr().
2684     // The single lookup result must be a variable template declaration.
2685     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2686         Id.TemplateId->Kind == TNK_Var_template) {
2687       assert(R.getAsSingle<VarTemplateDecl>() &&
2688              "There should only be one declaration found.");
2689     }
2690 
2691     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2692   }
2693 
2694   return BuildDeclarationNameExpr(SS, R, ADL);
2695 }
2696 
2697 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2698 /// declaration name, generally during template instantiation.
2699 /// There's a large number of things which don't need to be done along
2700 /// this path.
2701 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2702     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2703     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2704   DeclContext *DC = computeDeclContext(SS, false);
2705   if (!DC)
2706     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2707                                      NameInfo, /*TemplateArgs=*/nullptr);
2708 
2709   if (RequireCompleteDeclContext(SS, DC))
2710     return ExprError();
2711 
2712   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2713   LookupQualifiedName(R, DC);
2714 
2715   if (R.isAmbiguous())
2716     return ExprError();
2717 
2718   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2719     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2720                                      NameInfo, /*TemplateArgs=*/nullptr);
2721 
2722   if (R.empty()) {
2723     // Don't diagnose problems with invalid record decl, the secondary no_member
2724     // diagnostic during template instantiation is likely bogus, e.g. if a class
2725     // is invalid because it's derived from an invalid base class, then missing
2726     // members were likely supposed to be inherited.
2727     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2728       if (CD->isInvalidDecl())
2729         return ExprError();
2730     Diag(NameInfo.getLoc(), diag::err_no_member)
2731       << NameInfo.getName() << DC << SS.getRange();
2732     return ExprError();
2733   }
2734 
2735   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2736     // Diagnose a missing typename if this resolved unambiguously to a type in
2737     // a dependent context.  If we can recover with a type, downgrade this to
2738     // a warning in Microsoft compatibility mode.
2739     unsigned DiagID = diag::err_typename_missing;
2740     if (RecoveryTSI && getLangOpts().MSVCCompat)
2741       DiagID = diag::ext_typename_missing;
2742     SourceLocation Loc = SS.getBeginLoc();
2743     auto D = Diag(Loc, DiagID);
2744     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2745       << SourceRange(Loc, NameInfo.getEndLoc());
2746 
2747     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2748     // context.
2749     if (!RecoveryTSI)
2750       return ExprError();
2751 
2752     // Only issue the fixit if we're prepared to recover.
2753     D << FixItHint::CreateInsertion(Loc, "typename ");
2754 
2755     // Recover by pretending this was an elaborated type.
2756     QualType Ty = Context.getTypeDeclType(TD);
2757     TypeLocBuilder TLB;
2758     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2759 
2760     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2761     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2762     QTL.setElaboratedKeywordLoc(SourceLocation());
2763     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2764 
2765     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2766 
2767     return ExprEmpty();
2768   }
2769 
2770   // Defend against this resolving to an implicit member access. We usually
2771   // won't get here if this might be a legitimate a class member (we end up in
2772   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2773   // a pointer-to-member or in an unevaluated context in C++11.
2774   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2775     return BuildPossibleImplicitMemberExpr(SS,
2776                                            /*TemplateKWLoc=*/SourceLocation(),
2777                                            R, /*TemplateArgs=*/nullptr, S);
2778 
2779   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2780 }
2781 
2782 /// The parser has read a name in, and Sema has detected that we're currently
2783 /// inside an ObjC method. Perform some additional checks and determine if we
2784 /// should form a reference to an ivar.
2785 ///
2786 /// Ideally, most of this would be done by lookup, but there's
2787 /// actually quite a lot of extra work involved.
2788 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2789                                         IdentifierInfo *II) {
2790   SourceLocation Loc = Lookup.getNameLoc();
2791   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2792 
2793   // Check for error condition which is already reported.
2794   if (!CurMethod)
2795     return DeclResult(true);
2796 
2797   // There are two cases to handle here.  1) scoped lookup could have failed,
2798   // in which case we should look for an ivar.  2) scoped lookup could have
2799   // found a decl, but that decl is outside the current instance method (i.e.
2800   // a global variable).  In these two cases, we do a lookup for an ivar with
2801   // this name, if the lookup sucedes, we replace it our current decl.
2802 
2803   // If we're in a class method, we don't normally want to look for
2804   // ivars.  But if we don't find anything else, and there's an
2805   // ivar, that's an error.
2806   bool IsClassMethod = CurMethod->isClassMethod();
2807 
2808   bool LookForIvars;
2809   if (Lookup.empty())
2810     LookForIvars = true;
2811   else if (IsClassMethod)
2812     LookForIvars = false;
2813   else
2814     LookForIvars = (Lookup.isSingleResult() &&
2815                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2816   ObjCInterfaceDecl *IFace = nullptr;
2817   if (LookForIvars) {
2818     IFace = CurMethod->getClassInterface();
2819     ObjCInterfaceDecl *ClassDeclared;
2820     ObjCIvarDecl *IV = nullptr;
2821     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2822       // Diagnose using an ivar in a class method.
2823       if (IsClassMethod) {
2824         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2825         return DeclResult(true);
2826       }
2827 
2828       // Diagnose the use of an ivar outside of the declaring class.
2829       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2830           !declaresSameEntity(ClassDeclared, IFace) &&
2831           !getLangOpts().DebuggerSupport)
2832         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2833 
2834       // Success.
2835       return IV;
2836     }
2837   } else if (CurMethod->isInstanceMethod()) {
2838     // We should warn if a local variable hides an ivar.
2839     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2840       ObjCInterfaceDecl *ClassDeclared;
2841       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2842         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2843             declaresSameEntity(IFace, ClassDeclared))
2844           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2845       }
2846     }
2847   } else if (Lookup.isSingleResult() &&
2848              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2849     // If accessing a stand-alone ivar in a class method, this is an error.
2850     if (const ObjCIvarDecl *IV =
2851             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2852       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2853       return DeclResult(true);
2854     }
2855   }
2856 
2857   // Didn't encounter an error, didn't find an ivar.
2858   return DeclResult(false);
2859 }
2860 
2861 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2862                                   ObjCIvarDecl *IV) {
2863   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2864   assert(CurMethod && CurMethod->isInstanceMethod() &&
2865          "should not reference ivar from this context");
2866 
2867   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2868   assert(IFace && "should not reference ivar from this context");
2869 
2870   // If we're referencing an invalid decl, just return this as a silent
2871   // error node.  The error diagnostic was already emitted on the decl.
2872   if (IV->isInvalidDecl())
2873     return ExprError();
2874 
2875   // Check if referencing a field with __attribute__((deprecated)).
2876   if (DiagnoseUseOfDecl(IV, Loc))
2877     return ExprError();
2878 
2879   // FIXME: This should use a new expr for a direct reference, don't
2880   // turn this into Self->ivar, just return a BareIVarExpr or something.
2881   IdentifierInfo &II = Context.Idents.get("self");
2882   UnqualifiedId SelfName;
2883   SelfName.setImplicitSelfParam(&II);
2884   CXXScopeSpec SelfScopeSpec;
2885   SourceLocation TemplateKWLoc;
2886   ExprResult SelfExpr =
2887       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2888                         /*HasTrailingLParen=*/false,
2889                         /*IsAddressOfOperand=*/false);
2890   if (SelfExpr.isInvalid())
2891     return ExprError();
2892 
2893   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2894   if (SelfExpr.isInvalid())
2895     return ExprError();
2896 
2897   MarkAnyDeclReferenced(Loc, IV, true);
2898 
2899   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2900   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2901       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2902     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2903 
2904   ObjCIvarRefExpr *Result = new (Context)
2905       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2906                       IV->getLocation(), SelfExpr.get(), true, true);
2907 
2908   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2909     if (!isUnevaluatedContext() &&
2910         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2911       getCurFunction()->recordUseOfWeak(Result);
2912   }
2913   if (getLangOpts().ObjCAutoRefCount)
2914     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2915       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2916 
2917   return Result;
2918 }
2919 
2920 /// The parser has read a name in, and Sema has detected that we're currently
2921 /// inside an ObjC method. Perform some additional checks and determine if we
2922 /// should form a reference to an ivar. If so, build an expression referencing
2923 /// that ivar.
2924 ExprResult
2925 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2926                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2927   // FIXME: Integrate this lookup step into LookupParsedName.
2928   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2929   if (Ivar.isInvalid())
2930     return ExprError();
2931   if (Ivar.isUsable())
2932     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2933                             cast<ObjCIvarDecl>(Ivar.get()));
2934 
2935   if (Lookup.empty() && II && AllowBuiltinCreation)
2936     LookupBuiltin(Lookup);
2937 
2938   // Sentinel value saying that we didn't do anything special.
2939   return ExprResult(false);
2940 }
2941 
2942 /// Cast a base object to a member's actual type.
2943 ///
2944 /// There are two relevant checks:
2945 ///
2946 /// C++ [class.access.base]p7:
2947 ///
2948 ///   If a class member access operator [...] is used to access a non-static
2949 ///   data member or non-static member function, the reference is ill-formed if
2950 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2951 ///   naming class of the right operand.
2952 ///
2953 /// C++ [expr.ref]p7:
2954 ///
2955 ///   If E2 is a non-static data member or a non-static member function, the
2956 ///   program is ill-formed if the class of which E2 is directly a member is an
2957 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2958 ///
2959 /// Note that the latter check does not consider access; the access of the
2960 /// "real" base class is checked as appropriate when checking the access of the
2961 /// member name.
2962 ExprResult
2963 Sema::PerformObjectMemberConversion(Expr *From,
2964                                     NestedNameSpecifier *Qualifier,
2965                                     NamedDecl *FoundDecl,
2966                                     NamedDecl *Member) {
2967   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2968   if (!RD)
2969     return From;
2970 
2971   QualType DestRecordType;
2972   QualType DestType;
2973   QualType FromRecordType;
2974   QualType FromType = From->getType();
2975   bool PointerConversions = false;
2976   if (isa<FieldDecl>(Member)) {
2977     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2978     auto FromPtrType = FromType->getAs<PointerType>();
2979     DestRecordType = Context.getAddrSpaceQualType(
2980         DestRecordType, FromPtrType
2981                             ? FromType->getPointeeType().getAddressSpace()
2982                             : FromType.getAddressSpace());
2983 
2984     if (FromPtrType) {
2985       DestType = Context.getPointerType(DestRecordType);
2986       FromRecordType = FromPtrType->getPointeeType();
2987       PointerConversions = true;
2988     } else {
2989       DestType = DestRecordType;
2990       FromRecordType = FromType;
2991     }
2992   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2993     if (Method->isStatic())
2994       return From;
2995 
2996     DestType = Method->getThisType();
2997     DestRecordType = DestType->getPointeeType();
2998 
2999     if (FromType->getAs<PointerType>()) {
3000       FromRecordType = FromType->getPointeeType();
3001       PointerConversions = true;
3002     } else {
3003       FromRecordType = FromType;
3004       DestType = DestRecordType;
3005     }
3006 
3007     LangAS FromAS = FromRecordType.getAddressSpace();
3008     LangAS DestAS = DestRecordType.getAddressSpace();
3009     if (FromAS != DestAS) {
3010       QualType FromRecordTypeWithoutAS =
3011           Context.removeAddrSpaceQualType(FromRecordType);
3012       QualType FromTypeWithDestAS =
3013           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3014       if (PointerConversions)
3015         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3016       From = ImpCastExprToType(From, FromTypeWithDestAS,
3017                                CK_AddressSpaceConversion, From->getValueKind())
3018                  .get();
3019     }
3020   } else {
3021     // No conversion necessary.
3022     return From;
3023   }
3024 
3025   if (DestType->isDependentType() || FromType->isDependentType())
3026     return From;
3027 
3028   // If the unqualified types are the same, no conversion is necessary.
3029   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3030     return From;
3031 
3032   SourceRange FromRange = From->getSourceRange();
3033   SourceLocation FromLoc = FromRange.getBegin();
3034 
3035   ExprValueKind VK = From->getValueKind();
3036 
3037   // C++ [class.member.lookup]p8:
3038   //   [...] Ambiguities can often be resolved by qualifying a name with its
3039   //   class name.
3040   //
3041   // If the member was a qualified name and the qualified referred to a
3042   // specific base subobject type, we'll cast to that intermediate type
3043   // first and then to the object in which the member is declared. That allows
3044   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3045   //
3046   //   class Base { public: int x; };
3047   //   class Derived1 : public Base { };
3048   //   class Derived2 : public Base { };
3049   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3050   //
3051   //   void VeryDerived::f() {
3052   //     x = 17; // error: ambiguous base subobjects
3053   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3054   //   }
3055   if (Qualifier && Qualifier->getAsType()) {
3056     QualType QType = QualType(Qualifier->getAsType(), 0);
3057     assert(QType->isRecordType() && "lookup done with non-record type");
3058 
3059     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3060 
3061     // In C++98, the qualifier type doesn't actually have to be a base
3062     // type of the object type, in which case we just ignore it.
3063     // Otherwise build the appropriate casts.
3064     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3065       CXXCastPath BasePath;
3066       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3067                                        FromLoc, FromRange, &BasePath))
3068         return ExprError();
3069 
3070       if (PointerConversions)
3071         QType = Context.getPointerType(QType);
3072       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3073                                VK, &BasePath).get();
3074 
3075       FromType = QType;
3076       FromRecordType = QRecordType;
3077 
3078       // If the qualifier type was the same as the destination type,
3079       // we're done.
3080       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3081         return From;
3082     }
3083   }
3084 
3085   CXXCastPath BasePath;
3086   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3087                                    FromLoc, FromRange, &BasePath,
3088                                    /*IgnoreAccess=*/true))
3089     return ExprError();
3090 
3091   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3092                            VK, &BasePath);
3093 }
3094 
3095 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3096                                       const LookupResult &R,
3097                                       bool HasTrailingLParen) {
3098   // Only when used directly as the postfix-expression of a call.
3099   if (!HasTrailingLParen)
3100     return false;
3101 
3102   // Never if a scope specifier was provided.
3103   if (SS.isSet())
3104     return false;
3105 
3106   // Only in C++ or ObjC++.
3107   if (!getLangOpts().CPlusPlus)
3108     return false;
3109 
3110   // Turn off ADL when we find certain kinds of declarations during
3111   // normal lookup:
3112   for (NamedDecl *D : R) {
3113     // C++0x [basic.lookup.argdep]p3:
3114     //     -- a declaration of a class member
3115     // Since using decls preserve this property, we check this on the
3116     // original decl.
3117     if (D->isCXXClassMember())
3118       return false;
3119 
3120     // C++0x [basic.lookup.argdep]p3:
3121     //     -- a block-scope function declaration that is not a
3122     //        using-declaration
3123     // NOTE: we also trigger this for function templates (in fact, we
3124     // don't check the decl type at all, since all other decl types
3125     // turn off ADL anyway).
3126     if (isa<UsingShadowDecl>(D))
3127       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3128     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3129       return false;
3130 
3131     // C++0x [basic.lookup.argdep]p3:
3132     //     -- a declaration that is neither a function or a function
3133     //        template
3134     // And also for builtin functions.
3135     if (isa<FunctionDecl>(D)) {
3136       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3137 
3138       // But also builtin functions.
3139       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3140         return false;
3141     } else if (!isa<FunctionTemplateDecl>(D))
3142       return false;
3143   }
3144 
3145   return true;
3146 }
3147 
3148 
3149 /// Diagnoses obvious problems with the use of the given declaration
3150 /// as an expression.  This is only actually called for lookups that
3151 /// were not overloaded, and it doesn't promise that the declaration
3152 /// will in fact be used.
3153 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3154   if (D->isInvalidDecl())
3155     return true;
3156 
3157   if (isa<TypedefNameDecl>(D)) {
3158     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3159     return true;
3160   }
3161 
3162   if (isa<ObjCInterfaceDecl>(D)) {
3163     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3164     return true;
3165   }
3166 
3167   if (isa<NamespaceDecl>(D)) {
3168     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3169     return true;
3170   }
3171 
3172   return false;
3173 }
3174 
3175 // Certain multiversion types should be treated as overloaded even when there is
3176 // only one result.
3177 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3178   assert(R.isSingleResult() && "Expected only a single result");
3179   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3180   return FD &&
3181          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3182 }
3183 
3184 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3185                                           LookupResult &R, bool NeedsADL,
3186                                           bool AcceptInvalidDecl) {
3187   // If this is a single, fully-resolved result and we don't need ADL,
3188   // just build an ordinary singleton decl ref.
3189   if (!NeedsADL && R.isSingleResult() &&
3190       !R.getAsSingle<FunctionTemplateDecl>() &&
3191       !ShouldLookupResultBeMultiVersionOverload(R))
3192     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3193                                     R.getRepresentativeDecl(), nullptr,
3194                                     AcceptInvalidDecl);
3195 
3196   // We only need to check the declaration if there's exactly one
3197   // result, because in the overloaded case the results can only be
3198   // functions and function templates.
3199   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3200       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3201     return ExprError();
3202 
3203   // Otherwise, just build an unresolved lookup expression.  Suppress
3204   // any lookup-related diagnostics; we'll hash these out later, when
3205   // we've picked a target.
3206   R.suppressDiagnostics();
3207 
3208   UnresolvedLookupExpr *ULE
3209     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3210                                    SS.getWithLocInContext(Context),
3211                                    R.getLookupNameInfo(),
3212                                    NeedsADL, R.isOverloadedResult(),
3213                                    R.begin(), R.end());
3214 
3215   return ULE;
3216 }
3217 
3218 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3219                                                ValueDecl *var);
3220 
3221 /// Complete semantic analysis for a reference to the given declaration.
3222 ExprResult Sema::BuildDeclarationNameExpr(
3223     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3224     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3225     bool AcceptInvalidDecl) {
3226   assert(D && "Cannot refer to a NULL declaration");
3227   assert(!isa<FunctionTemplateDecl>(D) &&
3228          "Cannot refer unambiguously to a function template");
3229 
3230   SourceLocation Loc = NameInfo.getLoc();
3231   if (CheckDeclInExpr(*this, Loc, D)) {
3232     // Recovery from invalid cases (e.g. D is an invalid Decl).
3233     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3234     // diagnostics, as invalid decls use int as a fallback type.
3235     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3236   }
3237 
3238   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3239     // Specifically diagnose references to class templates that are missing
3240     // a template argument list.
3241     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3242     return ExprError();
3243   }
3244 
3245   // Make sure that we're referring to a value.
3246   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3247     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3248     Diag(D->getLocation(), diag::note_declared_at);
3249     return ExprError();
3250   }
3251 
3252   // Check whether this declaration can be used. Note that we suppress
3253   // this check when we're going to perform argument-dependent lookup
3254   // on this function name, because this might not be the function
3255   // that overload resolution actually selects.
3256   if (DiagnoseUseOfDecl(D, Loc))
3257     return ExprError();
3258 
3259   auto *VD = cast<ValueDecl>(D);
3260 
3261   // Only create DeclRefExpr's for valid Decl's.
3262   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3263     return ExprError();
3264 
3265   // Handle members of anonymous structs and unions.  If we got here,
3266   // and the reference is to a class member indirect field, then this
3267   // must be the subject of a pointer-to-member expression.
3268   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3269     if (!indirectField->isCXXClassMember())
3270       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3271                                                       indirectField);
3272 
3273   QualType type = VD->getType();
3274   if (type.isNull())
3275     return ExprError();
3276   ExprValueKind valueKind = VK_PRValue;
3277 
3278   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3279   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3280   // is expanded by some outer '...' in the context of the use.
3281   type = type.getNonPackExpansionType();
3282 
3283   switch (D->getKind()) {
3284     // Ignore all the non-ValueDecl kinds.
3285 #define ABSTRACT_DECL(kind)
3286 #define VALUE(type, base)
3287 #define DECL(type, base) case Decl::type:
3288 #include "clang/AST/DeclNodes.inc"
3289     llvm_unreachable("invalid value decl kind");
3290 
3291   // These shouldn't make it here.
3292   case Decl::ObjCAtDefsField:
3293     llvm_unreachable("forming non-member reference to ivar?");
3294 
3295   // Enum constants are always r-values and never references.
3296   // Unresolved using declarations are dependent.
3297   case Decl::EnumConstant:
3298   case Decl::UnresolvedUsingValue:
3299   case Decl::OMPDeclareReduction:
3300   case Decl::OMPDeclareMapper:
3301     valueKind = VK_PRValue;
3302     break;
3303 
3304   // Fields and indirect fields that got here must be for
3305   // pointer-to-member expressions; we just call them l-values for
3306   // internal consistency, because this subexpression doesn't really
3307   // exist in the high-level semantics.
3308   case Decl::Field:
3309   case Decl::IndirectField:
3310   case Decl::ObjCIvar:
3311     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3312 
3313     // These can't have reference type in well-formed programs, but
3314     // for internal consistency we do this anyway.
3315     type = type.getNonReferenceType();
3316     valueKind = VK_LValue;
3317     break;
3318 
3319   // Non-type template parameters are either l-values or r-values
3320   // depending on the type.
3321   case Decl::NonTypeTemplateParm: {
3322     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3323       type = reftype->getPointeeType();
3324       valueKind = VK_LValue; // even if the parameter is an r-value reference
3325       break;
3326     }
3327 
3328     // [expr.prim.id.unqual]p2:
3329     //   If the entity is a template parameter object for a template
3330     //   parameter of type T, the type of the expression is const T.
3331     //   [...] The expression is an lvalue if the entity is a [...] template
3332     //   parameter object.
3333     if (type->isRecordType()) {
3334       type = type.getUnqualifiedType().withConst();
3335       valueKind = VK_LValue;
3336       break;
3337     }
3338 
3339     // For non-references, we need to strip qualifiers just in case
3340     // the template parameter was declared as 'const int' or whatever.
3341     valueKind = VK_PRValue;
3342     type = type.getUnqualifiedType();
3343     break;
3344   }
3345 
3346   case Decl::Var:
3347   case Decl::VarTemplateSpecialization:
3348   case Decl::VarTemplatePartialSpecialization:
3349   case Decl::Decomposition:
3350   case Decl::OMPCapturedExpr:
3351     // In C, "extern void blah;" is valid and is an r-value.
3352     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3353         type->isVoidType()) {
3354       valueKind = VK_PRValue;
3355       break;
3356     }
3357     LLVM_FALLTHROUGH;
3358 
3359   case Decl::ImplicitParam:
3360   case Decl::ParmVar: {
3361     // These are always l-values.
3362     valueKind = VK_LValue;
3363     type = type.getNonReferenceType();
3364 
3365     // FIXME: Does the addition of const really only apply in
3366     // potentially-evaluated contexts? Since the variable isn't actually
3367     // captured in an unevaluated context, it seems that the answer is no.
3368     if (!isUnevaluatedContext()) {
3369       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3370       if (!CapturedType.isNull())
3371         type = CapturedType;
3372     }
3373 
3374     break;
3375   }
3376 
3377   case Decl::Binding: {
3378     // These are always lvalues.
3379     valueKind = VK_LValue;
3380     type = type.getNonReferenceType();
3381     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3382     // decides how that's supposed to work.
3383     auto *BD = cast<BindingDecl>(VD);
3384     if (BD->getDeclContext() != CurContext) {
3385       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3386       if (DD && DD->hasLocalStorage())
3387         diagnoseUncapturableValueReference(*this, Loc, BD);
3388     }
3389     break;
3390   }
3391 
3392   case Decl::Function: {
3393     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3394       if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3395         type = Context.BuiltinFnTy;
3396         valueKind = VK_PRValue;
3397         break;
3398       }
3399     }
3400 
3401     const FunctionType *fty = type->castAs<FunctionType>();
3402 
3403     // If we're referring to a function with an __unknown_anytype
3404     // result type, make the entire expression __unknown_anytype.
3405     if (fty->getReturnType() == Context.UnknownAnyTy) {
3406       type = Context.UnknownAnyTy;
3407       valueKind = VK_PRValue;
3408       break;
3409     }
3410 
3411     // Functions are l-values in C++.
3412     if (getLangOpts().CPlusPlus) {
3413       valueKind = VK_LValue;
3414       break;
3415     }
3416 
3417     // C99 DR 316 says that, if a function type comes from a
3418     // function definition (without a prototype), that type is only
3419     // used for checking compatibility. Therefore, when referencing
3420     // the function, we pretend that we don't have the full function
3421     // type.
3422     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3423       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3424                                             fty->getExtInfo());
3425 
3426     // Functions are r-values in C.
3427     valueKind = VK_PRValue;
3428     break;
3429   }
3430 
3431   case Decl::CXXDeductionGuide:
3432     llvm_unreachable("building reference to deduction guide");
3433 
3434   case Decl::MSProperty:
3435   case Decl::MSGuid:
3436   case Decl::TemplateParamObject:
3437     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3438     // capture in OpenMP, or duplicated between host and device?
3439     valueKind = VK_LValue;
3440     break;
3441 
3442   case Decl::CXXMethod:
3443     // If we're referring to a method with an __unknown_anytype
3444     // result type, make the entire expression __unknown_anytype.
3445     // This should only be possible with a type written directly.
3446     if (const FunctionProtoType *proto =
3447             dyn_cast<FunctionProtoType>(VD->getType()))
3448       if (proto->getReturnType() == Context.UnknownAnyTy) {
3449         type = Context.UnknownAnyTy;
3450         valueKind = VK_PRValue;
3451         break;
3452       }
3453 
3454     // C++ methods are l-values if static, r-values if non-static.
3455     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3456       valueKind = VK_LValue;
3457       break;
3458     }
3459     LLVM_FALLTHROUGH;
3460 
3461   case Decl::CXXConversion:
3462   case Decl::CXXDestructor:
3463   case Decl::CXXConstructor:
3464     valueKind = VK_PRValue;
3465     break;
3466   }
3467 
3468   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3469                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3470                           TemplateArgs);
3471 }
3472 
3473 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3474                                     SmallString<32> &Target) {
3475   Target.resize(CharByteWidth * (Source.size() + 1));
3476   char *ResultPtr = &Target[0];
3477   const llvm::UTF8 *ErrorPtr;
3478   bool success =
3479       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3480   (void)success;
3481   assert(success);
3482   Target.resize(ResultPtr - &Target[0]);
3483 }
3484 
3485 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3486                                      PredefinedExpr::IdentKind IK) {
3487   // Pick the current block, lambda, captured statement or function.
3488   Decl *currentDecl = nullptr;
3489   if (const BlockScopeInfo *BSI = getCurBlock())
3490     currentDecl = BSI->TheDecl;
3491   else if (const LambdaScopeInfo *LSI = getCurLambda())
3492     currentDecl = LSI->CallOperator;
3493   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3494     currentDecl = CSI->TheCapturedDecl;
3495   else
3496     currentDecl = getCurFunctionOrMethodDecl();
3497 
3498   if (!currentDecl) {
3499     Diag(Loc, diag::ext_predef_outside_function);
3500     currentDecl = Context.getTranslationUnitDecl();
3501   }
3502 
3503   QualType ResTy;
3504   StringLiteral *SL = nullptr;
3505   if (cast<DeclContext>(currentDecl)->isDependentContext())
3506     ResTy = Context.DependentTy;
3507   else {
3508     // Pre-defined identifiers are of type char[x], where x is the length of
3509     // the string.
3510     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3511     unsigned Length = Str.length();
3512 
3513     llvm::APInt LengthI(32, Length + 1);
3514     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3515       ResTy =
3516           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3517       SmallString<32> RawChars;
3518       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3519                               Str, RawChars);
3520       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3521                                            ArrayType::Normal,
3522                                            /*IndexTypeQuals*/ 0);
3523       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3524                                  /*Pascal*/ false, ResTy, Loc);
3525     } else {
3526       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3527       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3528                                            ArrayType::Normal,
3529                                            /*IndexTypeQuals*/ 0);
3530       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3531                                  /*Pascal*/ false, ResTy, Loc);
3532     }
3533   }
3534 
3535   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3536 }
3537 
3538 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3539                                                SourceLocation LParen,
3540                                                SourceLocation RParen,
3541                                                TypeSourceInfo *TSI) {
3542   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3543 }
3544 
3545 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3546                                                SourceLocation LParen,
3547                                                SourceLocation RParen,
3548                                                ParsedType ParsedTy) {
3549   TypeSourceInfo *TSI = nullptr;
3550   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3551 
3552   if (Ty.isNull())
3553     return ExprError();
3554   if (!TSI)
3555     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3556 
3557   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3558 }
3559 
3560 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3561   PredefinedExpr::IdentKind IK;
3562 
3563   switch (Kind) {
3564   default: llvm_unreachable("Unknown simple primary expr!");
3565   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3566   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3567   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3568   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3569   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3570   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3571   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3572   }
3573 
3574   return BuildPredefinedExpr(Loc, IK);
3575 }
3576 
3577 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3578   SmallString<16> CharBuffer;
3579   bool Invalid = false;
3580   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3581   if (Invalid)
3582     return ExprError();
3583 
3584   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3585                             PP, Tok.getKind());
3586   if (Literal.hadError())
3587     return ExprError();
3588 
3589   QualType Ty;
3590   if (Literal.isWide())
3591     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3592   else if (Literal.isUTF8() && getLangOpts().Char8)
3593     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3594   else if (Literal.isUTF16())
3595     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3596   else if (Literal.isUTF32())
3597     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3598   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3599     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3600   else
3601     Ty = Context.CharTy;  // 'x' -> char in C++
3602 
3603   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3604   if (Literal.isWide())
3605     Kind = CharacterLiteral::Wide;
3606   else if (Literal.isUTF16())
3607     Kind = CharacterLiteral::UTF16;
3608   else if (Literal.isUTF32())
3609     Kind = CharacterLiteral::UTF32;
3610   else if (Literal.isUTF8())
3611     Kind = CharacterLiteral::UTF8;
3612 
3613   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3614                                              Tok.getLocation());
3615 
3616   if (Literal.getUDSuffix().empty())
3617     return Lit;
3618 
3619   // We're building a user-defined literal.
3620   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3621   SourceLocation UDSuffixLoc =
3622     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3623 
3624   // Make sure we're allowed user-defined literals here.
3625   if (!UDLScope)
3626     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3627 
3628   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3629   //   operator "" X (ch)
3630   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3631                                         Lit, Tok.getLocation());
3632 }
3633 
3634 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3635   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3636   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3637                                 Context.IntTy, Loc);
3638 }
3639 
3640 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3641                                   QualType Ty, SourceLocation Loc) {
3642   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3643 
3644   using llvm::APFloat;
3645   APFloat Val(Format);
3646 
3647   APFloat::opStatus result = Literal.GetFloatValue(Val);
3648 
3649   // Overflow is always an error, but underflow is only an error if
3650   // we underflowed to zero (APFloat reports denormals as underflow).
3651   if ((result & APFloat::opOverflow) ||
3652       ((result & APFloat::opUnderflow) && Val.isZero())) {
3653     unsigned diagnostic;
3654     SmallString<20> buffer;
3655     if (result & APFloat::opOverflow) {
3656       diagnostic = diag::warn_float_overflow;
3657       APFloat::getLargest(Format).toString(buffer);
3658     } else {
3659       diagnostic = diag::warn_float_underflow;
3660       APFloat::getSmallest(Format).toString(buffer);
3661     }
3662 
3663     S.Diag(Loc, diagnostic)
3664       << Ty
3665       << StringRef(buffer.data(), buffer.size());
3666   }
3667 
3668   bool isExact = (result == APFloat::opOK);
3669   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3670 }
3671 
3672 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3673   assert(E && "Invalid expression");
3674 
3675   if (E->isValueDependent())
3676     return false;
3677 
3678   QualType QT = E->getType();
3679   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3680     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3681     return true;
3682   }
3683 
3684   llvm::APSInt ValueAPS;
3685   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3686 
3687   if (R.isInvalid())
3688     return true;
3689 
3690   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3691   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3692     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3693         << toString(ValueAPS, 10) << ValueIsPositive;
3694     return true;
3695   }
3696 
3697   return false;
3698 }
3699 
3700 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3701   // Fast path for a single digit (which is quite common).  A single digit
3702   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3703   if (Tok.getLength() == 1) {
3704     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3705     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3706   }
3707 
3708   SmallString<128> SpellingBuffer;
3709   // NumericLiteralParser wants to overread by one character.  Add padding to
3710   // the buffer in case the token is copied to the buffer.  If getSpelling()
3711   // returns a StringRef to the memory buffer, it should have a null char at
3712   // the EOF, so it is also safe.
3713   SpellingBuffer.resize(Tok.getLength() + 1);
3714 
3715   // Get the spelling of the token, which eliminates trigraphs, etc.
3716   bool Invalid = false;
3717   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3718   if (Invalid)
3719     return ExprError();
3720 
3721   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3722                                PP.getSourceManager(), PP.getLangOpts(),
3723                                PP.getTargetInfo(), PP.getDiagnostics());
3724   if (Literal.hadError)
3725     return ExprError();
3726 
3727   if (Literal.hasUDSuffix()) {
3728     // We're building a user-defined literal.
3729     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3730     SourceLocation UDSuffixLoc =
3731       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3732 
3733     // Make sure we're allowed user-defined literals here.
3734     if (!UDLScope)
3735       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3736 
3737     QualType CookedTy;
3738     if (Literal.isFloatingLiteral()) {
3739       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3740       // long double, the literal is treated as a call of the form
3741       //   operator "" X (f L)
3742       CookedTy = Context.LongDoubleTy;
3743     } else {
3744       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3745       // unsigned long long, the literal is treated as a call of the form
3746       //   operator "" X (n ULL)
3747       CookedTy = Context.UnsignedLongLongTy;
3748     }
3749 
3750     DeclarationName OpName =
3751       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3752     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3753     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3754 
3755     SourceLocation TokLoc = Tok.getLocation();
3756 
3757     // Perform literal operator lookup to determine if we're building a raw
3758     // literal or a cooked one.
3759     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3760     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3761                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3762                                   /*AllowStringTemplatePack*/ false,
3763                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3764     case LOLR_ErrorNoDiagnostic:
3765       // Lookup failure for imaginary constants isn't fatal, there's still the
3766       // GNU extension producing _Complex types.
3767       break;
3768     case LOLR_Error:
3769       return ExprError();
3770     case LOLR_Cooked: {
3771       Expr *Lit;
3772       if (Literal.isFloatingLiteral()) {
3773         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3774       } else {
3775         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3776         if (Literal.GetIntegerValue(ResultVal))
3777           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3778               << /* Unsigned */ 1;
3779         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3780                                      Tok.getLocation());
3781       }
3782       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3783     }
3784 
3785     case LOLR_Raw: {
3786       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3787       // literal is treated as a call of the form
3788       //   operator "" X ("n")
3789       unsigned Length = Literal.getUDSuffixOffset();
3790       QualType StrTy = Context.getConstantArrayType(
3791           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3792           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3793       Expr *Lit = StringLiteral::Create(
3794           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3795           /*Pascal*/false, StrTy, &TokLoc, 1);
3796       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3797     }
3798 
3799     case LOLR_Template: {
3800       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3801       // template), L is treated as a call fo the form
3802       //   operator "" X <'c1', 'c2', ... 'ck'>()
3803       // where n is the source character sequence c1 c2 ... ck.
3804       TemplateArgumentListInfo ExplicitArgs;
3805       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3806       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3807       llvm::APSInt Value(CharBits, CharIsUnsigned);
3808       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3809         Value = TokSpelling[I];
3810         TemplateArgument Arg(Context, Value, Context.CharTy);
3811         TemplateArgumentLocInfo ArgInfo;
3812         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3813       }
3814       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3815                                       &ExplicitArgs);
3816     }
3817     case LOLR_StringTemplatePack:
3818       llvm_unreachable("unexpected literal operator lookup result");
3819     }
3820   }
3821 
3822   Expr *Res;
3823 
3824   if (Literal.isFixedPointLiteral()) {
3825     QualType Ty;
3826 
3827     if (Literal.isAccum) {
3828       if (Literal.isHalf) {
3829         Ty = Context.ShortAccumTy;
3830       } else if (Literal.isLong) {
3831         Ty = Context.LongAccumTy;
3832       } else {
3833         Ty = Context.AccumTy;
3834       }
3835     } else if (Literal.isFract) {
3836       if (Literal.isHalf) {
3837         Ty = Context.ShortFractTy;
3838       } else if (Literal.isLong) {
3839         Ty = Context.LongFractTy;
3840       } else {
3841         Ty = Context.FractTy;
3842       }
3843     }
3844 
3845     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3846 
3847     bool isSigned = !Literal.isUnsigned;
3848     unsigned scale = Context.getFixedPointScale(Ty);
3849     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3850 
3851     llvm::APInt Val(bit_width, 0, isSigned);
3852     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3853     bool ValIsZero = Val.isZero() && !Overflowed;
3854 
3855     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3856     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3857       // Clause 6.4.4 - The value of a constant shall be in the range of
3858       // representable values for its type, with exception for constants of a
3859       // fract type with a value of exactly 1; such a constant shall denote
3860       // the maximal value for the type.
3861       --Val;
3862     else if (Val.ugt(MaxVal) || Overflowed)
3863       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3864 
3865     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3866                                               Tok.getLocation(), scale);
3867   } else if (Literal.isFloatingLiteral()) {
3868     QualType Ty;
3869     if (Literal.isHalf){
3870       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3871         Ty = Context.HalfTy;
3872       else {
3873         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3874         return ExprError();
3875       }
3876     } else if (Literal.isFloat)
3877       Ty = Context.FloatTy;
3878     else if (Literal.isLong)
3879       Ty = Context.LongDoubleTy;
3880     else if (Literal.isFloat16)
3881       Ty = Context.Float16Ty;
3882     else if (Literal.isFloat128)
3883       Ty = Context.Float128Ty;
3884     else
3885       Ty = Context.DoubleTy;
3886 
3887     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3888 
3889     if (Ty == Context.DoubleTy) {
3890       if (getLangOpts().SinglePrecisionConstants) {
3891         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3892           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3893         }
3894       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3895                                              "cl_khr_fp64", getLangOpts())) {
3896         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3897         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3898             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3899         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3900       }
3901     }
3902   } else if (!Literal.isIntegerLiteral()) {
3903     return ExprError();
3904   } else {
3905     QualType Ty;
3906 
3907     // 'long long' is a C99 or C++11 feature.
3908     if (!getLangOpts().C99 && Literal.isLongLong) {
3909       if (getLangOpts().CPlusPlus)
3910         Diag(Tok.getLocation(),
3911              getLangOpts().CPlusPlus11 ?
3912              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3913       else
3914         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3915     }
3916 
3917     // 'z/uz' literals are a C++2b feature.
3918     if (Literal.isSizeT)
3919       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3920                                   ? getLangOpts().CPlusPlus2b
3921                                         ? diag::warn_cxx20_compat_size_t_suffix
3922                                         : diag::ext_cxx2b_size_t_suffix
3923                                   : diag::err_cxx2b_size_t_suffix);
3924 
3925     // Get the value in the widest-possible width.
3926     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3927     llvm::APInt ResultVal(MaxWidth, 0);
3928 
3929     if (Literal.GetIntegerValue(ResultVal)) {
3930       // If this value didn't fit into uintmax_t, error and force to ull.
3931       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3932           << /* Unsigned */ 1;
3933       Ty = Context.UnsignedLongLongTy;
3934       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3935              "long long is not intmax_t?");
3936     } else {
3937       // If this value fits into a ULL, try to figure out what else it fits into
3938       // according to the rules of C99 6.4.4.1p5.
3939 
3940       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3941       // be an unsigned int.
3942       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3943 
3944       // Check from smallest to largest, picking the smallest type we can.
3945       unsigned Width = 0;
3946 
3947       // Microsoft specific integer suffixes are explicitly sized.
3948       if (Literal.MicrosoftInteger) {
3949         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3950           Width = 8;
3951           Ty = Context.CharTy;
3952         } else {
3953           Width = Literal.MicrosoftInteger;
3954           Ty = Context.getIntTypeForBitwidth(Width,
3955                                              /*Signed=*/!Literal.isUnsigned);
3956         }
3957       }
3958 
3959       // Check C++2b size_t literals.
3960       if (Literal.isSizeT) {
3961         assert(!Literal.MicrosoftInteger &&
3962                "size_t literals can't be Microsoft literals");
3963         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3964             Context.getTargetInfo().getSizeType());
3965 
3966         // Does it fit in size_t?
3967         if (ResultVal.isIntN(SizeTSize)) {
3968           // Does it fit in ssize_t?
3969           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3970             Ty = Context.getSignedSizeType();
3971           else if (AllowUnsigned)
3972             Ty = Context.getSizeType();
3973           Width = SizeTSize;
3974         }
3975       }
3976 
3977       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3978           !Literal.isSizeT) {
3979         // Are int/unsigned possibilities?
3980         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3981 
3982         // Does it fit in a unsigned int?
3983         if (ResultVal.isIntN(IntSize)) {
3984           // Does it fit in a signed int?
3985           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3986             Ty = Context.IntTy;
3987           else if (AllowUnsigned)
3988             Ty = Context.UnsignedIntTy;
3989           Width = IntSize;
3990         }
3991       }
3992 
3993       // Are long/unsigned long possibilities?
3994       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3995         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3996 
3997         // Does it fit in a unsigned long?
3998         if (ResultVal.isIntN(LongSize)) {
3999           // Does it fit in a signed long?
4000           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4001             Ty = Context.LongTy;
4002           else if (AllowUnsigned)
4003             Ty = Context.UnsignedLongTy;
4004           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4005           // is compatible.
4006           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4007             const unsigned LongLongSize =
4008                 Context.getTargetInfo().getLongLongWidth();
4009             Diag(Tok.getLocation(),
4010                  getLangOpts().CPlusPlus
4011                      ? Literal.isLong
4012                            ? diag::warn_old_implicitly_unsigned_long_cxx
4013                            : /*C++98 UB*/ diag::
4014                                  ext_old_implicitly_unsigned_long_cxx
4015                      : diag::warn_old_implicitly_unsigned_long)
4016                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4017                                             : /*will be ill-formed*/ 1);
4018             Ty = Context.UnsignedLongTy;
4019           }
4020           Width = LongSize;
4021         }
4022       }
4023 
4024       // Check long long if needed.
4025       if (Ty.isNull() && !Literal.isSizeT) {
4026         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4027 
4028         // Does it fit in a unsigned long long?
4029         if (ResultVal.isIntN(LongLongSize)) {
4030           // Does it fit in a signed long long?
4031           // To be compatible with MSVC, hex integer literals ending with the
4032           // LL or i64 suffix are always signed in Microsoft mode.
4033           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4034               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4035             Ty = Context.LongLongTy;
4036           else if (AllowUnsigned)
4037             Ty = Context.UnsignedLongLongTy;
4038           Width = LongLongSize;
4039         }
4040       }
4041 
4042       // If we still couldn't decide a type, we either have 'size_t' literal
4043       // that is out of range, or a decimal literal that does not fit in a
4044       // signed long long and has no U suffix.
4045       if (Ty.isNull()) {
4046         if (Literal.isSizeT)
4047           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4048               << Literal.isUnsigned;
4049         else
4050           Diag(Tok.getLocation(),
4051                diag::ext_integer_literal_too_large_for_signed);
4052         Ty = Context.UnsignedLongLongTy;
4053         Width = Context.getTargetInfo().getLongLongWidth();
4054       }
4055 
4056       if (ResultVal.getBitWidth() != Width)
4057         ResultVal = ResultVal.trunc(Width);
4058     }
4059     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4060   }
4061 
4062   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4063   if (Literal.isImaginary) {
4064     Res = new (Context) ImaginaryLiteral(Res,
4065                                         Context.getComplexType(Res->getType()));
4066 
4067     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4068   }
4069   return Res;
4070 }
4071 
4072 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4073   assert(E && "ActOnParenExpr() missing expr");
4074   QualType ExprTy = E->getType();
4075   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4076       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4077     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4078   return new (Context) ParenExpr(L, R, E);
4079 }
4080 
4081 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4082                                          SourceLocation Loc,
4083                                          SourceRange ArgRange) {
4084   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4085   // scalar or vector data type argument..."
4086   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4087   // type (C99 6.2.5p18) or void.
4088   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4089     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4090       << T << ArgRange;
4091     return true;
4092   }
4093 
4094   assert((T->isVoidType() || !T->isIncompleteType()) &&
4095          "Scalar types should always be complete");
4096   return false;
4097 }
4098 
4099 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4100                                            SourceLocation Loc,
4101                                            SourceRange ArgRange,
4102                                            UnaryExprOrTypeTrait TraitKind) {
4103   // Invalid types must be hard errors for SFINAE in C++.
4104   if (S.LangOpts.CPlusPlus)
4105     return true;
4106 
4107   // C99 6.5.3.4p1:
4108   if (T->isFunctionType() &&
4109       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4110        TraitKind == UETT_PreferredAlignOf)) {
4111     // sizeof(function)/alignof(function) is allowed as an extension.
4112     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4113         << getTraitSpelling(TraitKind) << ArgRange;
4114     return false;
4115   }
4116 
4117   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4118   // this is an error (OpenCL v1.1 s6.3.k)
4119   if (T->isVoidType()) {
4120     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4121                                         : diag::ext_sizeof_alignof_void_type;
4122     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4123     return false;
4124   }
4125 
4126   return true;
4127 }
4128 
4129 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4130                                              SourceLocation Loc,
4131                                              SourceRange ArgRange,
4132                                              UnaryExprOrTypeTrait TraitKind) {
4133   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4134   // runtime doesn't allow it.
4135   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4136     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4137       << T << (TraitKind == UETT_SizeOf)
4138       << ArgRange;
4139     return true;
4140   }
4141 
4142   return false;
4143 }
4144 
4145 /// Check whether E is a pointer from a decayed array type (the decayed
4146 /// pointer type is equal to T) and emit a warning if it is.
4147 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4148                                      Expr *E) {
4149   // Don't warn if the operation changed the type.
4150   if (T != E->getType())
4151     return;
4152 
4153   // Now look for array decays.
4154   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4155   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4156     return;
4157 
4158   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4159                                              << ICE->getType()
4160                                              << ICE->getSubExpr()->getType();
4161 }
4162 
4163 /// Check the constraints on expression operands to unary type expression
4164 /// and type traits.
4165 ///
4166 /// Completes any types necessary and validates the constraints on the operand
4167 /// expression. The logic mostly mirrors the type-based overload, but may modify
4168 /// the expression as it completes the type for that expression through template
4169 /// instantiation, etc.
4170 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4171                                             UnaryExprOrTypeTrait ExprKind) {
4172   QualType ExprTy = E->getType();
4173   assert(!ExprTy->isReferenceType());
4174 
4175   bool IsUnevaluatedOperand =
4176       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4177        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4178   if (IsUnevaluatedOperand) {
4179     ExprResult Result = CheckUnevaluatedOperand(E);
4180     if (Result.isInvalid())
4181       return true;
4182     E = Result.get();
4183   }
4184 
4185   // The operand for sizeof and alignof is in an unevaluated expression context,
4186   // so side effects could result in unintended consequences.
4187   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4188   // used to build SFINAE gadgets.
4189   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4190   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4191       !E->isInstantiationDependent() &&
4192       E->HasSideEffects(Context, false))
4193     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4194 
4195   if (ExprKind == UETT_VecStep)
4196     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4197                                         E->getSourceRange());
4198 
4199   // Explicitly list some types as extensions.
4200   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4201                                       E->getSourceRange(), ExprKind))
4202     return false;
4203 
4204   // 'alignof' applied to an expression only requires the base element type of
4205   // the expression to be complete. 'sizeof' requires the expression's type to
4206   // be complete (and will attempt to complete it if it's an array of unknown
4207   // bound).
4208   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4209     if (RequireCompleteSizedType(
4210             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4211             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4212             getTraitSpelling(ExprKind), E->getSourceRange()))
4213       return true;
4214   } else {
4215     if (RequireCompleteSizedExprType(
4216             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4217             getTraitSpelling(ExprKind), E->getSourceRange()))
4218       return true;
4219   }
4220 
4221   // Completing the expression's type may have changed it.
4222   ExprTy = E->getType();
4223   assert(!ExprTy->isReferenceType());
4224 
4225   if (ExprTy->isFunctionType()) {
4226     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4227         << getTraitSpelling(ExprKind) << E->getSourceRange();
4228     return true;
4229   }
4230 
4231   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4232                                        E->getSourceRange(), ExprKind))
4233     return true;
4234 
4235   if (ExprKind == UETT_SizeOf) {
4236     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4237       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4238         QualType OType = PVD->getOriginalType();
4239         QualType Type = PVD->getType();
4240         if (Type->isPointerType() && OType->isArrayType()) {
4241           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4242             << Type << OType;
4243           Diag(PVD->getLocation(), diag::note_declared_at);
4244         }
4245       }
4246     }
4247 
4248     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4249     // decays into a pointer and returns an unintended result. This is most
4250     // likely a typo for "sizeof(array) op x".
4251     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4252       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4253                                BO->getLHS());
4254       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4255                                BO->getRHS());
4256     }
4257   }
4258 
4259   return false;
4260 }
4261 
4262 /// Check the constraints on operands to unary expression and type
4263 /// traits.
4264 ///
4265 /// This will complete any types necessary, and validate the various constraints
4266 /// on those operands.
4267 ///
4268 /// The UsualUnaryConversions() function is *not* called by this routine.
4269 /// C99 6.3.2.1p[2-4] all state:
4270 ///   Except when it is the operand of the sizeof operator ...
4271 ///
4272 /// C++ [expr.sizeof]p4
4273 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4274 ///   standard conversions are not applied to the operand of sizeof.
4275 ///
4276 /// This policy is followed for all of the unary trait expressions.
4277 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4278                                             SourceLocation OpLoc,
4279                                             SourceRange ExprRange,
4280                                             UnaryExprOrTypeTrait ExprKind) {
4281   if (ExprType->isDependentType())
4282     return false;
4283 
4284   // C++ [expr.sizeof]p2:
4285   //     When applied to a reference or a reference type, the result
4286   //     is the size of the referenced type.
4287   // C++11 [expr.alignof]p3:
4288   //     When alignof is applied to a reference type, the result
4289   //     shall be the alignment of the referenced type.
4290   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4291     ExprType = Ref->getPointeeType();
4292 
4293   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4294   //   When alignof or _Alignof is applied to an array type, the result
4295   //   is the alignment of the element type.
4296   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4297       ExprKind == UETT_OpenMPRequiredSimdAlign)
4298     ExprType = Context.getBaseElementType(ExprType);
4299 
4300   if (ExprKind == UETT_VecStep)
4301     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4302 
4303   // Explicitly list some types as extensions.
4304   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4305                                       ExprKind))
4306     return false;
4307 
4308   if (RequireCompleteSizedType(
4309           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4310           getTraitSpelling(ExprKind), ExprRange))
4311     return true;
4312 
4313   if (ExprType->isFunctionType()) {
4314     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4315         << getTraitSpelling(ExprKind) << ExprRange;
4316     return true;
4317   }
4318 
4319   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4320                                        ExprKind))
4321     return true;
4322 
4323   return false;
4324 }
4325 
4326 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4327   // Cannot know anything else if the expression is dependent.
4328   if (E->isTypeDependent())
4329     return false;
4330 
4331   if (E->getObjectKind() == OK_BitField) {
4332     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4333        << 1 << E->getSourceRange();
4334     return true;
4335   }
4336 
4337   ValueDecl *D = nullptr;
4338   Expr *Inner = E->IgnoreParens();
4339   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4340     D = DRE->getDecl();
4341   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4342     D = ME->getMemberDecl();
4343   }
4344 
4345   // If it's a field, require the containing struct to have a
4346   // complete definition so that we can compute the layout.
4347   //
4348   // This can happen in C++11 onwards, either by naming the member
4349   // in a way that is not transformed into a member access expression
4350   // (in an unevaluated operand, for instance), or by naming the member
4351   // in a trailing-return-type.
4352   //
4353   // For the record, since __alignof__ on expressions is a GCC
4354   // extension, GCC seems to permit this but always gives the
4355   // nonsensical answer 0.
4356   //
4357   // We don't really need the layout here --- we could instead just
4358   // directly check for all the appropriate alignment-lowing
4359   // attributes --- but that would require duplicating a lot of
4360   // logic that just isn't worth duplicating for such a marginal
4361   // use-case.
4362   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4363     // Fast path this check, since we at least know the record has a
4364     // definition if we can find a member of it.
4365     if (!FD->getParent()->isCompleteDefinition()) {
4366       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4367         << E->getSourceRange();
4368       return true;
4369     }
4370 
4371     // Otherwise, if it's a field, and the field doesn't have
4372     // reference type, then it must have a complete type (or be a
4373     // flexible array member, which we explicitly want to
4374     // white-list anyway), which makes the following checks trivial.
4375     if (!FD->getType()->isReferenceType())
4376       return false;
4377   }
4378 
4379   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4380 }
4381 
4382 bool Sema::CheckVecStepExpr(Expr *E) {
4383   E = E->IgnoreParens();
4384 
4385   // Cannot know anything else if the expression is dependent.
4386   if (E->isTypeDependent())
4387     return false;
4388 
4389   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4390 }
4391 
4392 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4393                                         CapturingScopeInfo *CSI) {
4394   assert(T->isVariablyModifiedType());
4395   assert(CSI != nullptr);
4396 
4397   // We're going to walk down into the type and look for VLA expressions.
4398   do {
4399     const Type *Ty = T.getTypePtr();
4400     switch (Ty->getTypeClass()) {
4401 #define TYPE(Class, Base)
4402 #define ABSTRACT_TYPE(Class, Base)
4403 #define NON_CANONICAL_TYPE(Class, Base)
4404 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4405 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4406 #include "clang/AST/TypeNodes.inc"
4407       T = QualType();
4408       break;
4409     // These types are never variably-modified.
4410     case Type::Builtin:
4411     case Type::Complex:
4412     case Type::Vector:
4413     case Type::ExtVector:
4414     case Type::ConstantMatrix:
4415     case Type::Record:
4416     case Type::Enum:
4417     case Type::Elaborated:
4418     case Type::TemplateSpecialization:
4419     case Type::ObjCObject:
4420     case Type::ObjCInterface:
4421     case Type::ObjCObjectPointer:
4422     case Type::ObjCTypeParam:
4423     case Type::Pipe:
4424     case Type::BitInt:
4425       llvm_unreachable("type class is never variably-modified!");
4426     case Type::Adjusted:
4427       T = cast<AdjustedType>(Ty)->getOriginalType();
4428       break;
4429     case Type::Decayed:
4430       T = cast<DecayedType>(Ty)->getPointeeType();
4431       break;
4432     case Type::Pointer:
4433       T = cast<PointerType>(Ty)->getPointeeType();
4434       break;
4435     case Type::BlockPointer:
4436       T = cast<BlockPointerType>(Ty)->getPointeeType();
4437       break;
4438     case Type::LValueReference:
4439     case Type::RValueReference:
4440       T = cast<ReferenceType>(Ty)->getPointeeType();
4441       break;
4442     case Type::MemberPointer:
4443       T = cast<MemberPointerType>(Ty)->getPointeeType();
4444       break;
4445     case Type::ConstantArray:
4446     case Type::IncompleteArray:
4447       // Losing element qualification here is fine.
4448       T = cast<ArrayType>(Ty)->getElementType();
4449       break;
4450     case Type::VariableArray: {
4451       // Losing element qualification here is fine.
4452       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4453 
4454       // Unknown size indication requires no size computation.
4455       // Otherwise, evaluate and record it.
4456       auto Size = VAT->getSizeExpr();
4457       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4458           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4459         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4460 
4461       T = VAT->getElementType();
4462       break;
4463     }
4464     case Type::FunctionProto:
4465     case Type::FunctionNoProto:
4466       T = cast<FunctionType>(Ty)->getReturnType();
4467       break;
4468     case Type::Paren:
4469     case Type::TypeOf:
4470     case Type::UnaryTransform:
4471     case Type::Attributed:
4472     case Type::SubstTemplateTypeParm:
4473     case Type::MacroQualified:
4474       // Keep walking after single level desugaring.
4475       T = T.getSingleStepDesugaredType(Context);
4476       break;
4477     case Type::Typedef:
4478       T = cast<TypedefType>(Ty)->desugar();
4479       break;
4480     case Type::Decltype:
4481       T = cast<DecltypeType>(Ty)->desugar();
4482       break;
4483     case Type::Using:
4484       T = cast<UsingType>(Ty)->desugar();
4485       break;
4486     case Type::Auto:
4487     case Type::DeducedTemplateSpecialization:
4488       T = cast<DeducedType>(Ty)->getDeducedType();
4489       break;
4490     case Type::TypeOfExpr:
4491       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4492       break;
4493     case Type::Atomic:
4494       T = cast<AtomicType>(Ty)->getValueType();
4495       break;
4496     }
4497   } while (!T.isNull() && T->isVariablyModifiedType());
4498 }
4499 
4500 /// Build a sizeof or alignof expression given a type operand.
4501 ExprResult
4502 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4503                                      SourceLocation OpLoc,
4504                                      UnaryExprOrTypeTrait ExprKind,
4505                                      SourceRange R) {
4506   if (!TInfo)
4507     return ExprError();
4508 
4509   QualType T = TInfo->getType();
4510 
4511   if (!T->isDependentType() &&
4512       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4513     return ExprError();
4514 
4515   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4516     if (auto *TT = T->getAs<TypedefType>()) {
4517       for (auto I = FunctionScopes.rbegin(),
4518                 E = std::prev(FunctionScopes.rend());
4519            I != E; ++I) {
4520         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4521         if (CSI == nullptr)
4522           break;
4523         DeclContext *DC = nullptr;
4524         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4525           DC = LSI->CallOperator;
4526         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4527           DC = CRSI->TheCapturedDecl;
4528         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4529           DC = BSI->TheDecl;
4530         if (DC) {
4531           if (DC->containsDecl(TT->getDecl()))
4532             break;
4533           captureVariablyModifiedType(Context, T, CSI);
4534         }
4535       }
4536     }
4537   }
4538 
4539   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4540   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4541       TInfo->getType()->isVariablyModifiedType())
4542     TInfo = TransformToPotentiallyEvaluated(TInfo);
4543 
4544   return new (Context) UnaryExprOrTypeTraitExpr(
4545       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4546 }
4547 
4548 /// Build a sizeof or alignof expression given an expression
4549 /// operand.
4550 ExprResult
4551 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4552                                      UnaryExprOrTypeTrait ExprKind) {
4553   ExprResult PE = CheckPlaceholderExpr(E);
4554   if (PE.isInvalid())
4555     return ExprError();
4556 
4557   E = PE.get();
4558 
4559   // Verify that the operand is valid.
4560   bool isInvalid = false;
4561   if (E->isTypeDependent()) {
4562     // Delay type-checking for type-dependent expressions.
4563   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4564     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4565   } else if (ExprKind == UETT_VecStep) {
4566     isInvalid = CheckVecStepExpr(E);
4567   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4568       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4569       isInvalid = true;
4570   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4571     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4572     isInvalid = true;
4573   } else {
4574     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4575   }
4576 
4577   if (isInvalid)
4578     return ExprError();
4579 
4580   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4581     PE = TransformToPotentiallyEvaluated(E);
4582     if (PE.isInvalid()) return ExprError();
4583     E = PE.get();
4584   }
4585 
4586   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4587   return new (Context) UnaryExprOrTypeTraitExpr(
4588       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4589 }
4590 
4591 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4592 /// expr and the same for @c alignof and @c __alignof
4593 /// Note that the ArgRange is invalid if isType is false.
4594 ExprResult
4595 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4596                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4597                                     void *TyOrEx, SourceRange ArgRange) {
4598   // If error parsing type, ignore.
4599   if (!TyOrEx) return ExprError();
4600 
4601   if (IsType) {
4602     TypeSourceInfo *TInfo;
4603     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4604     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4605   }
4606 
4607   Expr *ArgEx = (Expr *)TyOrEx;
4608   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4609   return Result;
4610 }
4611 
4612 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4613                                      bool IsReal) {
4614   if (V.get()->isTypeDependent())
4615     return S.Context.DependentTy;
4616 
4617   // _Real and _Imag are only l-values for normal l-values.
4618   if (V.get()->getObjectKind() != OK_Ordinary) {
4619     V = S.DefaultLvalueConversion(V.get());
4620     if (V.isInvalid())
4621       return QualType();
4622   }
4623 
4624   // These operators return the element type of a complex type.
4625   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4626     return CT->getElementType();
4627 
4628   // Otherwise they pass through real integer and floating point types here.
4629   if (V.get()->getType()->isArithmeticType())
4630     return V.get()->getType();
4631 
4632   // Test for placeholders.
4633   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4634   if (PR.isInvalid()) return QualType();
4635   if (PR.get() != V.get()) {
4636     V = PR;
4637     return CheckRealImagOperand(S, V, Loc, IsReal);
4638   }
4639 
4640   // Reject anything else.
4641   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4642     << (IsReal ? "__real" : "__imag");
4643   return QualType();
4644 }
4645 
4646 
4647 
4648 ExprResult
4649 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4650                           tok::TokenKind Kind, Expr *Input) {
4651   UnaryOperatorKind Opc;
4652   switch (Kind) {
4653   default: llvm_unreachable("Unknown unary op!");
4654   case tok::plusplus:   Opc = UO_PostInc; break;
4655   case tok::minusminus: Opc = UO_PostDec; break;
4656   }
4657 
4658   // Since this might is a postfix expression, get rid of ParenListExprs.
4659   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4660   if (Result.isInvalid()) return ExprError();
4661   Input = Result.get();
4662 
4663   return BuildUnaryOp(S, OpLoc, Opc, Input);
4664 }
4665 
4666 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4667 ///
4668 /// \return true on error
4669 static bool checkArithmeticOnObjCPointer(Sema &S,
4670                                          SourceLocation opLoc,
4671                                          Expr *op) {
4672   assert(op->getType()->isObjCObjectPointerType());
4673   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4674       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4675     return false;
4676 
4677   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4678     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4679     << op->getSourceRange();
4680   return true;
4681 }
4682 
4683 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4684   auto *BaseNoParens = Base->IgnoreParens();
4685   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4686     return MSProp->getPropertyDecl()->getType()->isArrayType();
4687   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4688 }
4689 
4690 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4691 // Typically this is DependentTy, but can sometimes be more precise.
4692 //
4693 // There are cases when we could determine a non-dependent type:
4694 //  - LHS and RHS may have non-dependent types despite being type-dependent
4695 //    (e.g. unbounded array static members of the current instantiation)
4696 //  - one may be a dependent-sized array with known element type
4697 //  - one may be a dependent-typed valid index (enum in current instantiation)
4698 //
4699 // We *always* return a dependent type, in such cases it is DependentTy.
4700 // This avoids creating type-dependent expressions with non-dependent types.
4701 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4702 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4703                                                const ASTContext &Ctx) {
4704   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4705   QualType LTy = LHS->getType(), RTy = RHS->getType();
4706   QualType Result = Ctx.DependentTy;
4707   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4708     if (const PointerType *PT = LTy->getAs<PointerType>())
4709       Result = PT->getPointeeType();
4710     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4711       Result = AT->getElementType();
4712   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4713     if (const PointerType *PT = RTy->getAs<PointerType>())
4714       Result = PT->getPointeeType();
4715     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4716       Result = AT->getElementType();
4717   }
4718   // Ensure we return a dependent type.
4719   return Result->isDependentType() ? Result : Ctx.DependentTy;
4720 }
4721 
4722 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4723 
4724 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4725                                          SourceLocation lbLoc,
4726                                          MultiExprArg ArgExprs,
4727                                          SourceLocation rbLoc) {
4728 
4729   if (base && !base->getType().isNull() &&
4730       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4731     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4732                                     SourceLocation(), /*Length*/ nullptr,
4733                                     /*Stride=*/nullptr, rbLoc);
4734 
4735   // Since this might be a postfix expression, get rid of ParenListExprs.
4736   if (isa<ParenListExpr>(base)) {
4737     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4738     if (result.isInvalid())
4739       return ExprError();
4740     base = result.get();
4741   }
4742 
4743   // Check if base and idx form a MatrixSubscriptExpr.
4744   //
4745   // Helper to check for comma expressions, which are not allowed as indices for
4746   // matrix subscript expressions.
4747   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4748     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4749       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4750           << SourceRange(base->getBeginLoc(), rbLoc);
4751       return true;
4752     }
4753     return false;
4754   };
4755   // The matrix subscript operator ([][])is considered a single operator.
4756   // Separating the index expressions by parenthesis is not allowed.
4757   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4758       !isa<MatrixSubscriptExpr>(base)) {
4759     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4760         << SourceRange(base->getBeginLoc(), rbLoc);
4761     return ExprError();
4762   }
4763   // If the base is a MatrixSubscriptExpr, try to create a new
4764   // MatrixSubscriptExpr.
4765   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4766   if (matSubscriptE) {
4767     assert(ArgExprs.size() == 1);
4768     if (CheckAndReportCommaError(ArgExprs.front()))
4769       return ExprError();
4770 
4771     assert(matSubscriptE->isIncomplete() &&
4772            "base has to be an incomplete matrix subscript");
4773     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4774                                             matSubscriptE->getRowIdx(),
4775                                             ArgExprs.front(), rbLoc);
4776   }
4777 
4778   // Handle any non-overload placeholder types in the base and index
4779   // expressions.  We can't handle overloads here because the other
4780   // operand might be an overloadable type, in which case the overload
4781   // resolution for the operator overload should get the first crack
4782   // at the overload.
4783   bool IsMSPropertySubscript = false;
4784   if (base->getType()->isNonOverloadPlaceholderType()) {
4785     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4786     if (!IsMSPropertySubscript) {
4787       ExprResult result = CheckPlaceholderExpr(base);
4788       if (result.isInvalid())
4789         return ExprError();
4790       base = result.get();
4791     }
4792   }
4793 
4794   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4795   if (base->getType()->isMatrixType()) {
4796     assert(ArgExprs.size() == 1);
4797     if (CheckAndReportCommaError(ArgExprs.front()))
4798       return ExprError();
4799 
4800     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4801                                             rbLoc);
4802   }
4803 
4804   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4805     Expr *idx = ArgExprs[0];
4806     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4807         (isa<CXXOperatorCallExpr>(idx) &&
4808          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4809       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4810           << SourceRange(base->getBeginLoc(), rbLoc);
4811     }
4812   }
4813 
4814   if (ArgExprs.size() == 1 &&
4815       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4816     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4817     if (result.isInvalid())
4818       return ExprError();
4819     ArgExprs[0] = result.get();
4820   } else {
4821     if (checkArgsForPlaceholders(*this, ArgExprs))
4822       return ExprError();
4823   }
4824 
4825   // Build an unanalyzed expression if either operand is type-dependent.
4826   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4827       (base->isTypeDependent() ||
4828        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4829     return new (Context) ArraySubscriptExpr(
4830         base, ArgExprs.front(),
4831         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4832         VK_LValue, OK_Ordinary, rbLoc);
4833   }
4834 
4835   // MSDN, property (C++)
4836   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4837   // This attribute can also be used in the declaration of an empty array in a
4838   // class or structure definition. For example:
4839   // __declspec(property(get=GetX, put=PutX)) int x[];
4840   // The above statement indicates that x[] can be used with one or more array
4841   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4842   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4843   if (IsMSPropertySubscript) {
4844     assert(ArgExprs.size() == 1);
4845     // Build MS property subscript expression if base is MS property reference
4846     // or MS property subscript.
4847     return new (Context)
4848         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4849                                 VK_LValue, OK_Ordinary, rbLoc);
4850   }
4851 
4852   // Use C++ overloaded-operator rules if either operand has record
4853   // type.  The spec says to do this if either type is *overloadable*,
4854   // but enum types can't declare subscript operators or conversion
4855   // operators, so there's nothing interesting for overload resolution
4856   // to do if there aren't any record types involved.
4857   //
4858   // ObjC pointers have their own subscripting logic that is not tied
4859   // to overload resolution and so should not take this path.
4860   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4861       ((base->getType()->isRecordType() ||
4862         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4863     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4864   }
4865 
4866   ExprResult Res =
4867       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4868 
4869   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4870     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4871 
4872   return Res;
4873 }
4874 
4875 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4876   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4877   InitializationKind Kind =
4878       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4879   InitializationSequence InitSeq(*this, Entity, Kind, E);
4880   return InitSeq.Perform(*this, Entity, Kind, E);
4881 }
4882 
4883 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4884                                                   Expr *ColumnIdx,
4885                                                   SourceLocation RBLoc) {
4886   ExprResult BaseR = CheckPlaceholderExpr(Base);
4887   if (BaseR.isInvalid())
4888     return BaseR;
4889   Base = BaseR.get();
4890 
4891   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4892   if (RowR.isInvalid())
4893     return RowR;
4894   RowIdx = RowR.get();
4895 
4896   if (!ColumnIdx)
4897     return new (Context) MatrixSubscriptExpr(
4898         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4899 
4900   // Build an unanalyzed expression if any of the operands is type-dependent.
4901   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4902       ColumnIdx->isTypeDependent())
4903     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4904                                              Context.DependentTy, RBLoc);
4905 
4906   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4907   if (ColumnR.isInvalid())
4908     return ColumnR;
4909   ColumnIdx = ColumnR.get();
4910 
4911   // Check that IndexExpr is an integer expression. If it is a constant
4912   // expression, check that it is less than Dim (= the number of elements in the
4913   // corresponding dimension).
4914   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4915                           bool IsColumnIdx) -> Expr * {
4916     if (!IndexExpr->getType()->isIntegerType() &&
4917         !IndexExpr->isTypeDependent()) {
4918       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4919           << IsColumnIdx;
4920       return nullptr;
4921     }
4922 
4923     if (Optional<llvm::APSInt> Idx =
4924             IndexExpr->getIntegerConstantExpr(Context)) {
4925       if ((*Idx < 0 || *Idx >= Dim)) {
4926         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4927             << IsColumnIdx << Dim;
4928         return nullptr;
4929       }
4930     }
4931 
4932     ExprResult ConvExpr =
4933         tryConvertExprToType(IndexExpr, Context.getSizeType());
4934     assert(!ConvExpr.isInvalid() &&
4935            "should be able to convert any integer type to size type");
4936     return ConvExpr.get();
4937   };
4938 
4939   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4940   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4941   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4942   if (!RowIdx || !ColumnIdx)
4943     return ExprError();
4944 
4945   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4946                                            MTy->getElementType(), RBLoc);
4947 }
4948 
4949 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4950   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4951   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4952 
4953   // For expressions like `&(*s).b`, the base is recorded and what should be
4954   // checked.
4955   const MemberExpr *Member = nullptr;
4956   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4957     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4958 
4959   LastRecord.PossibleDerefs.erase(StrippedExpr);
4960 }
4961 
4962 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4963   if (isUnevaluatedContext())
4964     return;
4965 
4966   QualType ResultTy = E->getType();
4967   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4968 
4969   // Bail if the element is an array since it is not memory access.
4970   if (isa<ArrayType>(ResultTy))
4971     return;
4972 
4973   if (ResultTy->hasAttr(attr::NoDeref)) {
4974     LastRecord.PossibleDerefs.insert(E);
4975     return;
4976   }
4977 
4978   // Check if the base type is a pointer to a member access of a struct
4979   // marked with noderef.
4980   const Expr *Base = E->getBase();
4981   QualType BaseTy = Base->getType();
4982   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4983     // Not a pointer access
4984     return;
4985 
4986   const MemberExpr *Member = nullptr;
4987   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4988          Member->isArrow())
4989     Base = Member->getBase();
4990 
4991   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4992     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4993       LastRecord.PossibleDerefs.insert(E);
4994   }
4995 }
4996 
4997 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4998                                           Expr *LowerBound,
4999                                           SourceLocation ColonLocFirst,
5000                                           SourceLocation ColonLocSecond,
5001                                           Expr *Length, Expr *Stride,
5002                                           SourceLocation RBLoc) {
5003   if (Base->hasPlaceholderType() &&
5004       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5005     ExprResult Result = CheckPlaceholderExpr(Base);
5006     if (Result.isInvalid())
5007       return ExprError();
5008     Base = Result.get();
5009   }
5010   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5011     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5012     if (Result.isInvalid())
5013       return ExprError();
5014     Result = DefaultLvalueConversion(Result.get());
5015     if (Result.isInvalid())
5016       return ExprError();
5017     LowerBound = Result.get();
5018   }
5019   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5020     ExprResult Result = CheckPlaceholderExpr(Length);
5021     if (Result.isInvalid())
5022       return ExprError();
5023     Result = DefaultLvalueConversion(Result.get());
5024     if (Result.isInvalid())
5025       return ExprError();
5026     Length = Result.get();
5027   }
5028   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5029     ExprResult Result = CheckPlaceholderExpr(Stride);
5030     if (Result.isInvalid())
5031       return ExprError();
5032     Result = DefaultLvalueConversion(Result.get());
5033     if (Result.isInvalid())
5034       return ExprError();
5035     Stride = Result.get();
5036   }
5037 
5038   // Build an unanalyzed expression if either operand is type-dependent.
5039   if (Base->isTypeDependent() ||
5040       (LowerBound &&
5041        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5042       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5043       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5044     return new (Context) OMPArraySectionExpr(
5045         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5046         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5047   }
5048 
5049   // Perform default conversions.
5050   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5051   QualType ResultTy;
5052   if (OriginalTy->isAnyPointerType()) {
5053     ResultTy = OriginalTy->getPointeeType();
5054   } else if (OriginalTy->isArrayType()) {
5055     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5056   } else {
5057     return ExprError(
5058         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5059         << Base->getSourceRange());
5060   }
5061   // C99 6.5.2.1p1
5062   if (LowerBound) {
5063     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5064                                                       LowerBound);
5065     if (Res.isInvalid())
5066       return ExprError(Diag(LowerBound->getExprLoc(),
5067                             diag::err_omp_typecheck_section_not_integer)
5068                        << 0 << LowerBound->getSourceRange());
5069     LowerBound = Res.get();
5070 
5071     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5072         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5073       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5074           << 0 << LowerBound->getSourceRange();
5075   }
5076   if (Length) {
5077     auto Res =
5078         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5079     if (Res.isInvalid())
5080       return ExprError(Diag(Length->getExprLoc(),
5081                             diag::err_omp_typecheck_section_not_integer)
5082                        << 1 << Length->getSourceRange());
5083     Length = Res.get();
5084 
5085     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5086         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5087       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5088           << 1 << Length->getSourceRange();
5089   }
5090   if (Stride) {
5091     ExprResult Res =
5092         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5093     if (Res.isInvalid())
5094       return ExprError(Diag(Stride->getExprLoc(),
5095                             diag::err_omp_typecheck_section_not_integer)
5096                        << 1 << Stride->getSourceRange());
5097     Stride = Res.get();
5098 
5099     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5100         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5101       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5102           << 1 << Stride->getSourceRange();
5103   }
5104 
5105   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5106   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5107   // type. Note that functions are not objects, and that (in C99 parlance)
5108   // incomplete types are not object types.
5109   if (ResultTy->isFunctionType()) {
5110     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5111         << ResultTy << Base->getSourceRange();
5112     return ExprError();
5113   }
5114 
5115   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5116                           diag::err_omp_section_incomplete_type, Base))
5117     return ExprError();
5118 
5119   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5120     Expr::EvalResult Result;
5121     if (LowerBound->EvaluateAsInt(Result, Context)) {
5122       // OpenMP 5.0, [2.1.5 Array Sections]
5123       // The array section must be a subset of the original array.
5124       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5125       if (LowerBoundValue.isNegative()) {
5126         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5127             << LowerBound->getSourceRange();
5128         return ExprError();
5129       }
5130     }
5131   }
5132 
5133   if (Length) {
5134     Expr::EvalResult Result;
5135     if (Length->EvaluateAsInt(Result, Context)) {
5136       // OpenMP 5.0, [2.1.5 Array Sections]
5137       // The length must evaluate to non-negative integers.
5138       llvm::APSInt LengthValue = Result.Val.getInt();
5139       if (LengthValue.isNegative()) {
5140         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5141             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5142             << Length->getSourceRange();
5143         return ExprError();
5144       }
5145     }
5146   } else if (ColonLocFirst.isValid() &&
5147              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5148                                       !OriginalTy->isVariableArrayType()))) {
5149     // OpenMP 5.0, [2.1.5 Array Sections]
5150     // When the size of the array dimension is not known, the length must be
5151     // specified explicitly.
5152     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5153         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5154     return ExprError();
5155   }
5156 
5157   if (Stride) {
5158     Expr::EvalResult Result;
5159     if (Stride->EvaluateAsInt(Result, Context)) {
5160       // OpenMP 5.0, [2.1.5 Array Sections]
5161       // The stride must evaluate to a positive integer.
5162       llvm::APSInt StrideValue = Result.Val.getInt();
5163       if (!StrideValue.isStrictlyPositive()) {
5164         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5165             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5166             << Stride->getSourceRange();
5167         return ExprError();
5168       }
5169     }
5170   }
5171 
5172   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5173     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5174     if (Result.isInvalid())
5175       return ExprError();
5176     Base = Result.get();
5177   }
5178   return new (Context) OMPArraySectionExpr(
5179       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5180       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5181 }
5182 
5183 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5184                                           SourceLocation RParenLoc,
5185                                           ArrayRef<Expr *> Dims,
5186                                           ArrayRef<SourceRange> Brackets) {
5187   if (Base->hasPlaceholderType()) {
5188     ExprResult Result = CheckPlaceholderExpr(Base);
5189     if (Result.isInvalid())
5190       return ExprError();
5191     Result = DefaultLvalueConversion(Result.get());
5192     if (Result.isInvalid())
5193       return ExprError();
5194     Base = Result.get();
5195   }
5196   QualType BaseTy = Base->getType();
5197   // Delay analysis of the types/expressions if instantiation/specialization is
5198   // required.
5199   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5200     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5201                                        LParenLoc, RParenLoc, Dims, Brackets);
5202   if (!BaseTy->isPointerType() ||
5203       (!Base->isTypeDependent() &&
5204        BaseTy->getPointeeType()->isIncompleteType()))
5205     return ExprError(Diag(Base->getExprLoc(),
5206                           diag::err_omp_non_pointer_type_array_shaping_base)
5207                      << Base->getSourceRange());
5208 
5209   SmallVector<Expr *, 4> NewDims;
5210   bool ErrorFound = false;
5211   for (Expr *Dim : Dims) {
5212     if (Dim->hasPlaceholderType()) {
5213       ExprResult Result = CheckPlaceholderExpr(Dim);
5214       if (Result.isInvalid()) {
5215         ErrorFound = true;
5216         continue;
5217       }
5218       Result = DefaultLvalueConversion(Result.get());
5219       if (Result.isInvalid()) {
5220         ErrorFound = true;
5221         continue;
5222       }
5223       Dim = Result.get();
5224     }
5225     if (!Dim->isTypeDependent()) {
5226       ExprResult Result =
5227           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5228       if (Result.isInvalid()) {
5229         ErrorFound = true;
5230         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5231             << Dim->getSourceRange();
5232         continue;
5233       }
5234       Dim = Result.get();
5235       Expr::EvalResult EvResult;
5236       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5237         // OpenMP 5.0, [2.1.4 Array Shaping]
5238         // Each si is an integral type expression that must evaluate to a
5239         // positive integer.
5240         llvm::APSInt Value = EvResult.Val.getInt();
5241         if (!Value.isStrictlyPositive()) {
5242           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5243               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5244               << Dim->getSourceRange();
5245           ErrorFound = true;
5246           continue;
5247         }
5248       }
5249     }
5250     NewDims.push_back(Dim);
5251   }
5252   if (ErrorFound)
5253     return ExprError();
5254   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5255                                      LParenLoc, RParenLoc, NewDims, Brackets);
5256 }
5257 
5258 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5259                                       SourceLocation LLoc, SourceLocation RLoc,
5260                                       ArrayRef<OMPIteratorData> Data) {
5261   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5262   bool IsCorrect = true;
5263   for (const OMPIteratorData &D : Data) {
5264     TypeSourceInfo *TInfo = nullptr;
5265     SourceLocation StartLoc;
5266     QualType DeclTy;
5267     if (!D.Type.getAsOpaquePtr()) {
5268       // OpenMP 5.0, 2.1.6 Iterators
5269       // In an iterator-specifier, if the iterator-type is not specified then
5270       // the type of that iterator is of int type.
5271       DeclTy = Context.IntTy;
5272       StartLoc = D.DeclIdentLoc;
5273     } else {
5274       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5275       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5276     }
5277 
5278     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5279                              DeclTy->containsUnexpandedParameterPack() ||
5280                              DeclTy->isInstantiationDependentType();
5281     if (!IsDeclTyDependent) {
5282       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5283         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5284         // The iterator-type must be an integral or pointer type.
5285         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5286             << DeclTy;
5287         IsCorrect = false;
5288         continue;
5289       }
5290       if (DeclTy.isConstant(Context)) {
5291         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5292         // The iterator-type must not be const qualified.
5293         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5294             << DeclTy;
5295         IsCorrect = false;
5296         continue;
5297       }
5298     }
5299 
5300     // Iterator declaration.
5301     assert(D.DeclIdent && "Identifier expected.");
5302     // Always try to create iterator declarator to avoid extra error messages
5303     // about unknown declarations use.
5304     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5305                                D.DeclIdent, DeclTy, TInfo, SC_None);
5306     VD->setImplicit();
5307     if (S) {
5308       // Check for conflicting previous declaration.
5309       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5310       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5311                             ForVisibleRedeclaration);
5312       Previous.suppressDiagnostics();
5313       LookupName(Previous, S);
5314 
5315       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5316                            /*AllowInlineNamespace=*/false);
5317       if (!Previous.empty()) {
5318         NamedDecl *Old = Previous.getRepresentativeDecl();
5319         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5320         Diag(Old->getLocation(), diag::note_previous_definition);
5321       } else {
5322         PushOnScopeChains(VD, S);
5323       }
5324     } else {
5325       CurContext->addDecl(VD);
5326     }
5327     Expr *Begin = D.Range.Begin;
5328     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5329       ExprResult BeginRes =
5330           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5331       Begin = BeginRes.get();
5332     }
5333     Expr *End = D.Range.End;
5334     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5335       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5336       End = EndRes.get();
5337     }
5338     Expr *Step = D.Range.Step;
5339     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5340       if (!Step->getType()->isIntegralType(Context)) {
5341         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5342             << Step << Step->getSourceRange();
5343         IsCorrect = false;
5344         continue;
5345       }
5346       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5347       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5348       // If the step expression of a range-specification equals zero, the
5349       // behavior is unspecified.
5350       if (Result && Result->isZero()) {
5351         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5352             << Step << Step->getSourceRange();
5353         IsCorrect = false;
5354         continue;
5355       }
5356     }
5357     if (!Begin || !End || !IsCorrect) {
5358       IsCorrect = false;
5359       continue;
5360     }
5361     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5362     IDElem.IteratorDecl = VD;
5363     IDElem.AssignmentLoc = D.AssignLoc;
5364     IDElem.Range.Begin = Begin;
5365     IDElem.Range.End = End;
5366     IDElem.Range.Step = Step;
5367     IDElem.ColonLoc = D.ColonLoc;
5368     IDElem.SecondColonLoc = D.SecColonLoc;
5369   }
5370   if (!IsCorrect) {
5371     // Invalidate all created iterator declarations if error is found.
5372     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5373       if (Decl *ID = D.IteratorDecl)
5374         ID->setInvalidDecl();
5375     }
5376     return ExprError();
5377   }
5378   SmallVector<OMPIteratorHelperData, 4> Helpers;
5379   if (!CurContext->isDependentContext()) {
5380     // Build number of ityeration for each iteration range.
5381     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5382     // ((Begini-Stepi-1-Endi) / -Stepi);
5383     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5384       // (Endi - Begini)
5385       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5386                                           D.Range.Begin);
5387       if(!Res.isUsable()) {
5388         IsCorrect = false;
5389         continue;
5390       }
5391       ExprResult St, St1;
5392       if (D.Range.Step) {
5393         St = D.Range.Step;
5394         // (Endi - Begini) + Stepi
5395         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5396         if (!Res.isUsable()) {
5397           IsCorrect = false;
5398           continue;
5399         }
5400         // (Endi - Begini) + Stepi - 1
5401         Res =
5402             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5403                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5404         if (!Res.isUsable()) {
5405           IsCorrect = false;
5406           continue;
5407         }
5408         // ((Endi - Begini) + Stepi - 1) / Stepi
5409         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5410         if (!Res.isUsable()) {
5411           IsCorrect = false;
5412           continue;
5413         }
5414         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5415         // (Begini - Endi)
5416         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5417                                              D.Range.Begin, D.Range.End);
5418         if (!Res1.isUsable()) {
5419           IsCorrect = false;
5420           continue;
5421         }
5422         // (Begini - Endi) - Stepi
5423         Res1 =
5424             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5425         if (!Res1.isUsable()) {
5426           IsCorrect = false;
5427           continue;
5428         }
5429         // (Begini - Endi) - Stepi - 1
5430         Res1 =
5431             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5432                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5433         if (!Res1.isUsable()) {
5434           IsCorrect = false;
5435           continue;
5436         }
5437         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5438         Res1 =
5439             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5440         if (!Res1.isUsable()) {
5441           IsCorrect = false;
5442           continue;
5443         }
5444         // Stepi > 0.
5445         ExprResult CmpRes =
5446             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5447                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5448         if (!CmpRes.isUsable()) {
5449           IsCorrect = false;
5450           continue;
5451         }
5452         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5453                                  Res.get(), Res1.get());
5454         if (!Res.isUsable()) {
5455           IsCorrect = false;
5456           continue;
5457         }
5458       }
5459       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5460       if (!Res.isUsable()) {
5461         IsCorrect = false;
5462         continue;
5463       }
5464 
5465       // Build counter update.
5466       // Build counter.
5467       auto *CounterVD =
5468           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5469                           D.IteratorDecl->getBeginLoc(), nullptr,
5470                           Res.get()->getType(), nullptr, SC_None);
5471       CounterVD->setImplicit();
5472       ExprResult RefRes =
5473           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5474                            D.IteratorDecl->getBeginLoc());
5475       // Build counter update.
5476       // I = Begini + counter * Stepi;
5477       ExprResult UpdateRes;
5478       if (D.Range.Step) {
5479         UpdateRes = CreateBuiltinBinOp(
5480             D.AssignmentLoc, BO_Mul,
5481             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5482       } else {
5483         UpdateRes = DefaultLvalueConversion(RefRes.get());
5484       }
5485       if (!UpdateRes.isUsable()) {
5486         IsCorrect = false;
5487         continue;
5488       }
5489       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5490                                      UpdateRes.get());
5491       if (!UpdateRes.isUsable()) {
5492         IsCorrect = false;
5493         continue;
5494       }
5495       ExprResult VDRes =
5496           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5497                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5498                            D.IteratorDecl->getBeginLoc());
5499       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5500                                      UpdateRes.get());
5501       if (!UpdateRes.isUsable()) {
5502         IsCorrect = false;
5503         continue;
5504       }
5505       UpdateRes =
5506           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5507       if (!UpdateRes.isUsable()) {
5508         IsCorrect = false;
5509         continue;
5510       }
5511       ExprResult CounterUpdateRes =
5512           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5513       if (!CounterUpdateRes.isUsable()) {
5514         IsCorrect = false;
5515         continue;
5516       }
5517       CounterUpdateRes =
5518           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5519       if (!CounterUpdateRes.isUsable()) {
5520         IsCorrect = false;
5521         continue;
5522       }
5523       OMPIteratorHelperData &HD = Helpers.emplace_back();
5524       HD.CounterVD = CounterVD;
5525       HD.Upper = Res.get();
5526       HD.Update = UpdateRes.get();
5527       HD.CounterUpdate = CounterUpdateRes.get();
5528     }
5529   } else {
5530     Helpers.assign(ID.size(), {});
5531   }
5532   if (!IsCorrect) {
5533     // Invalidate all created iterator declarations if error is found.
5534     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5535       if (Decl *ID = D.IteratorDecl)
5536         ID->setInvalidDecl();
5537     }
5538     return ExprError();
5539   }
5540   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5541                                  LLoc, RLoc, ID, Helpers);
5542 }
5543 
5544 ExprResult
5545 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5546                                       Expr *Idx, SourceLocation RLoc) {
5547   Expr *LHSExp = Base;
5548   Expr *RHSExp = Idx;
5549 
5550   ExprValueKind VK = VK_LValue;
5551   ExprObjectKind OK = OK_Ordinary;
5552 
5553   // Per C++ core issue 1213, the result is an xvalue if either operand is
5554   // a non-lvalue array, and an lvalue otherwise.
5555   if (getLangOpts().CPlusPlus11) {
5556     for (auto *Op : {LHSExp, RHSExp}) {
5557       Op = Op->IgnoreImplicit();
5558       if (Op->getType()->isArrayType() && !Op->isLValue())
5559         VK = VK_XValue;
5560     }
5561   }
5562 
5563   // Perform default conversions.
5564   if (!LHSExp->getType()->getAs<VectorType>()) {
5565     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5566     if (Result.isInvalid())
5567       return ExprError();
5568     LHSExp = Result.get();
5569   }
5570   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5571   if (Result.isInvalid())
5572     return ExprError();
5573   RHSExp = Result.get();
5574 
5575   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5576 
5577   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5578   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5579   // in the subscript position. As a result, we need to derive the array base
5580   // and index from the expression types.
5581   Expr *BaseExpr, *IndexExpr;
5582   QualType ResultType;
5583   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5584     BaseExpr = LHSExp;
5585     IndexExpr = RHSExp;
5586     ResultType =
5587         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5588   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5589     BaseExpr = LHSExp;
5590     IndexExpr = RHSExp;
5591     ResultType = PTy->getPointeeType();
5592   } else if (const ObjCObjectPointerType *PTy =
5593                LHSTy->getAs<ObjCObjectPointerType>()) {
5594     BaseExpr = LHSExp;
5595     IndexExpr = RHSExp;
5596 
5597     // Use custom logic if this should be the pseudo-object subscript
5598     // expression.
5599     if (!LangOpts.isSubscriptPointerArithmetic())
5600       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5601                                           nullptr);
5602 
5603     ResultType = PTy->getPointeeType();
5604   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5605      // Handle the uncommon case of "123[Ptr]".
5606     BaseExpr = RHSExp;
5607     IndexExpr = LHSExp;
5608     ResultType = PTy->getPointeeType();
5609   } else if (const ObjCObjectPointerType *PTy =
5610                RHSTy->getAs<ObjCObjectPointerType>()) {
5611      // Handle the uncommon case of "123[Ptr]".
5612     BaseExpr = RHSExp;
5613     IndexExpr = LHSExp;
5614     ResultType = PTy->getPointeeType();
5615     if (!LangOpts.isSubscriptPointerArithmetic()) {
5616       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5617         << ResultType << BaseExpr->getSourceRange();
5618       return ExprError();
5619     }
5620   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5621     BaseExpr = LHSExp;    // vectors: V[123]
5622     IndexExpr = RHSExp;
5623     // We apply C++ DR1213 to vector subscripting too.
5624     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5625       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5626       if (Materialized.isInvalid())
5627         return ExprError();
5628       LHSExp = Materialized.get();
5629     }
5630     VK = LHSExp->getValueKind();
5631     if (VK != VK_PRValue)
5632       OK = OK_VectorComponent;
5633 
5634     ResultType = VTy->getElementType();
5635     QualType BaseType = BaseExpr->getType();
5636     Qualifiers BaseQuals = BaseType.getQualifiers();
5637     Qualifiers MemberQuals = ResultType.getQualifiers();
5638     Qualifiers Combined = BaseQuals + MemberQuals;
5639     if (Combined != MemberQuals)
5640       ResultType = Context.getQualifiedType(ResultType, Combined);
5641   } else if (LHSTy->isArrayType()) {
5642     // If we see an array that wasn't promoted by
5643     // DefaultFunctionArrayLvalueConversion, it must be an array that
5644     // wasn't promoted because of the C90 rule that doesn't
5645     // allow promoting non-lvalue arrays.  Warn, then
5646     // force the promotion here.
5647     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5648         << LHSExp->getSourceRange();
5649     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5650                                CK_ArrayToPointerDecay).get();
5651     LHSTy = LHSExp->getType();
5652 
5653     BaseExpr = LHSExp;
5654     IndexExpr = RHSExp;
5655     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5656   } else if (RHSTy->isArrayType()) {
5657     // Same as previous, except for 123[f().a] case
5658     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5659         << RHSExp->getSourceRange();
5660     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5661                                CK_ArrayToPointerDecay).get();
5662     RHSTy = RHSExp->getType();
5663 
5664     BaseExpr = RHSExp;
5665     IndexExpr = LHSExp;
5666     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5667   } else {
5668     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5669        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5670   }
5671   // C99 6.5.2.1p1
5672   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5673     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5674                      << IndexExpr->getSourceRange());
5675 
5676   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5677        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5678          && !IndexExpr->isTypeDependent())
5679     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5680 
5681   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5682   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5683   // type. Note that Functions are not objects, and that (in C99 parlance)
5684   // incomplete types are not object types.
5685   if (ResultType->isFunctionType()) {
5686     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5687         << ResultType << BaseExpr->getSourceRange();
5688     return ExprError();
5689   }
5690 
5691   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5692     // GNU extension: subscripting on pointer to void
5693     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5694       << BaseExpr->getSourceRange();
5695 
5696     // C forbids expressions of unqualified void type from being l-values.
5697     // See IsCForbiddenLValueType.
5698     if (!ResultType.hasQualifiers())
5699       VK = VK_PRValue;
5700   } else if (!ResultType->isDependentType() &&
5701              RequireCompleteSizedType(
5702                  LLoc, ResultType,
5703                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5704     return ExprError();
5705 
5706   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5707          !ResultType.isCForbiddenLValueType());
5708 
5709   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5710       FunctionScopes.size() > 1) {
5711     if (auto *TT =
5712             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5713       for (auto I = FunctionScopes.rbegin(),
5714                 E = std::prev(FunctionScopes.rend());
5715            I != E; ++I) {
5716         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5717         if (CSI == nullptr)
5718           break;
5719         DeclContext *DC = nullptr;
5720         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5721           DC = LSI->CallOperator;
5722         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5723           DC = CRSI->TheCapturedDecl;
5724         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5725           DC = BSI->TheDecl;
5726         if (DC) {
5727           if (DC->containsDecl(TT->getDecl()))
5728             break;
5729           captureVariablyModifiedType(
5730               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5731         }
5732       }
5733     }
5734   }
5735 
5736   return new (Context)
5737       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5738 }
5739 
5740 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5741                                   ParmVarDecl *Param) {
5742   if (Param->hasUnparsedDefaultArg()) {
5743     // If we've already cleared out the location for the default argument,
5744     // that means we're parsing it right now.
5745     if (!UnparsedDefaultArgLocs.count(Param)) {
5746       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5747       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5748       Param->setInvalidDecl();
5749       return true;
5750     }
5751 
5752     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5753         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5754     Diag(UnparsedDefaultArgLocs[Param],
5755          diag::note_default_argument_declared_here);
5756     return true;
5757   }
5758 
5759   if (Param->hasUninstantiatedDefaultArg() &&
5760       InstantiateDefaultArgument(CallLoc, FD, Param))
5761     return true;
5762 
5763   assert(Param->hasInit() && "default argument but no initializer?");
5764 
5765   // If the default expression creates temporaries, we need to
5766   // push them to the current stack of expression temporaries so they'll
5767   // be properly destroyed.
5768   // FIXME: We should really be rebuilding the default argument with new
5769   // bound temporaries; see the comment in PR5810.
5770   // We don't need to do that with block decls, though, because
5771   // blocks in default argument expression can never capture anything.
5772   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5773     // Set the "needs cleanups" bit regardless of whether there are
5774     // any explicit objects.
5775     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5776 
5777     // Append all the objects to the cleanup list.  Right now, this
5778     // should always be a no-op, because blocks in default argument
5779     // expressions should never be able to capture anything.
5780     assert(!Init->getNumObjects() &&
5781            "default argument expression has capturing blocks?");
5782   }
5783 
5784   // We already type-checked the argument, so we know it works.
5785   // Just mark all of the declarations in this potentially-evaluated expression
5786   // as being "referenced".
5787   EnterExpressionEvaluationContext EvalContext(
5788       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5789   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5790                                    /*SkipLocalVariables=*/true);
5791   return false;
5792 }
5793 
5794 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5795                                         FunctionDecl *FD, ParmVarDecl *Param) {
5796   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5797   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5798     return ExprError();
5799   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5800 }
5801 
5802 Sema::VariadicCallType
5803 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5804                           Expr *Fn) {
5805   if (Proto && Proto->isVariadic()) {
5806     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5807       return VariadicConstructor;
5808     else if (Fn && Fn->getType()->isBlockPointerType())
5809       return VariadicBlock;
5810     else if (FDecl) {
5811       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5812         if (Method->isInstance())
5813           return VariadicMethod;
5814     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5815       return VariadicMethod;
5816     return VariadicFunction;
5817   }
5818   return VariadicDoesNotApply;
5819 }
5820 
5821 namespace {
5822 class FunctionCallCCC final : public FunctionCallFilterCCC {
5823 public:
5824   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5825                   unsigned NumArgs, MemberExpr *ME)
5826       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5827         FunctionName(FuncName) {}
5828 
5829   bool ValidateCandidate(const TypoCorrection &candidate) override {
5830     if (!candidate.getCorrectionSpecifier() ||
5831         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5832       return false;
5833     }
5834 
5835     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5836   }
5837 
5838   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5839     return std::make_unique<FunctionCallCCC>(*this);
5840   }
5841 
5842 private:
5843   const IdentifierInfo *const FunctionName;
5844 };
5845 }
5846 
5847 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5848                                                FunctionDecl *FDecl,
5849                                                ArrayRef<Expr *> Args) {
5850   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5851   DeclarationName FuncName = FDecl->getDeclName();
5852   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5853 
5854   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5855   if (TypoCorrection Corrected = S.CorrectTypo(
5856           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5857           S.getScopeForContext(S.CurContext), nullptr, CCC,
5858           Sema::CTK_ErrorRecovery)) {
5859     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5860       if (Corrected.isOverloaded()) {
5861         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5862         OverloadCandidateSet::iterator Best;
5863         for (NamedDecl *CD : Corrected) {
5864           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5865             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5866                                    OCS);
5867         }
5868         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5869         case OR_Success:
5870           ND = Best->FoundDecl;
5871           Corrected.setCorrectionDecl(ND);
5872           break;
5873         default:
5874           break;
5875         }
5876       }
5877       ND = ND->getUnderlyingDecl();
5878       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5879         return Corrected;
5880     }
5881   }
5882   return TypoCorrection();
5883 }
5884 
5885 /// ConvertArgumentsForCall - Converts the arguments specified in
5886 /// Args/NumArgs to the parameter types of the function FDecl with
5887 /// function prototype Proto. Call is the call expression itself, and
5888 /// Fn is the function expression. For a C++ member function, this
5889 /// routine does not attempt to convert the object argument. Returns
5890 /// true if the call is ill-formed.
5891 bool
5892 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5893                               FunctionDecl *FDecl,
5894                               const FunctionProtoType *Proto,
5895                               ArrayRef<Expr *> Args,
5896                               SourceLocation RParenLoc,
5897                               bool IsExecConfig) {
5898   // Bail out early if calling a builtin with custom typechecking.
5899   if (FDecl)
5900     if (unsigned ID = FDecl->getBuiltinID())
5901       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5902         return false;
5903 
5904   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5905   // assignment, to the types of the corresponding parameter, ...
5906   unsigned NumParams = Proto->getNumParams();
5907   bool Invalid = false;
5908   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5909   unsigned FnKind = Fn->getType()->isBlockPointerType()
5910                        ? 1 /* block */
5911                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5912                                        : 0 /* function */);
5913 
5914   // If too few arguments are available (and we don't have default
5915   // arguments for the remaining parameters), don't make the call.
5916   if (Args.size() < NumParams) {
5917     if (Args.size() < MinArgs) {
5918       TypoCorrection TC;
5919       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5920         unsigned diag_id =
5921             MinArgs == NumParams && !Proto->isVariadic()
5922                 ? diag::err_typecheck_call_too_few_args_suggest
5923                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5924         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5925                                         << static_cast<unsigned>(Args.size())
5926                                         << TC.getCorrectionRange());
5927       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5928         Diag(RParenLoc,
5929              MinArgs == NumParams && !Proto->isVariadic()
5930                  ? diag::err_typecheck_call_too_few_args_one
5931                  : diag::err_typecheck_call_too_few_args_at_least_one)
5932             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5933       else
5934         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5935                             ? diag::err_typecheck_call_too_few_args
5936                             : diag::err_typecheck_call_too_few_args_at_least)
5937             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5938             << Fn->getSourceRange();
5939 
5940       // Emit the location of the prototype.
5941       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5942         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5943 
5944       return true;
5945     }
5946     // We reserve space for the default arguments when we create
5947     // the call expression, before calling ConvertArgumentsForCall.
5948     assert((Call->getNumArgs() == NumParams) &&
5949            "We should have reserved space for the default arguments before!");
5950   }
5951 
5952   // If too many are passed and not variadic, error on the extras and drop
5953   // them.
5954   if (Args.size() > NumParams) {
5955     if (!Proto->isVariadic()) {
5956       TypoCorrection TC;
5957       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5958         unsigned diag_id =
5959             MinArgs == NumParams && !Proto->isVariadic()
5960                 ? diag::err_typecheck_call_too_many_args_suggest
5961                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5962         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5963                                         << static_cast<unsigned>(Args.size())
5964                                         << TC.getCorrectionRange());
5965       } else if (NumParams == 1 && FDecl &&
5966                  FDecl->getParamDecl(0)->getDeclName())
5967         Diag(Args[NumParams]->getBeginLoc(),
5968              MinArgs == NumParams
5969                  ? diag::err_typecheck_call_too_many_args_one
5970                  : diag::err_typecheck_call_too_many_args_at_most_one)
5971             << FnKind << FDecl->getParamDecl(0)
5972             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5973             << SourceRange(Args[NumParams]->getBeginLoc(),
5974                            Args.back()->getEndLoc());
5975       else
5976         Diag(Args[NumParams]->getBeginLoc(),
5977              MinArgs == NumParams
5978                  ? diag::err_typecheck_call_too_many_args
5979                  : diag::err_typecheck_call_too_many_args_at_most)
5980             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5981             << Fn->getSourceRange()
5982             << SourceRange(Args[NumParams]->getBeginLoc(),
5983                            Args.back()->getEndLoc());
5984 
5985       // Emit the location of the prototype.
5986       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5987         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5988 
5989       // This deletes the extra arguments.
5990       Call->shrinkNumArgs(NumParams);
5991       return true;
5992     }
5993   }
5994   SmallVector<Expr *, 8> AllArgs;
5995   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5996 
5997   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5998                                    AllArgs, CallType);
5999   if (Invalid)
6000     return true;
6001   unsigned TotalNumArgs = AllArgs.size();
6002   for (unsigned i = 0; i < TotalNumArgs; ++i)
6003     Call->setArg(i, AllArgs[i]);
6004 
6005   Call->computeDependence();
6006   return false;
6007 }
6008 
6009 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6010                                   const FunctionProtoType *Proto,
6011                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6012                                   SmallVectorImpl<Expr *> &AllArgs,
6013                                   VariadicCallType CallType, bool AllowExplicit,
6014                                   bool IsListInitialization) {
6015   unsigned NumParams = Proto->getNumParams();
6016   bool Invalid = false;
6017   size_t ArgIx = 0;
6018   // Continue to check argument types (even if we have too few/many args).
6019   for (unsigned i = FirstParam; i < NumParams; i++) {
6020     QualType ProtoArgType = Proto->getParamType(i);
6021 
6022     Expr *Arg;
6023     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6024     if (ArgIx < Args.size()) {
6025       Arg = Args[ArgIx++];
6026 
6027       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6028                               diag::err_call_incomplete_argument, Arg))
6029         return true;
6030 
6031       // Strip the unbridged-cast placeholder expression off, if applicable.
6032       bool CFAudited = false;
6033       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6034           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6035           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6036         Arg = stripARCUnbridgedCast(Arg);
6037       else if (getLangOpts().ObjCAutoRefCount &&
6038                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6039                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6040         CFAudited = true;
6041 
6042       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6043           ProtoArgType->isBlockPointerType())
6044         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6045           BE->getBlockDecl()->setDoesNotEscape();
6046 
6047       InitializedEntity Entity =
6048           Param ? InitializedEntity::InitializeParameter(Context, Param,
6049                                                          ProtoArgType)
6050                 : InitializedEntity::InitializeParameter(
6051                       Context, ProtoArgType, Proto->isParamConsumed(i));
6052 
6053       // Remember that parameter belongs to a CF audited API.
6054       if (CFAudited)
6055         Entity.setParameterCFAudited();
6056 
6057       ExprResult ArgE = PerformCopyInitialization(
6058           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6059       if (ArgE.isInvalid())
6060         return true;
6061 
6062       Arg = ArgE.getAs<Expr>();
6063     } else {
6064       assert(Param && "can't use default arguments without a known callee");
6065 
6066       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6067       if (ArgExpr.isInvalid())
6068         return true;
6069 
6070       Arg = ArgExpr.getAs<Expr>();
6071     }
6072 
6073     // Check for array bounds violations for each argument to the call. This
6074     // check only triggers warnings when the argument isn't a more complex Expr
6075     // with its own checking, such as a BinaryOperator.
6076     CheckArrayAccess(Arg);
6077 
6078     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6079     CheckStaticArrayArgument(CallLoc, Param, Arg);
6080 
6081     AllArgs.push_back(Arg);
6082   }
6083 
6084   // If this is a variadic call, handle args passed through "...".
6085   if (CallType != VariadicDoesNotApply) {
6086     // Assume that extern "C" functions with variadic arguments that
6087     // return __unknown_anytype aren't *really* variadic.
6088     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6089         FDecl->isExternC()) {
6090       for (Expr *A : Args.slice(ArgIx)) {
6091         QualType paramType; // ignored
6092         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6093         Invalid |= arg.isInvalid();
6094         AllArgs.push_back(arg.get());
6095       }
6096 
6097     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6098     } else {
6099       for (Expr *A : Args.slice(ArgIx)) {
6100         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6101         Invalid |= Arg.isInvalid();
6102         AllArgs.push_back(Arg.get());
6103       }
6104     }
6105 
6106     // Check for array bounds violations.
6107     for (Expr *A : Args.slice(ArgIx))
6108       CheckArrayAccess(A);
6109   }
6110   return Invalid;
6111 }
6112 
6113 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6114   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6115   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6116     TL = DTL.getOriginalLoc();
6117   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6118     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6119       << ATL.getLocalSourceRange();
6120 }
6121 
6122 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6123 /// array parameter, check that it is non-null, and that if it is formed by
6124 /// array-to-pointer decay, the underlying array is sufficiently large.
6125 ///
6126 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6127 /// array type derivation, then for each call to the function, the value of the
6128 /// corresponding actual argument shall provide access to the first element of
6129 /// an array with at least as many elements as specified by the size expression.
6130 void
6131 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6132                                ParmVarDecl *Param,
6133                                const Expr *ArgExpr) {
6134   // Static array parameters are not supported in C++.
6135   if (!Param || getLangOpts().CPlusPlus)
6136     return;
6137 
6138   QualType OrigTy = Param->getOriginalType();
6139 
6140   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6141   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6142     return;
6143 
6144   if (ArgExpr->isNullPointerConstant(Context,
6145                                      Expr::NPC_NeverValueDependent)) {
6146     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6147     DiagnoseCalleeStaticArrayParam(*this, Param);
6148     return;
6149   }
6150 
6151   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6152   if (!CAT)
6153     return;
6154 
6155   const ConstantArrayType *ArgCAT =
6156     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6157   if (!ArgCAT)
6158     return;
6159 
6160   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6161                                              ArgCAT->getElementType())) {
6162     if (ArgCAT->getSize().ult(CAT->getSize())) {
6163       Diag(CallLoc, diag::warn_static_array_too_small)
6164           << ArgExpr->getSourceRange()
6165           << (unsigned)ArgCAT->getSize().getZExtValue()
6166           << (unsigned)CAT->getSize().getZExtValue() << 0;
6167       DiagnoseCalleeStaticArrayParam(*this, Param);
6168     }
6169     return;
6170   }
6171 
6172   Optional<CharUnits> ArgSize =
6173       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6174   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6175   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6176     Diag(CallLoc, diag::warn_static_array_too_small)
6177         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6178         << (unsigned)ParmSize->getQuantity() << 1;
6179     DiagnoseCalleeStaticArrayParam(*this, Param);
6180   }
6181 }
6182 
6183 /// Given a function expression of unknown-any type, try to rebuild it
6184 /// to have a function type.
6185 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6186 
6187 /// Is the given type a placeholder that we need to lower out
6188 /// immediately during argument processing?
6189 static bool isPlaceholderToRemoveAsArg(QualType type) {
6190   // Placeholders are never sugared.
6191   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6192   if (!placeholder) return false;
6193 
6194   switch (placeholder->getKind()) {
6195   // Ignore all the non-placeholder types.
6196 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6197   case BuiltinType::Id:
6198 #include "clang/Basic/OpenCLImageTypes.def"
6199 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6200   case BuiltinType::Id:
6201 #include "clang/Basic/OpenCLExtensionTypes.def"
6202   // In practice we'll never use this, since all SVE types are sugared
6203   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6204 #define SVE_TYPE(Name, Id, SingletonId) \
6205   case BuiltinType::Id:
6206 #include "clang/Basic/AArch64SVEACLETypes.def"
6207 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6208   case BuiltinType::Id:
6209 #include "clang/Basic/PPCTypes.def"
6210 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6211 #include "clang/Basic/RISCVVTypes.def"
6212 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6213 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6214 #include "clang/AST/BuiltinTypes.def"
6215     return false;
6216 
6217   // We cannot lower out overload sets; they might validly be resolved
6218   // by the call machinery.
6219   case BuiltinType::Overload:
6220     return false;
6221 
6222   // Unbridged casts in ARC can be handled in some call positions and
6223   // should be left in place.
6224   case BuiltinType::ARCUnbridgedCast:
6225     return false;
6226 
6227   // Pseudo-objects should be converted as soon as possible.
6228   case BuiltinType::PseudoObject:
6229     return true;
6230 
6231   // The debugger mode could theoretically but currently does not try
6232   // to resolve unknown-typed arguments based on known parameter types.
6233   case BuiltinType::UnknownAny:
6234     return true;
6235 
6236   // These are always invalid as call arguments and should be reported.
6237   case BuiltinType::BoundMember:
6238   case BuiltinType::BuiltinFn:
6239   case BuiltinType::IncompleteMatrixIdx:
6240   case BuiltinType::OMPArraySection:
6241   case BuiltinType::OMPArrayShaping:
6242   case BuiltinType::OMPIterator:
6243     return true;
6244 
6245   }
6246   llvm_unreachable("bad builtin type kind");
6247 }
6248 
6249 /// Check an argument list for placeholders that we won't try to
6250 /// handle later.
6251 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6252   // Apply this processing to all the arguments at once instead of
6253   // dying at the first failure.
6254   bool hasInvalid = false;
6255   for (size_t i = 0, e = args.size(); i != e; i++) {
6256     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6257       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6258       if (result.isInvalid()) hasInvalid = true;
6259       else args[i] = result.get();
6260     }
6261   }
6262   return hasInvalid;
6263 }
6264 
6265 /// If a builtin function has a pointer argument with no explicit address
6266 /// space, then it should be able to accept a pointer to any address
6267 /// space as input.  In order to do this, we need to replace the
6268 /// standard builtin declaration with one that uses the same address space
6269 /// as the call.
6270 ///
6271 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6272 ///                  it does not contain any pointer arguments without
6273 ///                  an address space qualifer.  Otherwise the rewritten
6274 ///                  FunctionDecl is returned.
6275 /// TODO: Handle pointer return types.
6276 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6277                                                 FunctionDecl *FDecl,
6278                                                 MultiExprArg ArgExprs) {
6279 
6280   QualType DeclType = FDecl->getType();
6281   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6282 
6283   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6284       ArgExprs.size() < FT->getNumParams())
6285     return nullptr;
6286 
6287   bool NeedsNewDecl = false;
6288   unsigned i = 0;
6289   SmallVector<QualType, 8> OverloadParams;
6290 
6291   for (QualType ParamType : FT->param_types()) {
6292 
6293     // Convert array arguments to pointer to simplify type lookup.
6294     ExprResult ArgRes =
6295         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6296     if (ArgRes.isInvalid())
6297       return nullptr;
6298     Expr *Arg = ArgRes.get();
6299     QualType ArgType = Arg->getType();
6300     if (!ParamType->isPointerType() ||
6301         ParamType.hasAddressSpace() ||
6302         !ArgType->isPointerType() ||
6303         !ArgType->getPointeeType().hasAddressSpace()) {
6304       OverloadParams.push_back(ParamType);
6305       continue;
6306     }
6307 
6308     QualType PointeeType = ParamType->getPointeeType();
6309     if (PointeeType.hasAddressSpace())
6310       continue;
6311 
6312     NeedsNewDecl = true;
6313     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6314 
6315     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6316     OverloadParams.push_back(Context.getPointerType(PointeeType));
6317   }
6318 
6319   if (!NeedsNewDecl)
6320     return nullptr;
6321 
6322   FunctionProtoType::ExtProtoInfo EPI;
6323   EPI.Variadic = FT->isVariadic();
6324   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6325                                                 OverloadParams, EPI);
6326   DeclContext *Parent = FDecl->getParent();
6327   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6328       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6329       FDecl->getIdentifier(), OverloadTy,
6330       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6331       false,
6332       /*hasPrototype=*/true);
6333   SmallVector<ParmVarDecl*, 16> Params;
6334   FT = cast<FunctionProtoType>(OverloadTy);
6335   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6336     QualType ParamType = FT->getParamType(i);
6337     ParmVarDecl *Parm =
6338         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6339                                 SourceLocation(), nullptr, ParamType,
6340                                 /*TInfo=*/nullptr, SC_None, nullptr);
6341     Parm->setScopeInfo(0, i);
6342     Params.push_back(Parm);
6343   }
6344   OverloadDecl->setParams(Params);
6345   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6346   return OverloadDecl;
6347 }
6348 
6349 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6350                                     FunctionDecl *Callee,
6351                                     MultiExprArg ArgExprs) {
6352   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6353   // similar attributes) really don't like it when functions are called with an
6354   // invalid number of args.
6355   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6356                          /*PartialOverloading=*/false) &&
6357       !Callee->isVariadic())
6358     return;
6359   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6360     return;
6361 
6362   if (const EnableIfAttr *Attr =
6363           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6364     S.Diag(Fn->getBeginLoc(),
6365            isa<CXXMethodDecl>(Callee)
6366                ? diag::err_ovl_no_viable_member_function_in_call
6367                : diag::err_ovl_no_viable_function_in_call)
6368         << Callee << Callee->getSourceRange();
6369     S.Diag(Callee->getLocation(),
6370            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6371         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6372     return;
6373   }
6374 }
6375 
6376 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6377     const UnresolvedMemberExpr *const UME, Sema &S) {
6378 
6379   const auto GetFunctionLevelDCIfCXXClass =
6380       [](Sema &S) -> const CXXRecordDecl * {
6381     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6382     if (!DC || !DC->getParent())
6383       return nullptr;
6384 
6385     // If the call to some member function was made from within a member
6386     // function body 'M' return return 'M's parent.
6387     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6388       return MD->getParent()->getCanonicalDecl();
6389     // else the call was made from within a default member initializer of a
6390     // class, so return the class.
6391     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6392       return RD->getCanonicalDecl();
6393     return nullptr;
6394   };
6395   // If our DeclContext is neither a member function nor a class (in the
6396   // case of a lambda in a default member initializer), we can't have an
6397   // enclosing 'this'.
6398 
6399   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6400   if (!CurParentClass)
6401     return false;
6402 
6403   // The naming class for implicit member functions call is the class in which
6404   // name lookup starts.
6405   const CXXRecordDecl *const NamingClass =
6406       UME->getNamingClass()->getCanonicalDecl();
6407   assert(NamingClass && "Must have naming class even for implicit access");
6408 
6409   // If the unresolved member functions were found in a 'naming class' that is
6410   // related (either the same or derived from) to the class that contains the
6411   // member function that itself contained the implicit member access.
6412 
6413   return CurParentClass == NamingClass ||
6414          CurParentClass->isDerivedFrom(NamingClass);
6415 }
6416 
6417 static void
6418 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6419     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6420 
6421   if (!UME)
6422     return;
6423 
6424   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6425   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6426   // already been captured, or if this is an implicit member function call (if
6427   // it isn't, an attempt to capture 'this' should already have been made).
6428   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6429       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6430     return;
6431 
6432   // Check if the naming class in which the unresolved members were found is
6433   // related (same as or is a base of) to the enclosing class.
6434 
6435   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6436     return;
6437 
6438 
6439   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6440   // If the enclosing function is not dependent, then this lambda is
6441   // capture ready, so if we can capture this, do so.
6442   if (!EnclosingFunctionCtx->isDependentContext()) {
6443     // If the current lambda and all enclosing lambdas can capture 'this' -
6444     // then go ahead and capture 'this' (since our unresolved overload set
6445     // contains at least one non-static member function).
6446     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6447       S.CheckCXXThisCapture(CallLoc);
6448   } else if (S.CurContext->isDependentContext()) {
6449     // ... since this is an implicit member reference, that might potentially
6450     // involve a 'this' capture, mark 'this' for potential capture in
6451     // enclosing lambdas.
6452     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6453       CurLSI->addPotentialThisCapture(CallLoc);
6454   }
6455 }
6456 
6457 // Once a call is fully resolved, warn for unqualified calls to specific
6458 // C++ standard functions, like move and forward.
6459 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6460   // We are only checking unary move and forward so exit early here.
6461   if (Call->getNumArgs() != 1)
6462     return;
6463 
6464   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6465   if (!E || isa<UnresolvedLookupExpr>(E))
6466     return;
6467   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6468   if (!DRE || !DRE->getLocation().isValid())
6469     return;
6470 
6471   if (DRE->getQualifier())
6472     return;
6473 
6474   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6475   if (!D || !D->isInStdNamespace())
6476     return;
6477 
6478   // Only warn for some functions deemed more frequent or problematic.
6479   static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6480   auto it = llvm::find(SpecialFunctions, D->getName());
6481   if (it == std::end(SpecialFunctions))
6482     return;
6483 
6484   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6485       << D->getQualifiedNameAsString()
6486       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6487 }
6488 
6489 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6490                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6491                                Expr *ExecConfig) {
6492   ExprResult Call =
6493       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6494                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6495   if (Call.isInvalid())
6496     return Call;
6497 
6498   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6499   // language modes.
6500   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6501     if (ULE->hasExplicitTemplateArgs() &&
6502         ULE->decls_begin() == ULE->decls_end()) {
6503       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6504                                  ? diag::warn_cxx17_compat_adl_only_template_id
6505                                  : diag::ext_adl_only_template_id)
6506           << ULE->getName();
6507     }
6508   }
6509 
6510   if (LangOpts.OpenMP)
6511     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6512                            ExecConfig);
6513   if (LangOpts.CPlusPlus) {
6514     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6515     if (CE)
6516       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6517   }
6518   return Call;
6519 }
6520 
6521 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6522 /// This provides the location of the left/right parens and a list of comma
6523 /// locations.
6524 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6525                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6526                                Expr *ExecConfig, bool IsExecConfig,
6527                                bool AllowRecovery) {
6528   // Since this might be a postfix expression, get rid of ParenListExprs.
6529   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6530   if (Result.isInvalid()) return ExprError();
6531   Fn = Result.get();
6532 
6533   if (checkArgsForPlaceholders(*this, ArgExprs))
6534     return ExprError();
6535 
6536   if (getLangOpts().CPlusPlus) {
6537     // If this is a pseudo-destructor expression, build the call immediately.
6538     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6539       if (!ArgExprs.empty()) {
6540         // Pseudo-destructor calls should not have any arguments.
6541         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6542             << FixItHint::CreateRemoval(
6543                    SourceRange(ArgExprs.front()->getBeginLoc(),
6544                                ArgExprs.back()->getEndLoc()));
6545       }
6546 
6547       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6548                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6549     }
6550     if (Fn->getType() == Context.PseudoObjectTy) {
6551       ExprResult result = CheckPlaceholderExpr(Fn);
6552       if (result.isInvalid()) return ExprError();
6553       Fn = result.get();
6554     }
6555 
6556     // Determine whether this is a dependent call inside a C++ template,
6557     // in which case we won't do any semantic analysis now.
6558     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6559       if (ExecConfig) {
6560         return CUDAKernelCallExpr::Create(Context, Fn,
6561                                           cast<CallExpr>(ExecConfig), ArgExprs,
6562                                           Context.DependentTy, VK_PRValue,
6563                                           RParenLoc, CurFPFeatureOverrides());
6564       } else {
6565 
6566         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6567             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6568             Fn->getBeginLoc());
6569 
6570         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6571                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6572       }
6573     }
6574 
6575     // Determine whether this is a call to an object (C++ [over.call.object]).
6576     if (Fn->getType()->isRecordType())
6577       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6578                                           RParenLoc);
6579 
6580     if (Fn->getType() == Context.UnknownAnyTy) {
6581       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6582       if (result.isInvalid()) return ExprError();
6583       Fn = result.get();
6584     }
6585 
6586     if (Fn->getType() == Context.BoundMemberTy) {
6587       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6588                                        RParenLoc, ExecConfig, IsExecConfig,
6589                                        AllowRecovery);
6590     }
6591   }
6592 
6593   // Check for overloaded calls.  This can happen even in C due to extensions.
6594   if (Fn->getType() == Context.OverloadTy) {
6595     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6596 
6597     // We aren't supposed to apply this logic if there's an '&' involved.
6598     if (!find.HasFormOfMemberPointer) {
6599       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6600         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6601                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6602       OverloadExpr *ovl = find.Expression;
6603       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6604         return BuildOverloadedCallExpr(
6605             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6606             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6607       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6608                                        RParenLoc, ExecConfig, IsExecConfig,
6609                                        AllowRecovery);
6610     }
6611   }
6612 
6613   // If we're directly calling a function, get the appropriate declaration.
6614   if (Fn->getType() == Context.UnknownAnyTy) {
6615     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6616     if (result.isInvalid()) return ExprError();
6617     Fn = result.get();
6618   }
6619 
6620   Expr *NakedFn = Fn->IgnoreParens();
6621 
6622   bool CallingNDeclIndirectly = false;
6623   NamedDecl *NDecl = nullptr;
6624   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6625     if (UnOp->getOpcode() == UO_AddrOf) {
6626       CallingNDeclIndirectly = true;
6627       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6628     }
6629   }
6630 
6631   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6632     NDecl = DRE->getDecl();
6633 
6634     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6635     if (FDecl && FDecl->getBuiltinID()) {
6636       // Rewrite the function decl for this builtin by replacing parameters
6637       // with no explicit address space with the address space of the arguments
6638       // in ArgExprs.
6639       if ((FDecl =
6640                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6641         NDecl = FDecl;
6642         Fn = DeclRefExpr::Create(
6643             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6644             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6645             nullptr, DRE->isNonOdrUse());
6646       }
6647     }
6648   } else if (isa<MemberExpr>(NakedFn))
6649     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6650 
6651   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6652     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6653                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6654       return ExprError();
6655 
6656     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6657 
6658     // If this expression is a call to a builtin function in HIP device
6659     // compilation, allow a pointer-type argument to default address space to be
6660     // passed as a pointer-type parameter to a non-default address space.
6661     // If Arg is declared in the default address space and Param is declared
6662     // in a non-default address space, perform an implicit address space cast to
6663     // the parameter type.
6664     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6665         FD->getBuiltinID()) {
6666       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6667         ParmVarDecl *Param = FD->getParamDecl(Idx);
6668         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6669             !ArgExprs[Idx]->getType()->isPointerType())
6670           continue;
6671 
6672         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6673         auto ArgTy = ArgExprs[Idx]->getType();
6674         auto ArgPtTy = ArgTy->getPointeeType();
6675         auto ArgAS = ArgPtTy.getAddressSpace();
6676 
6677         // Add address space cast if target address spaces are different
6678         bool NeedImplicitASC =
6679           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6680           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6681                                               // or from specific AS which has target AS matching that of Param.
6682           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6683         if (!NeedImplicitASC)
6684           continue;
6685 
6686         // First, ensure that the Arg is an RValue.
6687         if (ArgExprs[Idx]->isGLValue()) {
6688           ArgExprs[Idx] = ImplicitCastExpr::Create(
6689               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6690               nullptr, VK_PRValue, FPOptionsOverride());
6691         }
6692 
6693         // Construct a new arg type with address space of Param
6694         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6695         ArgPtQuals.setAddressSpace(ParamAS);
6696         auto NewArgPtTy =
6697             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6698         auto NewArgTy =
6699             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6700                                      ArgTy.getQualifiers());
6701 
6702         // Finally perform an implicit address space cast
6703         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6704                                           CK_AddressSpaceConversion)
6705                             .get();
6706       }
6707     }
6708   }
6709 
6710   if (Context.isDependenceAllowed() &&
6711       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6712     assert(!getLangOpts().CPlusPlus);
6713     assert((Fn->containsErrors() ||
6714             llvm::any_of(ArgExprs,
6715                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6716            "should only occur in error-recovery path.");
6717     QualType ReturnType =
6718         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6719             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6720             : Context.DependentTy;
6721     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6722                             Expr::getValueKindForType(ReturnType), RParenLoc,
6723                             CurFPFeatureOverrides());
6724   }
6725   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6726                                ExecConfig, IsExecConfig);
6727 }
6728 
6729 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6730 //  with the specified CallArgs
6731 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6732                                  MultiExprArg CallArgs) {
6733   StringRef Name = Context.BuiltinInfo.getName(Id);
6734   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6735                  Sema::LookupOrdinaryName);
6736   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6737 
6738   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6739   assert(BuiltInDecl && "failed to find builtin declaration");
6740 
6741   ExprResult DeclRef =
6742       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6743   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6744 
6745   ExprResult Call =
6746       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6747 
6748   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6749   return Call.get();
6750 }
6751 
6752 /// Parse a __builtin_astype expression.
6753 ///
6754 /// __builtin_astype( value, dst type )
6755 ///
6756 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6757                                  SourceLocation BuiltinLoc,
6758                                  SourceLocation RParenLoc) {
6759   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6760   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6761 }
6762 
6763 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6764 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6765                                  SourceLocation BuiltinLoc,
6766                                  SourceLocation RParenLoc) {
6767   ExprValueKind VK = VK_PRValue;
6768   ExprObjectKind OK = OK_Ordinary;
6769   QualType SrcTy = E->getType();
6770   if (!SrcTy->isDependentType() &&
6771       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6772     return ExprError(
6773         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6774         << DestTy << SrcTy << E->getSourceRange());
6775   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6776 }
6777 
6778 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6779 /// provided arguments.
6780 ///
6781 /// __builtin_convertvector( value, dst type )
6782 ///
6783 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6784                                         SourceLocation BuiltinLoc,
6785                                         SourceLocation RParenLoc) {
6786   TypeSourceInfo *TInfo;
6787   GetTypeFromParser(ParsedDestTy, &TInfo);
6788   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6789 }
6790 
6791 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6792 /// i.e. an expression not of \p OverloadTy.  The expression should
6793 /// unary-convert to an expression of function-pointer or
6794 /// block-pointer type.
6795 ///
6796 /// \param NDecl the declaration being called, if available
6797 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6798                                        SourceLocation LParenLoc,
6799                                        ArrayRef<Expr *> Args,
6800                                        SourceLocation RParenLoc, Expr *Config,
6801                                        bool IsExecConfig, ADLCallKind UsesADL) {
6802   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6803   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6804 
6805   // Functions with 'interrupt' attribute cannot be called directly.
6806   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6807     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6808     return ExprError();
6809   }
6810 
6811   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6812   // so there's some risk when calling out to non-interrupt handler functions
6813   // that the callee might not preserve them. This is easy to diagnose here,
6814   // but can be very challenging to debug.
6815   // Likewise, X86 interrupt handlers may only call routines with attribute
6816   // no_caller_saved_registers since there is no efficient way to
6817   // save and restore the non-GPR state.
6818   if (auto *Caller = getCurFunctionDecl()) {
6819     if (Caller->hasAttr<ARMInterruptAttr>()) {
6820       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6821       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6822         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6823         if (FDecl)
6824           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6825       }
6826     }
6827     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6828         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6829       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6830       if (FDecl)
6831         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6832     }
6833   }
6834 
6835   // Promote the function operand.
6836   // We special-case function promotion here because we only allow promoting
6837   // builtin functions to function pointers in the callee of a call.
6838   ExprResult Result;
6839   QualType ResultTy;
6840   if (BuiltinID &&
6841       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6842     // Extract the return type from the (builtin) function pointer type.
6843     // FIXME Several builtins still have setType in
6844     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6845     // Builtins.def to ensure they are correct before removing setType calls.
6846     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6847     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6848     ResultTy = FDecl->getCallResultType();
6849   } else {
6850     Result = CallExprUnaryConversions(Fn);
6851     ResultTy = Context.BoolTy;
6852   }
6853   if (Result.isInvalid())
6854     return ExprError();
6855   Fn = Result.get();
6856 
6857   // Check for a valid function type, but only if it is not a builtin which
6858   // requires custom type checking. These will be handled by
6859   // CheckBuiltinFunctionCall below just after creation of the call expression.
6860   const FunctionType *FuncT = nullptr;
6861   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6862   retry:
6863     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6864       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6865       // have type pointer to function".
6866       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6867       if (!FuncT)
6868         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6869                          << Fn->getType() << Fn->getSourceRange());
6870     } else if (const BlockPointerType *BPT =
6871                    Fn->getType()->getAs<BlockPointerType>()) {
6872       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6873     } else {
6874       // Handle calls to expressions of unknown-any type.
6875       if (Fn->getType() == Context.UnknownAnyTy) {
6876         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6877         if (rewrite.isInvalid())
6878           return ExprError();
6879         Fn = rewrite.get();
6880         goto retry;
6881       }
6882 
6883       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6884                        << Fn->getType() << Fn->getSourceRange());
6885     }
6886   }
6887 
6888   // Get the number of parameters in the function prototype, if any.
6889   // We will allocate space for max(Args.size(), NumParams) arguments
6890   // in the call expression.
6891   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6892   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6893 
6894   CallExpr *TheCall;
6895   if (Config) {
6896     assert(UsesADL == ADLCallKind::NotADL &&
6897            "CUDAKernelCallExpr should not use ADL");
6898     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6899                                          Args, ResultTy, VK_PRValue, RParenLoc,
6900                                          CurFPFeatureOverrides(), NumParams);
6901   } else {
6902     TheCall =
6903         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6904                          CurFPFeatureOverrides(), NumParams, UsesADL);
6905   }
6906 
6907   if (!Context.isDependenceAllowed()) {
6908     // Forget about the nulled arguments since typo correction
6909     // do not handle them well.
6910     TheCall->shrinkNumArgs(Args.size());
6911     // C cannot always handle TypoExpr nodes in builtin calls and direct
6912     // function calls as their argument checking don't necessarily handle
6913     // dependent types properly, so make sure any TypoExprs have been
6914     // dealt with.
6915     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6916     if (!Result.isUsable()) return ExprError();
6917     CallExpr *TheOldCall = TheCall;
6918     TheCall = dyn_cast<CallExpr>(Result.get());
6919     bool CorrectedTypos = TheCall != TheOldCall;
6920     if (!TheCall) return Result;
6921     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6922 
6923     // A new call expression node was created if some typos were corrected.
6924     // However it may not have been constructed with enough storage. In this
6925     // case, rebuild the node with enough storage. The waste of space is
6926     // immaterial since this only happens when some typos were corrected.
6927     if (CorrectedTypos && Args.size() < NumParams) {
6928       if (Config)
6929         TheCall = CUDAKernelCallExpr::Create(
6930             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6931             RParenLoc, CurFPFeatureOverrides(), NumParams);
6932       else
6933         TheCall =
6934             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6935                              CurFPFeatureOverrides(), NumParams, UsesADL);
6936     }
6937     // We can now handle the nulled arguments for the default arguments.
6938     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6939   }
6940 
6941   // Bail out early if calling a builtin with custom type checking.
6942   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6943     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6944 
6945   if (getLangOpts().CUDA) {
6946     if (Config) {
6947       // CUDA: Kernel calls must be to global functions
6948       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6949         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6950             << FDecl << Fn->getSourceRange());
6951 
6952       // CUDA: Kernel function must have 'void' return type
6953       if (!FuncT->getReturnType()->isVoidType() &&
6954           !FuncT->getReturnType()->getAs<AutoType>() &&
6955           !FuncT->getReturnType()->isInstantiationDependentType())
6956         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6957             << Fn->getType() << Fn->getSourceRange());
6958     } else {
6959       // CUDA: Calls to global functions must be configured
6960       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6961         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6962             << FDecl << Fn->getSourceRange());
6963     }
6964   }
6965 
6966   // Check for a valid return type
6967   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6968                           FDecl))
6969     return ExprError();
6970 
6971   // We know the result type of the call, set it.
6972   TheCall->setType(FuncT->getCallResultType(Context));
6973   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6974 
6975   if (Proto) {
6976     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6977                                 IsExecConfig))
6978       return ExprError();
6979   } else {
6980     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6981 
6982     if (FDecl) {
6983       // Check if we have too few/too many template arguments, based
6984       // on our knowledge of the function definition.
6985       const FunctionDecl *Def = nullptr;
6986       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6987         Proto = Def->getType()->getAs<FunctionProtoType>();
6988        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6989           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6990           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6991       }
6992 
6993       // If the function we're calling isn't a function prototype, but we have
6994       // a function prototype from a prior declaratiom, use that prototype.
6995       if (!FDecl->hasPrototype())
6996         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6997     }
6998 
6999     // Promote the arguments (C99 6.5.2.2p6).
7000     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7001       Expr *Arg = Args[i];
7002 
7003       if (Proto && i < Proto->getNumParams()) {
7004         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7005             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7006         ExprResult ArgE =
7007             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7008         if (ArgE.isInvalid())
7009           return true;
7010 
7011         Arg = ArgE.getAs<Expr>();
7012 
7013       } else {
7014         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7015 
7016         if (ArgE.isInvalid())
7017           return true;
7018 
7019         Arg = ArgE.getAs<Expr>();
7020       }
7021 
7022       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7023                               diag::err_call_incomplete_argument, Arg))
7024         return ExprError();
7025 
7026       TheCall->setArg(i, Arg);
7027     }
7028     TheCall->computeDependence();
7029   }
7030 
7031   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7032     if (!Method->isStatic())
7033       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7034         << Fn->getSourceRange());
7035 
7036   // Check for sentinels
7037   if (NDecl)
7038     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7039 
7040   // Warn for unions passing across security boundary (CMSE).
7041   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7042     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7043       if (const auto *RT =
7044               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7045         if (RT->getDecl()->isOrContainsUnion())
7046           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7047               << 0 << i;
7048       }
7049     }
7050   }
7051 
7052   // Do special checking on direct calls to functions.
7053   if (FDecl) {
7054     if (CheckFunctionCall(FDecl, TheCall, Proto))
7055       return ExprError();
7056 
7057     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7058 
7059     if (BuiltinID)
7060       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7061   } else if (NDecl) {
7062     if (CheckPointerCall(NDecl, TheCall, Proto))
7063       return ExprError();
7064   } else {
7065     if (CheckOtherCall(TheCall, Proto))
7066       return ExprError();
7067   }
7068 
7069   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7070 }
7071 
7072 ExprResult
7073 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7074                            SourceLocation RParenLoc, Expr *InitExpr) {
7075   assert(Ty && "ActOnCompoundLiteral(): missing type");
7076   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7077 
7078   TypeSourceInfo *TInfo;
7079   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7080   if (!TInfo)
7081     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7082 
7083   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7084 }
7085 
7086 ExprResult
7087 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7088                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7089   QualType literalType = TInfo->getType();
7090 
7091   if (literalType->isArrayType()) {
7092     if (RequireCompleteSizedType(
7093             LParenLoc, Context.getBaseElementType(literalType),
7094             diag::err_array_incomplete_or_sizeless_type,
7095             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7096       return ExprError();
7097     if (literalType->isVariableArrayType()) {
7098       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7099                                            diag::err_variable_object_no_init)) {
7100         return ExprError();
7101       }
7102     }
7103   } else if (!literalType->isDependentType() &&
7104              RequireCompleteType(LParenLoc, literalType,
7105                diag::err_typecheck_decl_incomplete_type,
7106                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7107     return ExprError();
7108 
7109   InitializedEntity Entity
7110     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7111   InitializationKind Kind
7112     = InitializationKind::CreateCStyleCast(LParenLoc,
7113                                            SourceRange(LParenLoc, RParenLoc),
7114                                            /*InitList=*/true);
7115   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7116   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7117                                       &literalType);
7118   if (Result.isInvalid())
7119     return ExprError();
7120   LiteralExpr = Result.get();
7121 
7122   bool isFileScope = !CurContext->isFunctionOrMethod();
7123 
7124   // In C, compound literals are l-values for some reason.
7125   // For GCC compatibility, in C++, file-scope array compound literals with
7126   // constant initializers are also l-values, and compound literals are
7127   // otherwise prvalues.
7128   //
7129   // (GCC also treats C++ list-initialized file-scope array prvalues with
7130   // constant initializers as l-values, but that's non-conforming, so we don't
7131   // follow it there.)
7132   //
7133   // FIXME: It would be better to handle the lvalue cases as materializing and
7134   // lifetime-extending a temporary object, but our materialized temporaries
7135   // representation only supports lifetime extension from a variable, not "out
7136   // of thin air".
7137   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7138   // is bound to the result of applying array-to-pointer decay to the compound
7139   // literal.
7140   // FIXME: GCC supports compound literals of reference type, which should
7141   // obviously have a value kind derived from the kind of reference involved.
7142   ExprValueKind VK =
7143       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7144           ? VK_PRValue
7145           : VK_LValue;
7146 
7147   if (isFileScope)
7148     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7149       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7150         Expr *Init = ILE->getInit(i);
7151         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7152       }
7153 
7154   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7155                                               VK, LiteralExpr, isFileScope);
7156   if (isFileScope) {
7157     if (!LiteralExpr->isTypeDependent() &&
7158         !LiteralExpr->isValueDependent() &&
7159         !literalType->isDependentType()) // C99 6.5.2.5p3
7160       if (CheckForConstantInitializer(LiteralExpr, literalType))
7161         return ExprError();
7162   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7163              literalType.getAddressSpace() != LangAS::Default) {
7164     // Embedded-C extensions to C99 6.5.2.5:
7165     //   "If the compound literal occurs inside the body of a function, the
7166     //   type name shall not be qualified by an address-space qualifier."
7167     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7168       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7169     return ExprError();
7170   }
7171 
7172   if (!isFileScope && !getLangOpts().CPlusPlus) {
7173     // Compound literals that have automatic storage duration are destroyed at
7174     // the end of the scope in C; in C++, they're just temporaries.
7175 
7176     // Emit diagnostics if it is or contains a C union type that is non-trivial
7177     // to destruct.
7178     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7179       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7180                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7181 
7182     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7183     if (literalType.isDestructedType()) {
7184       Cleanup.setExprNeedsCleanups(true);
7185       ExprCleanupObjects.push_back(E);
7186       getCurFunction()->setHasBranchProtectedScope();
7187     }
7188   }
7189 
7190   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7191       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7192     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7193                                        E->getInitializer()->getExprLoc());
7194 
7195   return MaybeBindToTemporary(E);
7196 }
7197 
7198 ExprResult
7199 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7200                     SourceLocation RBraceLoc) {
7201   // Only produce each kind of designated initialization diagnostic once.
7202   SourceLocation FirstDesignator;
7203   bool DiagnosedArrayDesignator = false;
7204   bool DiagnosedNestedDesignator = false;
7205   bool DiagnosedMixedDesignator = false;
7206 
7207   // Check that any designated initializers are syntactically valid in the
7208   // current language mode.
7209   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7210     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7211       if (FirstDesignator.isInvalid())
7212         FirstDesignator = DIE->getBeginLoc();
7213 
7214       if (!getLangOpts().CPlusPlus)
7215         break;
7216 
7217       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7218         DiagnosedNestedDesignator = true;
7219         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7220           << DIE->getDesignatorsSourceRange();
7221       }
7222 
7223       for (auto &Desig : DIE->designators()) {
7224         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7225           DiagnosedArrayDesignator = true;
7226           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7227             << Desig.getSourceRange();
7228         }
7229       }
7230 
7231       if (!DiagnosedMixedDesignator &&
7232           !isa<DesignatedInitExpr>(InitArgList[0])) {
7233         DiagnosedMixedDesignator = true;
7234         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7235           << DIE->getSourceRange();
7236         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7237           << InitArgList[0]->getSourceRange();
7238       }
7239     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7240                isa<DesignatedInitExpr>(InitArgList[0])) {
7241       DiagnosedMixedDesignator = true;
7242       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7243       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7244         << DIE->getSourceRange();
7245       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7246         << InitArgList[I]->getSourceRange();
7247     }
7248   }
7249 
7250   if (FirstDesignator.isValid()) {
7251     // Only diagnose designated initiaization as a C++20 extension if we didn't
7252     // already diagnose use of (non-C++20) C99 designator syntax.
7253     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7254         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7255       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7256                                 ? diag::warn_cxx17_compat_designated_init
7257                                 : diag::ext_cxx_designated_init);
7258     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7259       Diag(FirstDesignator, diag::ext_designated_init);
7260     }
7261   }
7262 
7263   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7264 }
7265 
7266 ExprResult
7267 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7268                     SourceLocation RBraceLoc) {
7269   // Semantic analysis for initializers is done by ActOnDeclarator() and
7270   // CheckInitializer() - it requires knowledge of the object being initialized.
7271 
7272   // Immediately handle non-overload placeholders.  Overloads can be
7273   // resolved contextually, but everything else here can't.
7274   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7275     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7276       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7277 
7278       // Ignore failures; dropping the entire initializer list because
7279       // of one failure would be terrible for indexing/etc.
7280       if (result.isInvalid()) continue;
7281 
7282       InitArgList[I] = result.get();
7283     }
7284   }
7285 
7286   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7287                                                RBraceLoc);
7288   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7289   return E;
7290 }
7291 
7292 /// Do an explicit extend of the given block pointer if we're in ARC.
7293 void Sema::maybeExtendBlockObject(ExprResult &E) {
7294   assert(E.get()->getType()->isBlockPointerType());
7295   assert(E.get()->isPRValue());
7296 
7297   // Only do this in an r-value context.
7298   if (!getLangOpts().ObjCAutoRefCount) return;
7299 
7300   E = ImplicitCastExpr::Create(
7301       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7302       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7303   Cleanup.setExprNeedsCleanups(true);
7304 }
7305 
7306 /// Prepare a conversion of the given expression to an ObjC object
7307 /// pointer type.
7308 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7309   QualType type = E.get()->getType();
7310   if (type->isObjCObjectPointerType()) {
7311     return CK_BitCast;
7312   } else if (type->isBlockPointerType()) {
7313     maybeExtendBlockObject(E);
7314     return CK_BlockPointerToObjCPointerCast;
7315   } else {
7316     assert(type->isPointerType());
7317     return CK_CPointerToObjCPointerCast;
7318   }
7319 }
7320 
7321 /// Prepares for a scalar cast, performing all the necessary stages
7322 /// except the final cast and returning the kind required.
7323 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7324   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7325   // Also, callers should have filtered out the invalid cases with
7326   // pointers.  Everything else should be possible.
7327 
7328   QualType SrcTy = Src.get()->getType();
7329   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7330     return CK_NoOp;
7331 
7332   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7333   case Type::STK_MemberPointer:
7334     llvm_unreachable("member pointer type in C");
7335 
7336   case Type::STK_CPointer:
7337   case Type::STK_BlockPointer:
7338   case Type::STK_ObjCObjectPointer:
7339     switch (DestTy->getScalarTypeKind()) {
7340     case Type::STK_CPointer: {
7341       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7342       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7343       if (SrcAS != DestAS)
7344         return CK_AddressSpaceConversion;
7345       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7346         return CK_NoOp;
7347       return CK_BitCast;
7348     }
7349     case Type::STK_BlockPointer:
7350       return (SrcKind == Type::STK_BlockPointer
7351                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7352     case Type::STK_ObjCObjectPointer:
7353       if (SrcKind == Type::STK_ObjCObjectPointer)
7354         return CK_BitCast;
7355       if (SrcKind == Type::STK_CPointer)
7356         return CK_CPointerToObjCPointerCast;
7357       maybeExtendBlockObject(Src);
7358       return CK_BlockPointerToObjCPointerCast;
7359     case Type::STK_Bool:
7360       return CK_PointerToBoolean;
7361     case Type::STK_Integral:
7362       return CK_PointerToIntegral;
7363     case Type::STK_Floating:
7364     case Type::STK_FloatingComplex:
7365     case Type::STK_IntegralComplex:
7366     case Type::STK_MemberPointer:
7367     case Type::STK_FixedPoint:
7368       llvm_unreachable("illegal cast from pointer");
7369     }
7370     llvm_unreachable("Should have returned before this");
7371 
7372   case Type::STK_FixedPoint:
7373     switch (DestTy->getScalarTypeKind()) {
7374     case Type::STK_FixedPoint:
7375       return CK_FixedPointCast;
7376     case Type::STK_Bool:
7377       return CK_FixedPointToBoolean;
7378     case Type::STK_Integral:
7379       return CK_FixedPointToIntegral;
7380     case Type::STK_Floating:
7381       return CK_FixedPointToFloating;
7382     case Type::STK_IntegralComplex:
7383     case Type::STK_FloatingComplex:
7384       Diag(Src.get()->getExprLoc(),
7385            diag::err_unimplemented_conversion_with_fixed_point_type)
7386           << DestTy;
7387       return CK_IntegralCast;
7388     case Type::STK_CPointer:
7389     case Type::STK_ObjCObjectPointer:
7390     case Type::STK_BlockPointer:
7391     case Type::STK_MemberPointer:
7392       llvm_unreachable("illegal cast to pointer type");
7393     }
7394     llvm_unreachable("Should have returned before this");
7395 
7396   case Type::STK_Bool: // casting from bool is like casting from an integer
7397   case Type::STK_Integral:
7398     switch (DestTy->getScalarTypeKind()) {
7399     case Type::STK_CPointer:
7400     case Type::STK_ObjCObjectPointer:
7401     case Type::STK_BlockPointer:
7402       if (Src.get()->isNullPointerConstant(Context,
7403                                            Expr::NPC_ValueDependentIsNull))
7404         return CK_NullToPointer;
7405       return CK_IntegralToPointer;
7406     case Type::STK_Bool:
7407       return CK_IntegralToBoolean;
7408     case Type::STK_Integral:
7409       return CK_IntegralCast;
7410     case Type::STK_Floating:
7411       return CK_IntegralToFloating;
7412     case Type::STK_IntegralComplex:
7413       Src = ImpCastExprToType(Src.get(),
7414                       DestTy->castAs<ComplexType>()->getElementType(),
7415                       CK_IntegralCast);
7416       return CK_IntegralRealToComplex;
7417     case Type::STK_FloatingComplex:
7418       Src = ImpCastExprToType(Src.get(),
7419                       DestTy->castAs<ComplexType>()->getElementType(),
7420                       CK_IntegralToFloating);
7421       return CK_FloatingRealToComplex;
7422     case Type::STK_MemberPointer:
7423       llvm_unreachable("member pointer type in C");
7424     case Type::STK_FixedPoint:
7425       return CK_IntegralToFixedPoint;
7426     }
7427     llvm_unreachable("Should have returned before this");
7428 
7429   case Type::STK_Floating:
7430     switch (DestTy->getScalarTypeKind()) {
7431     case Type::STK_Floating:
7432       return CK_FloatingCast;
7433     case Type::STK_Bool:
7434       return CK_FloatingToBoolean;
7435     case Type::STK_Integral:
7436       return CK_FloatingToIntegral;
7437     case Type::STK_FloatingComplex:
7438       Src = ImpCastExprToType(Src.get(),
7439                               DestTy->castAs<ComplexType>()->getElementType(),
7440                               CK_FloatingCast);
7441       return CK_FloatingRealToComplex;
7442     case Type::STK_IntegralComplex:
7443       Src = ImpCastExprToType(Src.get(),
7444                               DestTy->castAs<ComplexType>()->getElementType(),
7445                               CK_FloatingToIntegral);
7446       return CK_IntegralRealToComplex;
7447     case Type::STK_CPointer:
7448     case Type::STK_ObjCObjectPointer:
7449     case Type::STK_BlockPointer:
7450       llvm_unreachable("valid float->pointer cast?");
7451     case Type::STK_MemberPointer:
7452       llvm_unreachable("member pointer type in C");
7453     case Type::STK_FixedPoint:
7454       return CK_FloatingToFixedPoint;
7455     }
7456     llvm_unreachable("Should have returned before this");
7457 
7458   case Type::STK_FloatingComplex:
7459     switch (DestTy->getScalarTypeKind()) {
7460     case Type::STK_FloatingComplex:
7461       return CK_FloatingComplexCast;
7462     case Type::STK_IntegralComplex:
7463       return CK_FloatingComplexToIntegralComplex;
7464     case Type::STK_Floating: {
7465       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7466       if (Context.hasSameType(ET, DestTy))
7467         return CK_FloatingComplexToReal;
7468       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7469       return CK_FloatingCast;
7470     }
7471     case Type::STK_Bool:
7472       return CK_FloatingComplexToBoolean;
7473     case Type::STK_Integral:
7474       Src = ImpCastExprToType(Src.get(),
7475                               SrcTy->castAs<ComplexType>()->getElementType(),
7476                               CK_FloatingComplexToReal);
7477       return CK_FloatingToIntegral;
7478     case Type::STK_CPointer:
7479     case Type::STK_ObjCObjectPointer:
7480     case Type::STK_BlockPointer:
7481       llvm_unreachable("valid complex float->pointer cast?");
7482     case Type::STK_MemberPointer:
7483       llvm_unreachable("member pointer type in C");
7484     case Type::STK_FixedPoint:
7485       Diag(Src.get()->getExprLoc(),
7486            diag::err_unimplemented_conversion_with_fixed_point_type)
7487           << SrcTy;
7488       return CK_IntegralCast;
7489     }
7490     llvm_unreachable("Should have returned before this");
7491 
7492   case Type::STK_IntegralComplex:
7493     switch (DestTy->getScalarTypeKind()) {
7494     case Type::STK_FloatingComplex:
7495       return CK_IntegralComplexToFloatingComplex;
7496     case Type::STK_IntegralComplex:
7497       return CK_IntegralComplexCast;
7498     case Type::STK_Integral: {
7499       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7500       if (Context.hasSameType(ET, DestTy))
7501         return CK_IntegralComplexToReal;
7502       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7503       return CK_IntegralCast;
7504     }
7505     case Type::STK_Bool:
7506       return CK_IntegralComplexToBoolean;
7507     case Type::STK_Floating:
7508       Src = ImpCastExprToType(Src.get(),
7509                               SrcTy->castAs<ComplexType>()->getElementType(),
7510                               CK_IntegralComplexToReal);
7511       return CK_IntegralToFloating;
7512     case Type::STK_CPointer:
7513     case Type::STK_ObjCObjectPointer:
7514     case Type::STK_BlockPointer:
7515       llvm_unreachable("valid complex int->pointer cast?");
7516     case Type::STK_MemberPointer:
7517       llvm_unreachable("member pointer type in C");
7518     case Type::STK_FixedPoint:
7519       Diag(Src.get()->getExprLoc(),
7520            diag::err_unimplemented_conversion_with_fixed_point_type)
7521           << SrcTy;
7522       return CK_IntegralCast;
7523     }
7524     llvm_unreachable("Should have returned before this");
7525   }
7526 
7527   llvm_unreachable("Unhandled scalar cast");
7528 }
7529 
7530 static bool breakDownVectorType(QualType type, uint64_t &len,
7531                                 QualType &eltType) {
7532   // Vectors are simple.
7533   if (const VectorType *vecType = type->getAs<VectorType>()) {
7534     len = vecType->getNumElements();
7535     eltType = vecType->getElementType();
7536     assert(eltType->isScalarType());
7537     return true;
7538   }
7539 
7540   // We allow lax conversion to and from non-vector types, but only if
7541   // they're real types (i.e. non-complex, non-pointer scalar types).
7542   if (!type->isRealType()) return false;
7543 
7544   len = 1;
7545   eltType = type;
7546   return true;
7547 }
7548 
7549 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7550 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7551 /// allowed?
7552 ///
7553 /// This will also return false if the two given types do not make sense from
7554 /// the perspective of SVE bitcasts.
7555 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7556   assert(srcTy->isVectorType() || destTy->isVectorType());
7557 
7558   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7559     if (!FirstType->isSizelessBuiltinType())
7560       return false;
7561 
7562     const auto *VecTy = SecondType->getAs<VectorType>();
7563     return VecTy &&
7564            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7565   };
7566 
7567   return ValidScalableConversion(srcTy, destTy) ||
7568          ValidScalableConversion(destTy, srcTy);
7569 }
7570 
7571 /// Are the two types matrix types and do they have the same dimensions i.e.
7572 /// do they have the same number of rows and the same number of columns?
7573 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7574   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7575     return false;
7576 
7577   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7578   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7579 
7580   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7581          matSrcType->getNumColumns() == matDestType->getNumColumns();
7582 }
7583 
7584 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7585   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7586 
7587   uint64_t SrcLen, DestLen;
7588   QualType SrcEltTy, DestEltTy;
7589   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7590     return false;
7591   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7592     return false;
7593 
7594   // ASTContext::getTypeSize will return the size rounded up to a
7595   // power of 2, so instead of using that, we need to use the raw
7596   // element size multiplied by the element count.
7597   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7598   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7599 
7600   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7601 }
7602 
7603 /// Are the two types lax-compatible vector types?  That is, given
7604 /// that one of them is a vector, do they have equal storage sizes,
7605 /// where the storage size is the number of elements times the element
7606 /// size?
7607 ///
7608 /// This will also return false if either of the types is neither a
7609 /// vector nor a real type.
7610 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7611   assert(destTy->isVectorType() || srcTy->isVectorType());
7612 
7613   // Disallow lax conversions between scalars and ExtVectors (these
7614   // conversions are allowed for other vector types because common headers
7615   // depend on them).  Most scalar OP ExtVector cases are handled by the
7616   // splat path anyway, which does what we want (convert, not bitcast).
7617   // What this rules out for ExtVectors is crazy things like char4*float.
7618   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7619   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7620 
7621   return areVectorTypesSameSize(srcTy, destTy);
7622 }
7623 
7624 /// Is this a legal conversion between two types, one of which is
7625 /// known to be a vector type?
7626 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7627   assert(destTy->isVectorType() || srcTy->isVectorType());
7628 
7629   switch (Context.getLangOpts().getLaxVectorConversions()) {
7630   case LangOptions::LaxVectorConversionKind::None:
7631     return false;
7632 
7633   case LangOptions::LaxVectorConversionKind::Integer:
7634     if (!srcTy->isIntegralOrEnumerationType()) {
7635       auto *Vec = srcTy->getAs<VectorType>();
7636       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7637         return false;
7638     }
7639     if (!destTy->isIntegralOrEnumerationType()) {
7640       auto *Vec = destTy->getAs<VectorType>();
7641       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7642         return false;
7643     }
7644     // OK, integer (vector) -> integer (vector) bitcast.
7645     break;
7646 
7647     case LangOptions::LaxVectorConversionKind::All:
7648     break;
7649   }
7650 
7651   return areLaxCompatibleVectorTypes(srcTy, destTy);
7652 }
7653 
7654 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7655                            CastKind &Kind) {
7656   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7657     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7658       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7659              << DestTy << SrcTy << R;
7660     }
7661   } else if (SrcTy->isMatrixType()) {
7662     return Diag(R.getBegin(),
7663                 diag::err_invalid_conversion_between_matrix_and_type)
7664            << SrcTy << DestTy << R;
7665   } else if (DestTy->isMatrixType()) {
7666     return Diag(R.getBegin(),
7667                 diag::err_invalid_conversion_between_matrix_and_type)
7668            << DestTy << SrcTy << R;
7669   }
7670 
7671   Kind = CK_MatrixCast;
7672   return false;
7673 }
7674 
7675 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7676                            CastKind &Kind) {
7677   assert(VectorTy->isVectorType() && "Not a vector type!");
7678 
7679   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7680     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7681       return Diag(R.getBegin(),
7682                   Ty->isVectorType() ?
7683                   diag::err_invalid_conversion_between_vectors :
7684                   diag::err_invalid_conversion_between_vector_and_integer)
7685         << VectorTy << Ty << R;
7686   } else
7687     return Diag(R.getBegin(),
7688                 diag::err_invalid_conversion_between_vector_and_scalar)
7689       << VectorTy << Ty << R;
7690 
7691   Kind = CK_BitCast;
7692   return false;
7693 }
7694 
7695 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7696   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7697 
7698   if (DestElemTy == SplattedExpr->getType())
7699     return SplattedExpr;
7700 
7701   assert(DestElemTy->isFloatingType() ||
7702          DestElemTy->isIntegralOrEnumerationType());
7703 
7704   CastKind CK;
7705   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7706     // OpenCL requires that we convert `true` boolean expressions to -1, but
7707     // only when splatting vectors.
7708     if (DestElemTy->isFloatingType()) {
7709       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7710       // in two steps: boolean to signed integral, then to floating.
7711       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7712                                                  CK_BooleanToSignedIntegral);
7713       SplattedExpr = CastExprRes.get();
7714       CK = CK_IntegralToFloating;
7715     } else {
7716       CK = CK_BooleanToSignedIntegral;
7717     }
7718   } else {
7719     ExprResult CastExprRes = SplattedExpr;
7720     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7721     if (CastExprRes.isInvalid())
7722       return ExprError();
7723     SplattedExpr = CastExprRes.get();
7724   }
7725   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7726 }
7727 
7728 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7729                                     Expr *CastExpr, CastKind &Kind) {
7730   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7731 
7732   QualType SrcTy = CastExpr->getType();
7733 
7734   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7735   // an ExtVectorType.
7736   // In OpenCL, casts between vectors of different types are not allowed.
7737   // (See OpenCL 6.2).
7738   if (SrcTy->isVectorType()) {
7739     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7740         (getLangOpts().OpenCL &&
7741          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7742       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7743         << DestTy << SrcTy << R;
7744       return ExprError();
7745     }
7746     Kind = CK_BitCast;
7747     return CastExpr;
7748   }
7749 
7750   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7751   // conversion will take place first from scalar to elt type, and then
7752   // splat from elt type to vector.
7753   if (SrcTy->isPointerType())
7754     return Diag(R.getBegin(),
7755                 diag::err_invalid_conversion_between_vector_and_scalar)
7756       << DestTy << SrcTy << R;
7757 
7758   Kind = CK_VectorSplat;
7759   return prepareVectorSplat(DestTy, CastExpr);
7760 }
7761 
7762 ExprResult
7763 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7764                     Declarator &D, ParsedType &Ty,
7765                     SourceLocation RParenLoc, Expr *CastExpr) {
7766   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7767          "ActOnCastExpr(): missing type or expr");
7768 
7769   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7770   if (D.isInvalidType())
7771     return ExprError();
7772 
7773   if (getLangOpts().CPlusPlus) {
7774     // Check that there are no default arguments (C++ only).
7775     CheckExtraCXXDefaultArguments(D);
7776   } else {
7777     // Make sure any TypoExprs have been dealt with.
7778     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7779     if (!Res.isUsable())
7780       return ExprError();
7781     CastExpr = Res.get();
7782   }
7783 
7784   checkUnusedDeclAttributes(D);
7785 
7786   QualType castType = castTInfo->getType();
7787   Ty = CreateParsedType(castType, castTInfo);
7788 
7789   bool isVectorLiteral = false;
7790 
7791   // Check for an altivec or OpenCL literal,
7792   // i.e. all the elements are integer constants.
7793   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7794   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7795   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7796        && castType->isVectorType() && (PE || PLE)) {
7797     if (PLE && PLE->getNumExprs() == 0) {
7798       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7799       return ExprError();
7800     }
7801     if (PE || PLE->getNumExprs() == 1) {
7802       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7803       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7804         isVectorLiteral = true;
7805     }
7806     else
7807       isVectorLiteral = true;
7808   }
7809 
7810   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7811   // then handle it as such.
7812   if (isVectorLiteral)
7813     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7814 
7815   // If the Expr being casted is a ParenListExpr, handle it specially.
7816   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7817   // sequence of BinOp comma operators.
7818   if (isa<ParenListExpr>(CastExpr)) {
7819     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7820     if (Result.isInvalid()) return ExprError();
7821     CastExpr = Result.get();
7822   }
7823 
7824   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7825     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7826 
7827   CheckTollFreeBridgeCast(castType, CastExpr);
7828 
7829   CheckObjCBridgeRelatedCast(castType, CastExpr);
7830 
7831   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7832 
7833   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7834 }
7835 
7836 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7837                                     SourceLocation RParenLoc, Expr *E,
7838                                     TypeSourceInfo *TInfo) {
7839   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7840          "Expected paren or paren list expression");
7841 
7842   Expr **exprs;
7843   unsigned numExprs;
7844   Expr *subExpr;
7845   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7846   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7847     LiteralLParenLoc = PE->getLParenLoc();
7848     LiteralRParenLoc = PE->getRParenLoc();
7849     exprs = PE->getExprs();
7850     numExprs = PE->getNumExprs();
7851   } else { // isa<ParenExpr> by assertion at function entrance
7852     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7853     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7854     subExpr = cast<ParenExpr>(E)->getSubExpr();
7855     exprs = &subExpr;
7856     numExprs = 1;
7857   }
7858 
7859   QualType Ty = TInfo->getType();
7860   assert(Ty->isVectorType() && "Expected vector type");
7861 
7862   SmallVector<Expr *, 8> initExprs;
7863   const VectorType *VTy = Ty->castAs<VectorType>();
7864   unsigned numElems = VTy->getNumElements();
7865 
7866   // '(...)' form of vector initialization in AltiVec: the number of
7867   // initializers must be one or must match the size of the vector.
7868   // If a single value is specified in the initializer then it will be
7869   // replicated to all the components of the vector
7870   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7871                                  VTy->getElementType()))
7872     return ExprError();
7873   if (ShouldSplatAltivecScalarInCast(VTy)) {
7874     // The number of initializers must be one or must match the size of the
7875     // vector. If a single value is specified in the initializer then it will
7876     // be replicated to all the components of the vector
7877     if (numExprs == 1) {
7878       QualType ElemTy = VTy->getElementType();
7879       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7880       if (Literal.isInvalid())
7881         return ExprError();
7882       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7883                                   PrepareScalarCast(Literal, ElemTy));
7884       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7885     }
7886     else if (numExprs < numElems) {
7887       Diag(E->getExprLoc(),
7888            diag::err_incorrect_number_of_vector_initializers);
7889       return ExprError();
7890     }
7891     else
7892       initExprs.append(exprs, exprs + numExprs);
7893   }
7894   else {
7895     // For OpenCL, when the number of initializers is a single value,
7896     // it will be replicated to all components of the vector.
7897     if (getLangOpts().OpenCL &&
7898         VTy->getVectorKind() == VectorType::GenericVector &&
7899         numExprs == 1) {
7900         QualType ElemTy = VTy->getElementType();
7901         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7902         if (Literal.isInvalid())
7903           return ExprError();
7904         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7905                                     PrepareScalarCast(Literal, ElemTy));
7906         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7907     }
7908 
7909     initExprs.append(exprs, exprs + numExprs);
7910   }
7911   // FIXME: This means that pretty-printing the final AST will produce curly
7912   // braces instead of the original commas.
7913   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7914                                                    initExprs, LiteralRParenLoc);
7915   initE->setType(Ty);
7916   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7917 }
7918 
7919 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7920 /// the ParenListExpr into a sequence of comma binary operators.
7921 ExprResult
7922 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7923   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7924   if (!E)
7925     return OrigExpr;
7926 
7927   ExprResult Result(E->getExpr(0));
7928 
7929   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7930     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7931                         E->getExpr(i));
7932 
7933   if (Result.isInvalid()) return ExprError();
7934 
7935   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7936 }
7937 
7938 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7939                                     SourceLocation R,
7940                                     MultiExprArg Val) {
7941   return ParenListExpr::Create(Context, L, Val, R);
7942 }
7943 
7944 /// Emit a specialized diagnostic when one expression is a null pointer
7945 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7946 /// emitted.
7947 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7948                                       SourceLocation QuestionLoc) {
7949   Expr *NullExpr = LHSExpr;
7950   Expr *NonPointerExpr = RHSExpr;
7951   Expr::NullPointerConstantKind NullKind =
7952       NullExpr->isNullPointerConstant(Context,
7953                                       Expr::NPC_ValueDependentIsNotNull);
7954 
7955   if (NullKind == Expr::NPCK_NotNull) {
7956     NullExpr = RHSExpr;
7957     NonPointerExpr = LHSExpr;
7958     NullKind =
7959         NullExpr->isNullPointerConstant(Context,
7960                                         Expr::NPC_ValueDependentIsNotNull);
7961   }
7962 
7963   if (NullKind == Expr::NPCK_NotNull)
7964     return false;
7965 
7966   if (NullKind == Expr::NPCK_ZeroExpression)
7967     return false;
7968 
7969   if (NullKind == Expr::NPCK_ZeroLiteral) {
7970     // In this case, check to make sure that we got here from a "NULL"
7971     // string in the source code.
7972     NullExpr = NullExpr->IgnoreParenImpCasts();
7973     SourceLocation loc = NullExpr->getExprLoc();
7974     if (!findMacroSpelling(loc, "NULL"))
7975       return false;
7976   }
7977 
7978   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7979   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7980       << NonPointerExpr->getType() << DiagType
7981       << NonPointerExpr->getSourceRange();
7982   return true;
7983 }
7984 
7985 /// Return false if the condition expression is valid, true otherwise.
7986 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7987   QualType CondTy = Cond->getType();
7988 
7989   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7990   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7991     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7992       << CondTy << Cond->getSourceRange();
7993     return true;
7994   }
7995 
7996   // C99 6.5.15p2
7997   if (CondTy->isScalarType()) return false;
7998 
7999   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8000     << CondTy << Cond->getSourceRange();
8001   return true;
8002 }
8003 
8004 /// Handle when one or both operands are void type.
8005 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8006                                          ExprResult &RHS) {
8007     Expr *LHSExpr = LHS.get();
8008     Expr *RHSExpr = RHS.get();
8009 
8010     if (!LHSExpr->getType()->isVoidType())
8011       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8012           << RHSExpr->getSourceRange();
8013     if (!RHSExpr->getType()->isVoidType())
8014       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8015           << LHSExpr->getSourceRange();
8016     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8017     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8018     return S.Context.VoidTy;
8019 }
8020 
8021 /// Return false if the NullExpr can be promoted to PointerTy,
8022 /// true otherwise.
8023 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8024                                         QualType PointerTy) {
8025   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8026       !NullExpr.get()->isNullPointerConstant(S.Context,
8027                                             Expr::NPC_ValueDependentIsNull))
8028     return true;
8029 
8030   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8031   return false;
8032 }
8033 
8034 /// Checks compatibility between two pointers and return the resulting
8035 /// type.
8036 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8037                                                      ExprResult &RHS,
8038                                                      SourceLocation Loc) {
8039   QualType LHSTy = LHS.get()->getType();
8040   QualType RHSTy = RHS.get()->getType();
8041 
8042   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8043     // Two identical pointers types are always compatible.
8044     return LHSTy;
8045   }
8046 
8047   QualType lhptee, rhptee;
8048 
8049   // Get the pointee types.
8050   bool IsBlockPointer = false;
8051   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8052     lhptee = LHSBTy->getPointeeType();
8053     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8054     IsBlockPointer = true;
8055   } else {
8056     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8057     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8058   }
8059 
8060   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8061   // differently qualified versions of compatible types, the result type is
8062   // a pointer to an appropriately qualified version of the composite
8063   // type.
8064 
8065   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8066   // clause doesn't make sense for our extensions. E.g. address space 2 should
8067   // be incompatible with address space 3: they may live on different devices or
8068   // anything.
8069   Qualifiers lhQual = lhptee.getQualifiers();
8070   Qualifiers rhQual = rhptee.getQualifiers();
8071 
8072   LangAS ResultAddrSpace = LangAS::Default;
8073   LangAS LAddrSpace = lhQual.getAddressSpace();
8074   LangAS RAddrSpace = rhQual.getAddressSpace();
8075 
8076   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8077   // spaces is disallowed.
8078   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8079     ResultAddrSpace = LAddrSpace;
8080   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8081     ResultAddrSpace = RAddrSpace;
8082   else {
8083     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8084         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8085         << RHS.get()->getSourceRange();
8086     return QualType();
8087   }
8088 
8089   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8090   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8091   lhQual.removeCVRQualifiers();
8092   rhQual.removeCVRQualifiers();
8093 
8094   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8095   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8096   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8097   // qual types are compatible iff
8098   //  * corresponded types are compatible
8099   //  * CVR qualifiers are equal
8100   //  * address spaces are equal
8101   // Thus for conditional operator we merge CVR and address space unqualified
8102   // pointees and if there is a composite type we return a pointer to it with
8103   // merged qualifiers.
8104   LHSCastKind =
8105       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8106   RHSCastKind =
8107       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8108   lhQual.removeAddressSpace();
8109   rhQual.removeAddressSpace();
8110 
8111   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8112   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8113 
8114   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8115 
8116   if (CompositeTy.isNull()) {
8117     // In this situation, we assume void* type. No especially good
8118     // reason, but this is what gcc does, and we do have to pick
8119     // to get a consistent AST.
8120     QualType incompatTy;
8121     incompatTy = S.Context.getPointerType(
8122         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8123     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8124     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8125 
8126     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8127     // for casts between types with incompatible address space qualifiers.
8128     // For the following code the compiler produces casts between global and
8129     // local address spaces of the corresponded innermost pointees:
8130     // local int *global *a;
8131     // global int *global *b;
8132     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8133     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8134         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8135         << RHS.get()->getSourceRange();
8136 
8137     return incompatTy;
8138   }
8139 
8140   // The pointer types are compatible.
8141   // In case of OpenCL ResultTy should have the address space qualifier
8142   // which is a superset of address spaces of both the 2nd and the 3rd
8143   // operands of the conditional operator.
8144   QualType ResultTy = [&, ResultAddrSpace]() {
8145     if (S.getLangOpts().OpenCL) {
8146       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8147       CompositeQuals.setAddressSpace(ResultAddrSpace);
8148       return S.Context
8149           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8150           .withCVRQualifiers(MergedCVRQual);
8151     }
8152     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8153   }();
8154   if (IsBlockPointer)
8155     ResultTy = S.Context.getBlockPointerType(ResultTy);
8156   else
8157     ResultTy = S.Context.getPointerType(ResultTy);
8158 
8159   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8160   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8161   return ResultTy;
8162 }
8163 
8164 /// Return the resulting type when the operands are both block pointers.
8165 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8166                                                           ExprResult &LHS,
8167                                                           ExprResult &RHS,
8168                                                           SourceLocation Loc) {
8169   QualType LHSTy = LHS.get()->getType();
8170   QualType RHSTy = RHS.get()->getType();
8171 
8172   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8173     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8174       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8175       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8176       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8177       return destType;
8178     }
8179     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8180       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8181       << RHS.get()->getSourceRange();
8182     return QualType();
8183   }
8184 
8185   // We have 2 block pointer types.
8186   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8187 }
8188 
8189 /// Return the resulting type when the operands are both pointers.
8190 static QualType
8191 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8192                                             ExprResult &RHS,
8193                                             SourceLocation Loc) {
8194   // get the pointer types
8195   QualType LHSTy = LHS.get()->getType();
8196   QualType RHSTy = RHS.get()->getType();
8197 
8198   // get the "pointed to" types
8199   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8200   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8201 
8202   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8203   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8204     // Figure out necessary qualifiers (C99 6.5.15p6)
8205     QualType destPointee
8206       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8207     QualType destType = S.Context.getPointerType(destPointee);
8208     // Add qualifiers if necessary.
8209     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8210     // Promote to void*.
8211     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8212     return destType;
8213   }
8214   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8215     QualType destPointee
8216       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8217     QualType destType = S.Context.getPointerType(destPointee);
8218     // Add qualifiers if necessary.
8219     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8220     // Promote to void*.
8221     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8222     return destType;
8223   }
8224 
8225   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8226 }
8227 
8228 /// Return false if the first expression is not an integer and the second
8229 /// expression is not a pointer, true otherwise.
8230 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8231                                         Expr* PointerExpr, SourceLocation Loc,
8232                                         bool IsIntFirstExpr) {
8233   if (!PointerExpr->getType()->isPointerType() ||
8234       !Int.get()->getType()->isIntegerType())
8235     return false;
8236 
8237   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8238   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8239 
8240   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8241     << Expr1->getType() << Expr2->getType()
8242     << Expr1->getSourceRange() << Expr2->getSourceRange();
8243   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8244                             CK_IntegralToPointer);
8245   return true;
8246 }
8247 
8248 /// Simple conversion between integer and floating point types.
8249 ///
8250 /// Used when handling the OpenCL conditional operator where the
8251 /// condition is a vector while the other operands are scalar.
8252 ///
8253 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8254 /// types are either integer or floating type. Between the two
8255 /// operands, the type with the higher rank is defined as the "result
8256 /// type". The other operand needs to be promoted to the same type. No
8257 /// other type promotion is allowed. We cannot use
8258 /// UsualArithmeticConversions() for this purpose, since it always
8259 /// promotes promotable types.
8260 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8261                                             ExprResult &RHS,
8262                                             SourceLocation QuestionLoc) {
8263   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8264   if (LHS.isInvalid())
8265     return QualType();
8266   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8267   if (RHS.isInvalid())
8268     return QualType();
8269 
8270   // For conversion purposes, we ignore any qualifiers.
8271   // For example, "const float" and "float" are equivalent.
8272   QualType LHSType =
8273     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8274   QualType RHSType =
8275     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8276 
8277   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8278     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8279       << LHSType << LHS.get()->getSourceRange();
8280     return QualType();
8281   }
8282 
8283   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8284     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8285       << RHSType << RHS.get()->getSourceRange();
8286     return QualType();
8287   }
8288 
8289   // If both types are identical, no conversion is needed.
8290   if (LHSType == RHSType)
8291     return LHSType;
8292 
8293   // Now handle "real" floating types (i.e. float, double, long double).
8294   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8295     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8296                                  /*IsCompAssign = */ false);
8297 
8298   // Finally, we have two differing integer types.
8299   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8300   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8301 }
8302 
8303 /// Convert scalar operands to a vector that matches the
8304 ///        condition in length.
8305 ///
8306 /// Used when handling the OpenCL conditional operator where the
8307 /// condition is a vector while the other operands are scalar.
8308 ///
8309 /// We first compute the "result type" for the scalar operands
8310 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8311 /// into a vector of that type where the length matches the condition
8312 /// vector type. s6.11.6 requires that the element types of the result
8313 /// and the condition must have the same number of bits.
8314 static QualType
8315 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8316                               QualType CondTy, SourceLocation QuestionLoc) {
8317   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8318   if (ResTy.isNull()) return QualType();
8319 
8320   const VectorType *CV = CondTy->getAs<VectorType>();
8321   assert(CV);
8322 
8323   // Determine the vector result type
8324   unsigned NumElements = CV->getNumElements();
8325   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8326 
8327   // Ensure that all types have the same number of bits
8328   if (S.Context.getTypeSize(CV->getElementType())
8329       != S.Context.getTypeSize(ResTy)) {
8330     // Since VectorTy is created internally, it does not pretty print
8331     // with an OpenCL name. Instead, we just print a description.
8332     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8333     SmallString<64> Str;
8334     llvm::raw_svector_ostream OS(Str);
8335     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8336     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8337       << CondTy << OS.str();
8338     return QualType();
8339   }
8340 
8341   // Convert operands to the vector result type
8342   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8343   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8344 
8345   return VectorTy;
8346 }
8347 
8348 /// Return false if this is a valid OpenCL condition vector
8349 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8350                                        SourceLocation QuestionLoc) {
8351   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8352   // integral type.
8353   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8354   assert(CondTy);
8355   QualType EleTy = CondTy->getElementType();
8356   if (EleTy->isIntegerType()) return false;
8357 
8358   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8359     << Cond->getType() << Cond->getSourceRange();
8360   return true;
8361 }
8362 
8363 /// Return false if the vector condition type and the vector
8364 ///        result type are compatible.
8365 ///
8366 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8367 /// number of elements, and their element types have the same number
8368 /// of bits.
8369 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8370                               SourceLocation QuestionLoc) {
8371   const VectorType *CV = CondTy->getAs<VectorType>();
8372   const VectorType *RV = VecResTy->getAs<VectorType>();
8373   assert(CV && RV);
8374 
8375   if (CV->getNumElements() != RV->getNumElements()) {
8376     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8377       << CondTy << VecResTy;
8378     return true;
8379   }
8380 
8381   QualType CVE = CV->getElementType();
8382   QualType RVE = RV->getElementType();
8383 
8384   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8385     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8386       << CondTy << VecResTy;
8387     return true;
8388   }
8389 
8390   return false;
8391 }
8392 
8393 /// Return the resulting type for the conditional operator in
8394 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8395 ///        s6.3.i) when the condition is a vector type.
8396 static QualType
8397 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8398                              ExprResult &LHS, ExprResult &RHS,
8399                              SourceLocation QuestionLoc) {
8400   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8401   if (Cond.isInvalid())
8402     return QualType();
8403   QualType CondTy = Cond.get()->getType();
8404 
8405   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8406     return QualType();
8407 
8408   // If either operand is a vector then find the vector type of the
8409   // result as specified in OpenCL v1.1 s6.3.i.
8410   if (LHS.get()->getType()->isVectorType() ||
8411       RHS.get()->getType()->isVectorType()) {
8412     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8413                                               /*isCompAssign*/false,
8414                                               /*AllowBothBool*/true,
8415                                               /*AllowBoolConversions*/false);
8416     if (VecResTy.isNull()) return QualType();
8417     // The result type must match the condition type as specified in
8418     // OpenCL v1.1 s6.11.6.
8419     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8420       return QualType();
8421     return VecResTy;
8422   }
8423 
8424   // Both operands are scalar.
8425   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8426 }
8427 
8428 /// Return true if the Expr is block type
8429 static bool checkBlockType(Sema &S, const Expr *E) {
8430   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8431     QualType Ty = CE->getCallee()->getType();
8432     if (Ty->isBlockPointerType()) {
8433       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8434       return true;
8435     }
8436   }
8437   return false;
8438 }
8439 
8440 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8441 /// In that case, LHS = cond.
8442 /// C99 6.5.15
8443 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8444                                         ExprResult &RHS, ExprValueKind &VK,
8445                                         ExprObjectKind &OK,
8446                                         SourceLocation QuestionLoc) {
8447 
8448   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8449   if (!LHSResult.isUsable()) return QualType();
8450   LHS = LHSResult;
8451 
8452   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8453   if (!RHSResult.isUsable()) return QualType();
8454   RHS = RHSResult;
8455 
8456   // C++ is sufficiently different to merit its own checker.
8457   if (getLangOpts().CPlusPlus)
8458     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8459 
8460   VK = VK_PRValue;
8461   OK = OK_Ordinary;
8462 
8463   if (Context.isDependenceAllowed() &&
8464       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8465        RHS.get()->isTypeDependent())) {
8466     assert(!getLangOpts().CPlusPlus);
8467     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8468             RHS.get()->containsErrors()) &&
8469            "should only occur in error-recovery path.");
8470     return Context.DependentTy;
8471   }
8472 
8473   // The OpenCL operator with a vector condition is sufficiently
8474   // different to merit its own checker.
8475   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8476       Cond.get()->getType()->isExtVectorType())
8477     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8478 
8479   // First, check the condition.
8480   Cond = UsualUnaryConversions(Cond.get());
8481   if (Cond.isInvalid())
8482     return QualType();
8483   if (checkCondition(*this, Cond.get(), QuestionLoc))
8484     return QualType();
8485 
8486   // Now check the two expressions.
8487   if (LHS.get()->getType()->isVectorType() ||
8488       RHS.get()->getType()->isVectorType())
8489     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8490                                /*AllowBothBool*/true,
8491                                /*AllowBoolConversions*/false);
8492 
8493   QualType ResTy =
8494       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8495   if (LHS.isInvalid() || RHS.isInvalid())
8496     return QualType();
8497 
8498   QualType LHSTy = LHS.get()->getType();
8499   QualType RHSTy = RHS.get()->getType();
8500 
8501   // Diagnose attempts to convert between __ibm128, __float128 and long double
8502   // where such conversions currently can't be handled.
8503   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8504     Diag(QuestionLoc,
8505          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8506       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8507     return QualType();
8508   }
8509 
8510   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8511   // selection operator (?:).
8512   if (getLangOpts().OpenCL &&
8513       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8514     return QualType();
8515   }
8516 
8517   // If both operands have arithmetic type, do the usual arithmetic conversions
8518   // to find a common type: C99 6.5.15p3,5.
8519   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8520     // Disallow invalid arithmetic conversions, such as those between bit-
8521     // precise integers types of different sizes, or between a bit-precise
8522     // integer and another type.
8523     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8524       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8525           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8526           << RHS.get()->getSourceRange();
8527       return QualType();
8528     }
8529 
8530     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8531     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8532 
8533     return ResTy;
8534   }
8535 
8536   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8537   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8538     return LHSTy;
8539   }
8540 
8541   // If both operands are the same structure or union type, the result is that
8542   // type.
8543   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8544     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8545       if (LHSRT->getDecl() == RHSRT->getDecl())
8546         // "If both the operands have structure or union type, the result has
8547         // that type."  This implies that CV qualifiers are dropped.
8548         return LHSTy.getUnqualifiedType();
8549     // FIXME: Type of conditional expression must be complete in C mode.
8550   }
8551 
8552   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8553   // The following || allows only one side to be void (a GCC-ism).
8554   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8555     return checkConditionalVoidType(*this, LHS, RHS);
8556   }
8557 
8558   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8559   // the type of the other operand."
8560   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8561   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8562 
8563   // All objective-c pointer type analysis is done here.
8564   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8565                                                         QuestionLoc);
8566   if (LHS.isInvalid() || RHS.isInvalid())
8567     return QualType();
8568   if (!compositeType.isNull())
8569     return compositeType;
8570 
8571 
8572   // Handle block pointer types.
8573   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8574     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8575                                                      QuestionLoc);
8576 
8577   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8578   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8579     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8580                                                        QuestionLoc);
8581 
8582   // GCC compatibility: soften pointer/integer mismatch.  Note that
8583   // null pointers have been filtered out by this point.
8584   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8585       /*IsIntFirstExpr=*/true))
8586     return RHSTy;
8587   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8588       /*IsIntFirstExpr=*/false))
8589     return LHSTy;
8590 
8591   // Allow ?: operations in which both operands have the same
8592   // built-in sizeless type.
8593   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8594     return LHSTy;
8595 
8596   // Emit a better diagnostic if one of the expressions is a null pointer
8597   // constant and the other is not a pointer type. In this case, the user most
8598   // likely forgot to take the address of the other expression.
8599   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8600     return QualType();
8601 
8602   // Otherwise, the operands are not compatible.
8603   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8604     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8605     << RHS.get()->getSourceRange();
8606   return QualType();
8607 }
8608 
8609 /// FindCompositeObjCPointerType - Helper method to find composite type of
8610 /// two objective-c pointer types of the two input expressions.
8611 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8612                                             SourceLocation QuestionLoc) {
8613   QualType LHSTy = LHS.get()->getType();
8614   QualType RHSTy = RHS.get()->getType();
8615 
8616   // Handle things like Class and struct objc_class*.  Here we case the result
8617   // to the pseudo-builtin, because that will be implicitly cast back to the
8618   // redefinition type if an attempt is made to access its fields.
8619   if (LHSTy->isObjCClassType() &&
8620       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8621     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8622     return LHSTy;
8623   }
8624   if (RHSTy->isObjCClassType() &&
8625       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8626     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8627     return RHSTy;
8628   }
8629   // And the same for struct objc_object* / id
8630   if (LHSTy->isObjCIdType() &&
8631       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8632     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8633     return LHSTy;
8634   }
8635   if (RHSTy->isObjCIdType() &&
8636       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8637     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8638     return RHSTy;
8639   }
8640   // And the same for struct objc_selector* / SEL
8641   if (Context.isObjCSelType(LHSTy) &&
8642       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8643     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8644     return LHSTy;
8645   }
8646   if (Context.isObjCSelType(RHSTy) &&
8647       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8648     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8649     return RHSTy;
8650   }
8651   // Check constraints for Objective-C object pointers types.
8652   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8653 
8654     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8655       // Two identical object pointer types are always compatible.
8656       return LHSTy;
8657     }
8658     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8659     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8660     QualType compositeType = LHSTy;
8661 
8662     // If both operands are interfaces and either operand can be
8663     // assigned to the other, use that type as the composite
8664     // type. This allows
8665     //   xxx ? (A*) a : (B*) b
8666     // where B is a subclass of A.
8667     //
8668     // Additionally, as for assignment, if either type is 'id'
8669     // allow silent coercion. Finally, if the types are
8670     // incompatible then make sure to use 'id' as the composite
8671     // type so the result is acceptable for sending messages to.
8672 
8673     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8674     // It could return the composite type.
8675     if (!(compositeType =
8676           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8677       // Nothing more to do.
8678     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8679       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8680     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8681       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8682     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8683                 RHSOPT->isObjCQualifiedIdType()) &&
8684                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8685                                                          true)) {
8686       // Need to handle "id<xx>" explicitly.
8687       // GCC allows qualified id and any Objective-C type to devolve to
8688       // id. Currently localizing to here until clear this should be
8689       // part of ObjCQualifiedIdTypesAreCompatible.
8690       compositeType = Context.getObjCIdType();
8691     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8692       compositeType = Context.getObjCIdType();
8693     } else {
8694       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8695       << LHSTy << RHSTy
8696       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8697       QualType incompatTy = Context.getObjCIdType();
8698       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8699       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8700       return incompatTy;
8701     }
8702     // The object pointer types are compatible.
8703     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8704     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8705     return compositeType;
8706   }
8707   // Check Objective-C object pointer types and 'void *'
8708   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8709     if (getLangOpts().ObjCAutoRefCount) {
8710       // ARC forbids the implicit conversion of object pointers to 'void *',
8711       // so these types are not compatible.
8712       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8713           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8714       LHS = RHS = true;
8715       return QualType();
8716     }
8717     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8718     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8719     QualType destPointee
8720     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8721     QualType destType = Context.getPointerType(destPointee);
8722     // Add qualifiers if necessary.
8723     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8724     // Promote to void*.
8725     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8726     return destType;
8727   }
8728   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8729     if (getLangOpts().ObjCAutoRefCount) {
8730       // ARC forbids the implicit conversion of object pointers to 'void *',
8731       // so these types are not compatible.
8732       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8733           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8734       LHS = RHS = true;
8735       return QualType();
8736     }
8737     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8738     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8739     QualType destPointee
8740     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8741     QualType destType = Context.getPointerType(destPointee);
8742     // Add qualifiers if necessary.
8743     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8744     // Promote to void*.
8745     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8746     return destType;
8747   }
8748   return QualType();
8749 }
8750 
8751 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8752 /// ParenRange in parentheses.
8753 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8754                                const PartialDiagnostic &Note,
8755                                SourceRange ParenRange) {
8756   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8757   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8758       EndLoc.isValid()) {
8759     Self.Diag(Loc, Note)
8760       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8761       << FixItHint::CreateInsertion(EndLoc, ")");
8762   } else {
8763     // We can't display the parentheses, so just show the bare note.
8764     Self.Diag(Loc, Note) << ParenRange;
8765   }
8766 }
8767 
8768 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8769   return BinaryOperator::isAdditiveOp(Opc) ||
8770          BinaryOperator::isMultiplicativeOp(Opc) ||
8771          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8772   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8773   // not any of the logical operators.  Bitwise-xor is commonly used as a
8774   // logical-xor because there is no logical-xor operator.  The logical
8775   // operators, including uses of xor, have a high false positive rate for
8776   // precedence warnings.
8777 }
8778 
8779 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8780 /// expression, either using a built-in or overloaded operator,
8781 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8782 /// expression.
8783 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8784                                    Expr **RHSExprs) {
8785   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8786   E = E->IgnoreImpCasts();
8787   E = E->IgnoreConversionOperatorSingleStep();
8788   E = E->IgnoreImpCasts();
8789   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8790     E = MTE->getSubExpr();
8791     E = E->IgnoreImpCasts();
8792   }
8793 
8794   // Built-in binary operator.
8795   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8796     if (IsArithmeticOp(OP->getOpcode())) {
8797       *Opcode = OP->getOpcode();
8798       *RHSExprs = OP->getRHS();
8799       return true;
8800     }
8801   }
8802 
8803   // Overloaded operator.
8804   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8805     if (Call->getNumArgs() != 2)
8806       return false;
8807 
8808     // Make sure this is really a binary operator that is safe to pass into
8809     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8810     OverloadedOperatorKind OO = Call->getOperator();
8811     if (OO < OO_Plus || OO > OO_Arrow ||
8812         OO == OO_PlusPlus || OO == OO_MinusMinus)
8813       return false;
8814 
8815     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8816     if (IsArithmeticOp(OpKind)) {
8817       *Opcode = OpKind;
8818       *RHSExprs = Call->getArg(1);
8819       return true;
8820     }
8821   }
8822 
8823   return false;
8824 }
8825 
8826 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8827 /// or is a logical expression such as (x==y) which has int type, but is
8828 /// commonly interpreted as boolean.
8829 static bool ExprLooksBoolean(Expr *E) {
8830   E = E->IgnoreParenImpCasts();
8831 
8832   if (E->getType()->isBooleanType())
8833     return true;
8834   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8835     return OP->isComparisonOp() || OP->isLogicalOp();
8836   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8837     return OP->getOpcode() == UO_LNot;
8838   if (E->getType()->isPointerType())
8839     return true;
8840   // FIXME: What about overloaded operator calls returning "unspecified boolean
8841   // type"s (commonly pointer-to-members)?
8842 
8843   return false;
8844 }
8845 
8846 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8847 /// and binary operator are mixed in a way that suggests the programmer assumed
8848 /// the conditional operator has higher precedence, for example:
8849 /// "int x = a + someBinaryCondition ? 1 : 2".
8850 static void DiagnoseConditionalPrecedence(Sema &Self,
8851                                           SourceLocation OpLoc,
8852                                           Expr *Condition,
8853                                           Expr *LHSExpr,
8854                                           Expr *RHSExpr) {
8855   BinaryOperatorKind CondOpcode;
8856   Expr *CondRHS;
8857 
8858   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8859     return;
8860   if (!ExprLooksBoolean(CondRHS))
8861     return;
8862 
8863   // The condition is an arithmetic binary expression, with a right-
8864   // hand side that looks boolean, so warn.
8865 
8866   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8867                         ? diag::warn_precedence_bitwise_conditional
8868                         : diag::warn_precedence_conditional;
8869 
8870   Self.Diag(OpLoc, DiagID)
8871       << Condition->getSourceRange()
8872       << BinaryOperator::getOpcodeStr(CondOpcode);
8873 
8874   SuggestParentheses(
8875       Self, OpLoc,
8876       Self.PDiag(diag::note_precedence_silence)
8877           << BinaryOperator::getOpcodeStr(CondOpcode),
8878       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8879 
8880   SuggestParentheses(Self, OpLoc,
8881                      Self.PDiag(diag::note_precedence_conditional_first),
8882                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8883 }
8884 
8885 /// Compute the nullability of a conditional expression.
8886 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8887                                               QualType LHSTy, QualType RHSTy,
8888                                               ASTContext &Ctx) {
8889   if (!ResTy->isAnyPointerType())
8890     return ResTy;
8891 
8892   auto GetNullability = [&Ctx](QualType Ty) {
8893     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8894     if (Kind) {
8895       // For our purposes, treat _Nullable_result as _Nullable.
8896       if (*Kind == NullabilityKind::NullableResult)
8897         return NullabilityKind::Nullable;
8898       return *Kind;
8899     }
8900     return NullabilityKind::Unspecified;
8901   };
8902 
8903   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8904   NullabilityKind MergedKind;
8905 
8906   // Compute nullability of a binary conditional expression.
8907   if (IsBin) {
8908     if (LHSKind == NullabilityKind::NonNull)
8909       MergedKind = NullabilityKind::NonNull;
8910     else
8911       MergedKind = RHSKind;
8912   // Compute nullability of a normal conditional expression.
8913   } else {
8914     if (LHSKind == NullabilityKind::Nullable ||
8915         RHSKind == NullabilityKind::Nullable)
8916       MergedKind = NullabilityKind::Nullable;
8917     else if (LHSKind == NullabilityKind::NonNull)
8918       MergedKind = RHSKind;
8919     else if (RHSKind == NullabilityKind::NonNull)
8920       MergedKind = LHSKind;
8921     else
8922       MergedKind = NullabilityKind::Unspecified;
8923   }
8924 
8925   // Return if ResTy already has the correct nullability.
8926   if (GetNullability(ResTy) == MergedKind)
8927     return ResTy;
8928 
8929   // Strip all nullability from ResTy.
8930   while (ResTy->getNullability(Ctx))
8931     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8932 
8933   // Create a new AttributedType with the new nullability kind.
8934   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8935   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8936 }
8937 
8938 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8939 /// in the case of a the GNU conditional expr extension.
8940 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8941                                     SourceLocation ColonLoc,
8942                                     Expr *CondExpr, Expr *LHSExpr,
8943                                     Expr *RHSExpr) {
8944   if (!Context.isDependenceAllowed()) {
8945     // C cannot handle TypoExpr nodes in the condition because it
8946     // doesn't handle dependent types properly, so make sure any TypoExprs have
8947     // been dealt with before checking the operands.
8948     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8949     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8950     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8951 
8952     if (!CondResult.isUsable())
8953       return ExprError();
8954 
8955     if (LHSExpr) {
8956       if (!LHSResult.isUsable())
8957         return ExprError();
8958     }
8959 
8960     if (!RHSResult.isUsable())
8961       return ExprError();
8962 
8963     CondExpr = CondResult.get();
8964     LHSExpr = LHSResult.get();
8965     RHSExpr = RHSResult.get();
8966   }
8967 
8968   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8969   // was the condition.
8970   OpaqueValueExpr *opaqueValue = nullptr;
8971   Expr *commonExpr = nullptr;
8972   if (!LHSExpr) {
8973     commonExpr = CondExpr;
8974     // Lower out placeholder types first.  This is important so that we don't
8975     // try to capture a placeholder. This happens in few cases in C++; such
8976     // as Objective-C++'s dictionary subscripting syntax.
8977     if (commonExpr->hasPlaceholderType()) {
8978       ExprResult result = CheckPlaceholderExpr(commonExpr);
8979       if (!result.isUsable()) return ExprError();
8980       commonExpr = result.get();
8981     }
8982     // We usually want to apply unary conversions *before* saving, except
8983     // in the special case of a C++ l-value conditional.
8984     if (!(getLangOpts().CPlusPlus
8985           && !commonExpr->isTypeDependent()
8986           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8987           && commonExpr->isGLValue()
8988           && commonExpr->isOrdinaryOrBitFieldObject()
8989           && RHSExpr->isOrdinaryOrBitFieldObject()
8990           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8991       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8992       if (commonRes.isInvalid())
8993         return ExprError();
8994       commonExpr = commonRes.get();
8995     }
8996 
8997     // If the common expression is a class or array prvalue, materialize it
8998     // so that we can safely refer to it multiple times.
8999     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9000                                     commonExpr->getType()->isArrayType())) {
9001       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9002       if (MatExpr.isInvalid())
9003         return ExprError();
9004       commonExpr = MatExpr.get();
9005     }
9006 
9007     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9008                                                 commonExpr->getType(),
9009                                                 commonExpr->getValueKind(),
9010                                                 commonExpr->getObjectKind(),
9011                                                 commonExpr);
9012     LHSExpr = CondExpr = opaqueValue;
9013   }
9014 
9015   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9016   ExprValueKind VK = VK_PRValue;
9017   ExprObjectKind OK = OK_Ordinary;
9018   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9019   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9020                                              VK, OK, QuestionLoc);
9021   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9022       RHS.isInvalid())
9023     return ExprError();
9024 
9025   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9026                                 RHS.get());
9027 
9028   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9029 
9030   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9031                                          Context);
9032 
9033   if (!commonExpr)
9034     return new (Context)
9035         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9036                             RHS.get(), result, VK, OK);
9037 
9038   return new (Context) BinaryConditionalOperator(
9039       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9040       ColonLoc, result, VK, OK);
9041 }
9042 
9043 // Check if we have a conversion between incompatible cmse function pointer
9044 // types, that is, a conversion between a function pointer with the
9045 // cmse_nonsecure_call attribute and one without.
9046 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9047                                           QualType ToType) {
9048   if (const auto *ToFn =
9049           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9050     if (const auto *FromFn =
9051             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9052       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9053       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9054 
9055       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9056     }
9057   }
9058   return false;
9059 }
9060 
9061 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9062 // being closely modeled after the C99 spec:-). The odd characteristic of this
9063 // routine is it effectively iqnores the qualifiers on the top level pointee.
9064 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9065 // FIXME: add a couple examples in this comment.
9066 static Sema::AssignConvertType
9067 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9068   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9069   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9070 
9071   // get the "pointed to" type (ignoring qualifiers at the top level)
9072   const Type *lhptee, *rhptee;
9073   Qualifiers lhq, rhq;
9074   std::tie(lhptee, lhq) =
9075       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9076   std::tie(rhptee, rhq) =
9077       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9078 
9079   Sema::AssignConvertType ConvTy = Sema::Compatible;
9080 
9081   // C99 6.5.16.1p1: This following citation is common to constraints
9082   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9083   // qualifiers of the type *pointed to* by the right;
9084 
9085   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9086   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9087       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9088     // Ignore lifetime for further calculation.
9089     lhq.removeObjCLifetime();
9090     rhq.removeObjCLifetime();
9091   }
9092 
9093   if (!lhq.compatiblyIncludes(rhq)) {
9094     // Treat address-space mismatches as fatal.
9095     if (!lhq.isAddressSpaceSupersetOf(rhq))
9096       return Sema::IncompatiblePointerDiscardsQualifiers;
9097 
9098     // It's okay to add or remove GC or lifetime qualifiers when converting to
9099     // and from void*.
9100     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9101                         .compatiblyIncludes(
9102                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9103              && (lhptee->isVoidType() || rhptee->isVoidType()))
9104       ; // keep old
9105 
9106     // Treat lifetime mismatches as fatal.
9107     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9108       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9109 
9110     // For GCC/MS compatibility, other qualifier mismatches are treated
9111     // as still compatible in C.
9112     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9113   }
9114 
9115   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9116   // incomplete type and the other is a pointer to a qualified or unqualified
9117   // version of void...
9118   if (lhptee->isVoidType()) {
9119     if (rhptee->isIncompleteOrObjectType())
9120       return ConvTy;
9121 
9122     // As an extension, we allow cast to/from void* to function pointer.
9123     assert(rhptee->isFunctionType());
9124     return Sema::FunctionVoidPointer;
9125   }
9126 
9127   if (rhptee->isVoidType()) {
9128     if (lhptee->isIncompleteOrObjectType())
9129       return ConvTy;
9130 
9131     // As an extension, we allow cast to/from void* to function pointer.
9132     assert(lhptee->isFunctionType());
9133     return Sema::FunctionVoidPointer;
9134   }
9135 
9136   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9137   // unqualified versions of compatible types, ...
9138   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9139   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9140     // Check if the pointee types are compatible ignoring the sign.
9141     // We explicitly check for char so that we catch "char" vs
9142     // "unsigned char" on systems where "char" is unsigned.
9143     if (lhptee->isCharType())
9144       ltrans = S.Context.UnsignedCharTy;
9145     else if (lhptee->hasSignedIntegerRepresentation())
9146       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9147 
9148     if (rhptee->isCharType())
9149       rtrans = S.Context.UnsignedCharTy;
9150     else if (rhptee->hasSignedIntegerRepresentation())
9151       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9152 
9153     if (ltrans == rtrans) {
9154       // Types are compatible ignoring the sign. Qualifier incompatibility
9155       // takes priority over sign incompatibility because the sign
9156       // warning can be disabled.
9157       if (ConvTy != Sema::Compatible)
9158         return ConvTy;
9159 
9160       return Sema::IncompatiblePointerSign;
9161     }
9162 
9163     // If we are a multi-level pointer, it's possible that our issue is simply
9164     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9165     // the eventual target type is the same and the pointers have the same
9166     // level of indirection, this must be the issue.
9167     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9168       do {
9169         std::tie(lhptee, lhq) =
9170           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9171         std::tie(rhptee, rhq) =
9172           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9173 
9174         // Inconsistent address spaces at this point is invalid, even if the
9175         // address spaces would be compatible.
9176         // FIXME: This doesn't catch address space mismatches for pointers of
9177         // different nesting levels, like:
9178         //   __local int *** a;
9179         //   int ** b = a;
9180         // It's not clear how to actually determine when such pointers are
9181         // invalidly incompatible.
9182         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9183           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9184 
9185       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9186 
9187       if (lhptee == rhptee)
9188         return Sema::IncompatibleNestedPointerQualifiers;
9189     }
9190 
9191     // General pointer incompatibility takes priority over qualifiers.
9192     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9193       return Sema::IncompatibleFunctionPointer;
9194     return Sema::IncompatiblePointer;
9195   }
9196   if (!S.getLangOpts().CPlusPlus &&
9197       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9198     return Sema::IncompatibleFunctionPointer;
9199   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9200     return Sema::IncompatibleFunctionPointer;
9201   return ConvTy;
9202 }
9203 
9204 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9205 /// block pointer types are compatible or whether a block and normal pointer
9206 /// are compatible. It is more restrict than comparing two function pointer
9207 // types.
9208 static Sema::AssignConvertType
9209 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9210                                     QualType RHSType) {
9211   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9212   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9213 
9214   QualType lhptee, rhptee;
9215 
9216   // get the "pointed to" type (ignoring qualifiers at the top level)
9217   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9218   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9219 
9220   // In C++, the types have to match exactly.
9221   if (S.getLangOpts().CPlusPlus)
9222     return Sema::IncompatibleBlockPointer;
9223 
9224   Sema::AssignConvertType ConvTy = Sema::Compatible;
9225 
9226   // For blocks we enforce that qualifiers are identical.
9227   Qualifiers LQuals = lhptee.getLocalQualifiers();
9228   Qualifiers RQuals = rhptee.getLocalQualifiers();
9229   if (S.getLangOpts().OpenCL) {
9230     LQuals.removeAddressSpace();
9231     RQuals.removeAddressSpace();
9232   }
9233   if (LQuals != RQuals)
9234     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9235 
9236   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9237   // assignment.
9238   // The current behavior is similar to C++ lambdas. A block might be
9239   // assigned to a variable iff its return type and parameters are compatible
9240   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9241   // an assignment. Presumably it should behave in way that a function pointer
9242   // assignment does in C, so for each parameter and return type:
9243   //  * CVR and address space of LHS should be a superset of CVR and address
9244   //  space of RHS.
9245   //  * unqualified types should be compatible.
9246   if (S.getLangOpts().OpenCL) {
9247     if (!S.Context.typesAreBlockPointerCompatible(
9248             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9249             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9250       return Sema::IncompatibleBlockPointer;
9251   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9252     return Sema::IncompatibleBlockPointer;
9253 
9254   return ConvTy;
9255 }
9256 
9257 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9258 /// for assignment compatibility.
9259 static Sema::AssignConvertType
9260 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9261                                    QualType RHSType) {
9262   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9263   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9264 
9265   if (LHSType->isObjCBuiltinType()) {
9266     // Class is not compatible with ObjC object pointers.
9267     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9268         !RHSType->isObjCQualifiedClassType())
9269       return Sema::IncompatiblePointer;
9270     return Sema::Compatible;
9271   }
9272   if (RHSType->isObjCBuiltinType()) {
9273     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9274         !LHSType->isObjCQualifiedClassType())
9275       return Sema::IncompatiblePointer;
9276     return Sema::Compatible;
9277   }
9278   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9279   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9280 
9281   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9282       // make an exception for id<P>
9283       !LHSType->isObjCQualifiedIdType())
9284     return Sema::CompatiblePointerDiscardsQualifiers;
9285 
9286   if (S.Context.typesAreCompatible(LHSType, RHSType))
9287     return Sema::Compatible;
9288   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9289     return Sema::IncompatibleObjCQualifiedId;
9290   return Sema::IncompatiblePointer;
9291 }
9292 
9293 Sema::AssignConvertType
9294 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9295                                  QualType LHSType, QualType RHSType) {
9296   // Fake up an opaque expression.  We don't actually care about what
9297   // cast operations are required, so if CheckAssignmentConstraints
9298   // adds casts to this they'll be wasted, but fortunately that doesn't
9299   // usually happen on valid code.
9300   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9301   ExprResult RHSPtr = &RHSExpr;
9302   CastKind K;
9303 
9304   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9305 }
9306 
9307 /// This helper function returns true if QT is a vector type that has element
9308 /// type ElementType.
9309 static bool isVector(QualType QT, QualType ElementType) {
9310   if (const VectorType *VT = QT->getAs<VectorType>())
9311     return VT->getElementType().getCanonicalType() == ElementType;
9312   return false;
9313 }
9314 
9315 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9316 /// has code to accommodate several GCC extensions when type checking
9317 /// pointers. Here are some objectionable examples that GCC considers warnings:
9318 ///
9319 ///  int a, *pint;
9320 ///  short *pshort;
9321 ///  struct foo *pfoo;
9322 ///
9323 ///  pint = pshort; // warning: assignment from incompatible pointer type
9324 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9325 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9326 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9327 ///
9328 /// As a result, the code for dealing with pointers is more complex than the
9329 /// C99 spec dictates.
9330 ///
9331 /// Sets 'Kind' for any result kind except Incompatible.
9332 Sema::AssignConvertType
9333 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9334                                  CastKind &Kind, bool ConvertRHS) {
9335   QualType RHSType = RHS.get()->getType();
9336   QualType OrigLHSType = LHSType;
9337 
9338   // Get canonical types.  We're not formatting these types, just comparing
9339   // them.
9340   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9341   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9342 
9343   // Common case: no conversion required.
9344   if (LHSType == RHSType) {
9345     Kind = CK_NoOp;
9346     return Compatible;
9347   }
9348 
9349   // If we have an atomic type, try a non-atomic assignment, then just add an
9350   // atomic qualification step.
9351   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9352     Sema::AssignConvertType result =
9353       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9354     if (result != Compatible)
9355       return result;
9356     if (Kind != CK_NoOp && ConvertRHS)
9357       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9358     Kind = CK_NonAtomicToAtomic;
9359     return Compatible;
9360   }
9361 
9362   // If the left-hand side is a reference type, then we are in a
9363   // (rare!) case where we've allowed the use of references in C,
9364   // e.g., as a parameter type in a built-in function. In this case,
9365   // just make sure that the type referenced is compatible with the
9366   // right-hand side type. The caller is responsible for adjusting
9367   // LHSType so that the resulting expression does not have reference
9368   // type.
9369   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9370     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9371       Kind = CK_LValueBitCast;
9372       return Compatible;
9373     }
9374     return Incompatible;
9375   }
9376 
9377   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9378   // to the same ExtVector type.
9379   if (LHSType->isExtVectorType()) {
9380     if (RHSType->isExtVectorType())
9381       return Incompatible;
9382     if (RHSType->isArithmeticType()) {
9383       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9384       if (ConvertRHS)
9385         RHS = prepareVectorSplat(LHSType, RHS.get());
9386       Kind = CK_VectorSplat;
9387       return Compatible;
9388     }
9389   }
9390 
9391   // Conversions to or from vector type.
9392   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9393     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9394       // Allow assignments of an AltiVec vector type to an equivalent GCC
9395       // vector type and vice versa
9396       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9397         Kind = CK_BitCast;
9398         return Compatible;
9399       }
9400 
9401       // If we are allowing lax vector conversions, and LHS and RHS are both
9402       // vectors, the total size only needs to be the same. This is a bitcast;
9403       // no bits are changed but the result type is different.
9404       if (isLaxVectorConversion(RHSType, LHSType)) {
9405         Kind = CK_BitCast;
9406         return IncompatibleVectors;
9407       }
9408     }
9409 
9410     // When the RHS comes from another lax conversion (e.g. binops between
9411     // scalars and vectors) the result is canonicalized as a vector. When the
9412     // LHS is also a vector, the lax is allowed by the condition above. Handle
9413     // the case where LHS is a scalar.
9414     if (LHSType->isScalarType()) {
9415       const VectorType *VecType = RHSType->getAs<VectorType>();
9416       if (VecType && VecType->getNumElements() == 1 &&
9417           isLaxVectorConversion(RHSType, LHSType)) {
9418         ExprResult *VecExpr = &RHS;
9419         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9420         Kind = CK_BitCast;
9421         return Compatible;
9422       }
9423     }
9424 
9425     // Allow assignments between fixed-length and sizeless SVE vectors.
9426     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9427         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9428       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9429           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9430         Kind = CK_BitCast;
9431         return Compatible;
9432       }
9433 
9434     return Incompatible;
9435   }
9436 
9437   // Diagnose attempts to convert between __ibm128, __float128 and long double
9438   // where such conversions currently can't be handled.
9439   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9440     return Incompatible;
9441 
9442   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9443   // discards the imaginary part.
9444   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9445       !LHSType->getAs<ComplexType>())
9446     return Incompatible;
9447 
9448   // Arithmetic conversions.
9449   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9450       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9451     if (ConvertRHS)
9452       Kind = PrepareScalarCast(RHS, LHSType);
9453     return Compatible;
9454   }
9455 
9456   // Conversions to normal pointers.
9457   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9458     // U* -> T*
9459     if (isa<PointerType>(RHSType)) {
9460       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9461       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9462       if (AddrSpaceL != AddrSpaceR)
9463         Kind = CK_AddressSpaceConversion;
9464       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9465         Kind = CK_NoOp;
9466       else
9467         Kind = CK_BitCast;
9468       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9469     }
9470 
9471     // int -> T*
9472     if (RHSType->isIntegerType()) {
9473       Kind = CK_IntegralToPointer; // FIXME: null?
9474       return IntToPointer;
9475     }
9476 
9477     // C pointers are not compatible with ObjC object pointers,
9478     // with two exceptions:
9479     if (isa<ObjCObjectPointerType>(RHSType)) {
9480       //  - conversions to void*
9481       if (LHSPointer->getPointeeType()->isVoidType()) {
9482         Kind = CK_BitCast;
9483         return Compatible;
9484       }
9485 
9486       //  - conversions from 'Class' to the redefinition type
9487       if (RHSType->isObjCClassType() &&
9488           Context.hasSameType(LHSType,
9489                               Context.getObjCClassRedefinitionType())) {
9490         Kind = CK_BitCast;
9491         return Compatible;
9492       }
9493 
9494       Kind = CK_BitCast;
9495       return IncompatiblePointer;
9496     }
9497 
9498     // U^ -> void*
9499     if (RHSType->getAs<BlockPointerType>()) {
9500       if (LHSPointer->getPointeeType()->isVoidType()) {
9501         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9502         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9503                                 ->getPointeeType()
9504                                 .getAddressSpace();
9505         Kind =
9506             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9507         return Compatible;
9508       }
9509     }
9510 
9511     return Incompatible;
9512   }
9513 
9514   // Conversions to block pointers.
9515   if (isa<BlockPointerType>(LHSType)) {
9516     // U^ -> T^
9517     if (RHSType->isBlockPointerType()) {
9518       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9519                               ->getPointeeType()
9520                               .getAddressSpace();
9521       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9522                               ->getPointeeType()
9523                               .getAddressSpace();
9524       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9525       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9526     }
9527 
9528     // int or null -> T^
9529     if (RHSType->isIntegerType()) {
9530       Kind = CK_IntegralToPointer; // FIXME: null
9531       return IntToBlockPointer;
9532     }
9533 
9534     // id -> T^
9535     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9536       Kind = CK_AnyPointerToBlockPointerCast;
9537       return Compatible;
9538     }
9539 
9540     // void* -> T^
9541     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9542       if (RHSPT->getPointeeType()->isVoidType()) {
9543         Kind = CK_AnyPointerToBlockPointerCast;
9544         return Compatible;
9545       }
9546 
9547     return Incompatible;
9548   }
9549 
9550   // Conversions to Objective-C pointers.
9551   if (isa<ObjCObjectPointerType>(LHSType)) {
9552     // A* -> B*
9553     if (RHSType->isObjCObjectPointerType()) {
9554       Kind = CK_BitCast;
9555       Sema::AssignConvertType result =
9556         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9557       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9558           result == Compatible &&
9559           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9560         result = IncompatibleObjCWeakRef;
9561       return result;
9562     }
9563 
9564     // int or null -> A*
9565     if (RHSType->isIntegerType()) {
9566       Kind = CK_IntegralToPointer; // FIXME: null
9567       return IntToPointer;
9568     }
9569 
9570     // In general, C pointers are not compatible with ObjC object pointers,
9571     // with two exceptions:
9572     if (isa<PointerType>(RHSType)) {
9573       Kind = CK_CPointerToObjCPointerCast;
9574 
9575       //  - conversions from 'void*'
9576       if (RHSType->isVoidPointerType()) {
9577         return Compatible;
9578       }
9579 
9580       //  - conversions to 'Class' from its redefinition type
9581       if (LHSType->isObjCClassType() &&
9582           Context.hasSameType(RHSType,
9583                               Context.getObjCClassRedefinitionType())) {
9584         return Compatible;
9585       }
9586 
9587       return IncompatiblePointer;
9588     }
9589 
9590     // Only under strict condition T^ is compatible with an Objective-C pointer.
9591     if (RHSType->isBlockPointerType() &&
9592         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9593       if (ConvertRHS)
9594         maybeExtendBlockObject(RHS);
9595       Kind = CK_BlockPointerToObjCPointerCast;
9596       return Compatible;
9597     }
9598 
9599     return Incompatible;
9600   }
9601 
9602   // Conversions from pointers that are not covered by the above.
9603   if (isa<PointerType>(RHSType)) {
9604     // T* -> _Bool
9605     if (LHSType == Context.BoolTy) {
9606       Kind = CK_PointerToBoolean;
9607       return Compatible;
9608     }
9609 
9610     // T* -> int
9611     if (LHSType->isIntegerType()) {
9612       Kind = CK_PointerToIntegral;
9613       return PointerToInt;
9614     }
9615 
9616     return Incompatible;
9617   }
9618 
9619   // Conversions from Objective-C pointers that are not covered by the above.
9620   if (isa<ObjCObjectPointerType>(RHSType)) {
9621     // T* -> _Bool
9622     if (LHSType == Context.BoolTy) {
9623       Kind = CK_PointerToBoolean;
9624       return Compatible;
9625     }
9626 
9627     // T* -> int
9628     if (LHSType->isIntegerType()) {
9629       Kind = CK_PointerToIntegral;
9630       return PointerToInt;
9631     }
9632 
9633     return Incompatible;
9634   }
9635 
9636   // struct A -> struct B
9637   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9638     if (Context.typesAreCompatible(LHSType, RHSType)) {
9639       Kind = CK_NoOp;
9640       return Compatible;
9641     }
9642   }
9643 
9644   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9645     Kind = CK_IntToOCLSampler;
9646     return Compatible;
9647   }
9648 
9649   return Incompatible;
9650 }
9651 
9652 /// Constructs a transparent union from an expression that is
9653 /// used to initialize the transparent union.
9654 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9655                                       ExprResult &EResult, QualType UnionType,
9656                                       FieldDecl *Field) {
9657   // Build an initializer list that designates the appropriate member
9658   // of the transparent union.
9659   Expr *E = EResult.get();
9660   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9661                                                    E, SourceLocation());
9662   Initializer->setType(UnionType);
9663   Initializer->setInitializedFieldInUnion(Field);
9664 
9665   // Build a compound literal constructing a value of the transparent
9666   // union type from this initializer list.
9667   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9668   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9669                                         VK_PRValue, Initializer, false);
9670 }
9671 
9672 Sema::AssignConvertType
9673 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9674                                                ExprResult &RHS) {
9675   QualType RHSType = RHS.get()->getType();
9676 
9677   // If the ArgType is a Union type, we want to handle a potential
9678   // transparent_union GCC extension.
9679   const RecordType *UT = ArgType->getAsUnionType();
9680   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9681     return Incompatible;
9682 
9683   // The field to initialize within the transparent union.
9684   RecordDecl *UD = UT->getDecl();
9685   FieldDecl *InitField = nullptr;
9686   // It's compatible if the expression matches any of the fields.
9687   for (auto *it : UD->fields()) {
9688     if (it->getType()->isPointerType()) {
9689       // If the transparent union contains a pointer type, we allow:
9690       // 1) void pointer
9691       // 2) null pointer constant
9692       if (RHSType->isPointerType())
9693         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9694           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9695           InitField = it;
9696           break;
9697         }
9698 
9699       if (RHS.get()->isNullPointerConstant(Context,
9700                                            Expr::NPC_ValueDependentIsNull)) {
9701         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9702                                 CK_NullToPointer);
9703         InitField = it;
9704         break;
9705       }
9706     }
9707 
9708     CastKind Kind;
9709     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9710           == Compatible) {
9711       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9712       InitField = it;
9713       break;
9714     }
9715   }
9716 
9717   if (!InitField)
9718     return Incompatible;
9719 
9720   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9721   return Compatible;
9722 }
9723 
9724 Sema::AssignConvertType
9725 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9726                                        bool Diagnose,
9727                                        bool DiagnoseCFAudited,
9728                                        bool ConvertRHS) {
9729   // We need to be able to tell the caller whether we diagnosed a problem, if
9730   // they ask us to issue diagnostics.
9731   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9732 
9733   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9734   // we can't avoid *all* modifications at the moment, so we need some somewhere
9735   // to put the updated value.
9736   ExprResult LocalRHS = CallerRHS;
9737   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9738 
9739   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9740     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9741       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9742           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9743         Diag(RHS.get()->getExprLoc(),
9744              diag::warn_noderef_to_dereferenceable_pointer)
9745             << RHS.get()->getSourceRange();
9746       }
9747     }
9748   }
9749 
9750   if (getLangOpts().CPlusPlus) {
9751     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9752       // C++ 5.17p3: If the left operand is not of class type, the
9753       // expression is implicitly converted (C++ 4) to the
9754       // cv-unqualified type of the left operand.
9755       QualType RHSType = RHS.get()->getType();
9756       if (Diagnose) {
9757         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9758                                         AA_Assigning);
9759       } else {
9760         ImplicitConversionSequence ICS =
9761             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9762                                   /*SuppressUserConversions=*/false,
9763                                   AllowedExplicit::None,
9764                                   /*InOverloadResolution=*/false,
9765                                   /*CStyle=*/false,
9766                                   /*AllowObjCWritebackConversion=*/false);
9767         if (ICS.isFailure())
9768           return Incompatible;
9769         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9770                                         ICS, AA_Assigning);
9771       }
9772       if (RHS.isInvalid())
9773         return Incompatible;
9774       Sema::AssignConvertType result = Compatible;
9775       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9776           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9777         result = IncompatibleObjCWeakRef;
9778       return result;
9779     }
9780 
9781     // FIXME: Currently, we fall through and treat C++ classes like C
9782     // structures.
9783     // FIXME: We also fall through for atomics; not sure what should
9784     // happen there, though.
9785   } else if (RHS.get()->getType() == Context.OverloadTy) {
9786     // As a set of extensions to C, we support overloading on functions. These
9787     // functions need to be resolved here.
9788     DeclAccessPair DAP;
9789     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9790             RHS.get(), LHSType, /*Complain=*/false, DAP))
9791       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9792     else
9793       return Incompatible;
9794   }
9795 
9796   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9797   // a null pointer constant.
9798   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9799        LHSType->isBlockPointerType()) &&
9800       RHS.get()->isNullPointerConstant(Context,
9801                                        Expr::NPC_ValueDependentIsNull)) {
9802     if (Diagnose || ConvertRHS) {
9803       CastKind Kind;
9804       CXXCastPath Path;
9805       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9806                              /*IgnoreBaseAccess=*/false, Diagnose);
9807       if (ConvertRHS)
9808         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9809     }
9810     return Compatible;
9811   }
9812 
9813   // OpenCL queue_t type assignment.
9814   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9815                                  Context, Expr::NPC_ValueDependentIsNull)) {
9816     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9817     return Compatible;
9818   }
9819 
9820   // This check seems unnatural, however it is necessary to ensure the proper
9821   // conversion of functions/arrays. If the conversion were done for all
9822   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9823   // expressions that suppress this implicit conversion (&, sizeof).
9824   //
9825   // Suppress this for references: C++ 8.5.3p5.
9826   if (!LHSType->isReferenceType()) {
9827     // FIXME: We potentially allocate here even if ConvertRHS is false.
9828     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9829     if (RHS.isInvalid())
9830       return Incompatible;
9831   }
9832   CastKind Kind;
9833   Sema::AssignConvertType result =
9834     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9835 
9836   // C99 6.5.16.1p2: The value of the right operand is converted to the
9837   // type of the assignment expression.
9838   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9839   // so that we can use references in built-in functions even in C.
9840   // The getNonReferenceType() call makes sure that the resulting expression
9841   // does not have reference type.
9842   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9843     QualType Ty = LHSType.getNonLValueExprType(Context);
9844     Expr *E = RHS.get();
9845 
9846     // Check for various Objective-C errors. If we are not reporting
9847     // diagnostics and just checking for errors, e.g., during overload
9848     // resolution, return Incompatible to indicate the failure.
9849     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9850         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9851                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9852       if (!Diagnose)
9853         return Incompatible;
9854     }
9855     if (getLangOpts().ObjC &&
9856         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9857                                            E->getType(), E, Diagnose) ||
9858          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9859       if (!Diagnose)
9860         return Incompatible;
9861       // Replace the expression with a corrected version and continue so we
9862       // can find further errors.
9863       RHS = E;
9864       return Compatible;
9865     }
9866 
9867     if (ConvertRHS)
9868       RHS = ImpCastExprToType(E, Ty, Kind);
9869   }
9870 
9871   return result;
9872 }
9873 
9874 namespace {
9875 /// The original operand to an operator, prior to the application of the usual
9876 /// arithmetic conversions and converting the arguments of a builtin operator
9877 /// candidate.
9878 struct OriginalOperand {
9879   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9880     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9881       Op = MTE->getSubExpr();
9882     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9883       Op = BTE->getSubExpr();
9884     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9885       Orig = ICE->getSubExprAsWritten();
9886       Conversion = ICE->getConversionFunction();
9887     }
9888   }
9889 
9890   QualType getType() const { return Orig->getType(); }
9891 
9892   Expr *Orig;
9893   NamedDecl *Conversion;
9894 };
9895 }
9896 
9897 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9898                                ExprResult &RHS) {
9899   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9900 
9901   Diag(Loc, diag::err_typecheck_invalid_operands)
9902     << OrigLHS.getType() << OrigRHS.getType()
9903     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9904 
9905   // If a user-defined conversion was applied to either of the operands prior
9906   // to applying the built-in operator rules, tell the user about it.
9907   if (OrigLHS.Conversion) {
9908     Diag(OrigLHS.Conversion->getLocation(),
9909          diag::note_typecheck_invalid_operands_converted)
9910       << 0 << LHS.get()->getType();
9911   }
9912   if (OrigRHS.Conversion) {
9913     Diag(OrigRHS.Conversion->getLocation(),
9914          diag::note_typecheck_invalid_operands_converted)
9915       << 1 << RHS.get()->getType();
9916   }
9917 
9918   return QualType();
9919 }
9920 
9921 // Diagnose cases where a scalar was implicitly converted to a vector and
9922 // diagnose the underlying types. Otherwise, diagnose the error
9923 // as invalid vector logical operands for non-C++ cases.
9924 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9925                                             ExprResult &RHS) {
9926   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9927   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9928 
9929   bool LHSNatVec = LHSType->isVectorType();
9930   bool RHSNatVec = RHSType->isVectorType();
9931 
9932   if (!(LHSNatVec && RHSNatVec)) {
9933     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9934     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9935     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9936         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9937         << Vector->getSourceRange();
9938     return QualType();
9939   }
9940 
9941   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9942       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9943       << RHS.get()->getSourceRange();
9944 
9945   return QualType();
9946 }
9947 
9948 /// Try to convert a value of non-vector type to a vector type by converting
9949 /// the type to the element type of the vector and then performing a splat.
9950 /// If the language is OpenCL, we only use conversions that promote scalar
9951 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9952 /// for float->int.
9953 ///
9954 /// OpenCL V2.0 6.2.6.p2:
9955 /// An error shall occur if any scalar operand type has greater rank
9956 /// than the type of the vector element.
9957 ///
9958 /// \param scalar - if non-null, actually perform the conversions
9959 /// \return true if the operation fails (but without diagnosing the failure)
9960 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9961                                      QualType scalarTy,
9962                                      QualType vectorEltTy,
9963                                      QualType vectorTy,
9964                                      unsigned &DiagID) {
9965   // The conversion to apply to the scalar before splatting it,
9966   // if necessary.
9967   CastKind scalarCast = CK_NoOp;
9968 
9969   if (vectorEltTy->isIntegralType(S.Context)) {
9970     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9971         (scalarTy->isIntegerType() &&
9972          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9973       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9974       return true;
9975     }
9976     if (!scalarTy->isIntegralType(S.Context))
9977       return true;
9978     scalarCast = CK_IntegralCast;
9979   } else if (vectorEltTy->isRealFloatingType()) {
9980     if (scalarTy->isRealFloatingType()) {
9981       if (S.getLangOpts().OpenCL &&
9982           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9983         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9984         return true;
9985       }
9986       scalarCast = CK_FloatingCast;
9987     }
9988     else if (scalarTy->isIntegralType(S.Context))
9989       scalarCast = CK_IntegralToFloating;
9990     else
9991       return true;
9992   } else {
9993     return true;
9994   }
9995 
9996   // Adjust scalar if desired.
9997   if (scalar) {
9998     if (scalarCast != CK_NoOp)
9999       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10000     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10001   }
10002   return false;
10003 }
10004 
10005 /// Convert vector E to a vector with the same number of elements but different
10006 /// element type.
10007 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10008   const auto *VecTy = E->getType()->getAs<VectorType>();
10009   assert(VecTy && "Expression E must be a vector");
10010   QualType NewVecTy = S.Context.getVectorType(ElementType,
10011                                               VecTy->getNumElements(),
10012                                               VecTy->getVectorKind());
10013 
10014   // Look through the implicit cast. Return the subexpression if its type is
10015   // NewVecTy.
10016   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10017     if (ICE->getSubExpr()->getType() == NewVecTy)
10018       return ICE->getSubExpr();
10019 
10020   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10021   return S.ImpCastExprToType(E, NewVecTy, Cast);
10022 }
10023 
10024 /// Test if a (constant) integer Int can be casted to another integer type
10025 /// IntTy without losing precision.
10026 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10027                                       QualType OtherIntTy) {
10028   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10029 
10030   // Reject cases where the value of the Int is unknown as that would
10031   // possibly cause truncation, but accept cases where the scalar can be
10032   // demoted without loss of precision.
10033   Expr::EvalResult EVResult;
10034   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10035   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10036   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10037   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10038 
10039   if (CstInt) {
10040     // If the scalar is constant and is of a higher order and has more active
10041     // bits that the vector element type, reject it.
10042     llvm::APSInt Result = EVResult.Val.getInt();
10043     unsigned NumBits = IntSigned
10044                            ? (Result.isNegative() ? Result.getMinSignedBits()
10045                                                   : Result.getActiveBits())
10046                            : Result.getActiveBits();
10047     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10048       return true;
10049 
10050     // If the signedness of the scalar type and the vector element type
10051     // differs and the number of bits is greater than that of the vector
10052     // element reject it.
10053     return (IntSigned != OtherIntSigned &&
10054             NumBits > S.Context.getIntWidth(OtherIntTy));
10055   }
10056 
10057   // Reject cases where the value of the scalar is not constant and it's
10058   // order is greater than that of the vector element type.
10059   return (Order < 0);
10060 }
10061 
10062 /// Test if a (constant) integer Int can be casted to floating point type
10063 /// FloatTy without losing precision.
10064 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10065                                      QualType FloatTy) {
10066   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10067 
10068   // Determine if the integer constant can be expressed as a floating point
10069   // number of the appropriate type.
10070   Expr::EvalResult EVResult;
10071   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10072 
10073   uint64_t Bits = 0;
10074   if (CstInt) {
10075     // Reject constants that would be truncated if they were converted to
10076     // the floating point type. Test by simple to/from conversion.
10077     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10078     //        could be avoided if there was a convertFromAPInt method
10079     //        which could signal back if implicit truncation occurred.
10080     llvm::APSInt Result = EVResult.Val.getInt();
10081     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10082     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10083                            llvm::APFloat::rmTowardZero);
10084     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10085                              !IntTy->hasSignedIntegerRepresentation());
10086     bool Ignored = false;
10087     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10088                            &Ignored);
10089     if (Result != ConvertBack)
10090       return true;
10091   } else {
10092     // Reject types that cannot be fully encoded into the mantissa of
10093     // the float.
10094     Bits = S.Context.getTypeSize(IntTy);
10095     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10096         S.Context.getFloatTypeSemantics(FloatTy));
10097     if (Bits > FloatPrec)
10098       return true;
10099   }
10100 
10101   return false;
10102 }
10103 
10104 /// Attempt to convert and splat Scalar into a vector whose types matches
10105 /// Vector following GCC conversion rules. The rule is that implicit
10106 /// conversion can occur when Scalar can be casted to match Vector's element
10107 /// type without causing truncation of Scalar.
10108 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10109                                         ExprResult *Vector) {
10110   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10111   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10112   const auto *VT = VectorTy->castAs<VectorType>();
10113 
10114   assert(!isa<ExtVectorType>(VT) &&
10115          "ExtVectorTypes should not be handled here!");
10116 
10117   QualType VectorEltTy = VT->getElementType();
10118 
10119   // Reject cases where the vector element type or the scalar element type are
10120   // not integral or floating point types.
10121   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10122     return true;
10123 
10124   // The conversion to apply to the scalar before splatting it,
10125   // if necessary.
10126   CastKind ScalarCast = CK_NoOp;
10127 
10128   // Accept cases where the vector elements are integers and the scalar is
10129   // an integer.
10130   // FIXME: Notionally if the scalar was a floating point value with a precise
10131   //        integral representation, we could cast it to an appropriate integer
10132   //        type and then perform the rest of the checks here. GCC will perform
10133   //        this conversion in some cases as determined by the input language.
10134   //        We should accept it on a language independent basis.
10135   if (VectorEltTy->isIntegralType(S.Context) &&
10136       ScalarTy->isIntegralType(S.Context) &&
10137       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10138 
10139     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10140       return true;
10141 
10142     ScalarCast = CK_IntegralCast;
10143   } else if (VectorEltTy->isIntegralType(S.Context) &&
10144              ScalarTy->isRealFloatingType()) {
10145     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10146       ScalarCast = CK_FloatingToIntegral;
10147     else
10148       return true;
10149   } else if (VectorEltTy->isRealFloatingType()) {
10150     if (ScalarTy->isRealFloatingType()) {
10151 
10152       // Reject cases where the scalar type is not a constant and has a higher
10153       // Order than the vector element type.
10154       llvm::APFloat Result(0.0);
10155 
10156       // Determine whether this is a constant scalar. In the event that the
10157       // value is dependent (and thus cannot be evaluated by the constant
10158       // evaluator), skip the evaluation. This will then diagnose once the
10159       // expression is instantiated.
10160       bool CstScalar = Scalar->get()->isValueDependent() ||
10161                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10162       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10163       if (!CstScalar && Order < 0)
10164         return true;
10165 
10166       // If the scalar cannot be safely casted to the vector element type,
10167       // reject it.
10168       if (CstScalar) {
10169         bool Truncated = false;
10170         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10171                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10172         if (Truncated)
10173           return true;
10174       }
10175 
10176       ScalarCast = CK_FloatingCast;
10177     } else if (ScalarTy->isIntegralType(S.Context)) {
10178       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10179         return true;
10180 
10181       ScalarCast = CK_IntegralToFloating;
10182     } else
10183       return true;
10184   } else if (ScalarTy->isEnumeralType())
10185     return true;
10186 
10187   // Adjust scalar if desired.
10188   if (Scalar) {
10189     if (ScalarCast != CK_NoOp)
10190       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10191     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10192   }
10193   return false;
10194 }
10195 
10196 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10197                                    SourceLocation Loc, bool IsCompAssign,
10198                                    bool AllowBothBool,
10199                                    bool AllowBoolConversions) {
10200   if (!IsCompAssign) {
10201     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10202     if (LHS.isInvalid())
10203       return QualType();
10204   }
10205   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10206   if (RHS.isInvalid())
10207     return QualType();
10208 
10209   // For conversion purposes, we ignore any qualifiers.
10210   // For example, "const float" and "float" are equivalent.
10211   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10212   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10213 
10214   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10215   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10216   assert(LHSVecType || RHSVecType);
10217 
10218   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10219       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10220     return InvalidOperands(Loc, LHS, RHS);
10221 
10222   // AltiVec-style "vector bool op vector bool" combinations are allowed
10223   // for some operators but not others.
10224   if (!AllowBothBool &&
10225       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10226       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10227     return InvalidOperands(Loc, LHS, RHS);
10228 
10229   // If the vector types are identical, return.
10230   if (Context.hasSameType(LHSType, RHSType))
10231     return LHSType;
10232 
10233   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10234   if (LHSVecType && RHSVecType &&
10235       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10236     if (isa<ExtVectorType>(LHSVecType)) {
10237       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10238       return LHSType;
10239     }
10240 
10241     if (!IsCompAssign)
10242       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10243     return RHSType;
10244   }
10245 
10246   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10247   // can be mixed, with the result being the non-bool type.  The non-bool
10248   // operand must have integer element type.
10249   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10250       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10251       (Context.getTypeSize(LHSVecType->getElementType()) ==
10252        Context.getTypeSize(RHSVecType->getElementType()))) {
10253     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10254         LHSVecType->getElementType()->isIntegerType() &&
10255         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10256       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10257       return LHSType;
10258     }
10259     if (!IsCompAssign &&
10260         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10261         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10262         RHSVecType->getElementType()->isIntegerType()) {
10263       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10264       return RHSType;
10265     }
10266   }
10267 
10268   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10269   // since the ambiguity can affect the ABI.
10270   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10271     const VectorType *VecType = SecondType->getAs<VectorType>();
10272     return FirstType->isSizelessBuiltinType() && VecType &&
10273            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10274             VecType->getVectorKind() ==
10275                 VectorType::SveFixedLengthPredicateVector);
10276   };
10277 
10278   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10279     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10280     return QualType();
10281   }
10282 
10283   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10284   // since the ambiguity can affect the ABI.
10285   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10286     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10287     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10288 
10289     if (FirstVecType && SecondVecType)
10290       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10291              (SecondVecType->getVectorKind() ==
10292                   VectorType::SveFixedLengthDataVector ||
10293               SecondVecType->getVectorKind() ==
10294                   VectorType::SveFixedLengthPredicateVector);
10295 
10296     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10297            SecondVecType->getVectorKind() == VectorType::GenericVector;
10298   };
10299 
10300   if (IsSveGnuConversion(LHSType, RHSType) ||
10301       IsSveGnuConversion(RHSType, LHSType)) {
10302     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10303     return QualType();
10304   }
10305 
10306   // If there's a vector type and a scalar, try to convert the scalar to
10307   // the vector element type and splat.
10308   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10309   if (!RHSVecType) {
10310     if (isa<ExtVectorType>(LHSVecType)) {
10311       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10312                                     LHSVecType->getElementType(), LHSType,
10313                                     DiagID))
10314         return LHSType;
10315     } else {
10316       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10317         return LHSType;
10318     }
10319   }
10320   if (!LHSVecType) {
10321     if (isa<ExtVectorType>(RHSVecType)) {
10322       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10323                                     LHSType, RHSVecType->getElementType(),
10324                                     RHSType, DiagID))
10325         return RHSType;
10326     } else {
10327       if (LHS.get()->isLValue() ||
10328           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10329         return RHSType;
10330     }
10331   }
10332 
10333   // FIXME: The code below also handles conversion between vectors and
10334   // non-scalars, we should break this down into fine grained specific checks
10335   // and emit proper diagnostics.
10336   QualType VecType = LHSVecType ? LHSType : RHSType;
10337   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10338   QualType OtherType = LHSVecType ? RHSType : LHSType;
10339   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10340   if (isLaxVectorConversion(OtherType, VecType)) {
10341     // If we're allowing lax vector conversions, only the total (data) size
10342     // needs to be the same. For non compound assignment, if one of the types is
10343     // scalar, the result is always the vector type.
10344     if (!IsCompAssign) {
10345       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10346       return VecType;
10347     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10348     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10349     // type. Note that this is already done by non-compound assignments in
10350     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10351     // <1 x T> -> T. The result is also a vector type.
10352     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10353                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10354       ExprResult *RHSExpr = &RHS;
10355       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10356       return VecType;
10357     }
10358   }
10359 
10360   // Okay, the expression is invalid.
10361 
10362   // If there's a non-vector, non-real operand, diagnose that.
10363   if ((!RHSVecType && !RHSType->isRealType()) ||
10364       (!LHSVecType && !LHSType->isRealType())) {
10365     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10366       << LHSType << RHSType
10367       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10368     return QualType();
10369   }
10370 
10371   // OpenCL V1.1 6.2.6.p1:
10372   // If the operands are of more than one vector type, then an error shall
10373   // occur. Implicit conversions between vector types are not permitted, per
10374   // section 6.2.1.
10375   if (getLangOpts().OpenCL &&
10376       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10377       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10378     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10379                                                            << RHSType;
10380     return QualType();
10381   }
10382 
10383 
10384   // If there is a vector type that is not a ExtVector and a scalar, we reach
10385   // this point if scalar could not be converted to the vector's element type
10386   // without truncation.
10387   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10388       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10389     QualType Scalar = LHSVecType ? RHSType : LHSType;
10390     QualType Vector = LHSVecType ? LHSType : RHSType;
10391     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10392     Diag(Loc,
10393          diag::err_typecheck_vector_not_convertable_implict_truncation)
10394         << ScalarOrVector << Scalar << Vector;
10395 
10396     return QualType();
10397   }
10398 
10399   // Otherwise, use the generic diagnostic.
10400   Diag(Loc, DiagID)
10401     << LHSType << RHSType
10402     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10403   return QualType();
10404 }
10405 
10406 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10407                                            SourceLocation Loc) {
10408   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10409   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10410 
10411   const BuiltinType *LHSVecType = LHSType->getAs<BuiltinType>();
10412   const BuiltinType *RHSVecType = RHSType->getAs<BuiltinType>();
10413 
10414   unsigned DiagID = diag::err_typecheck_invalid_operands;
10415   if (LHSVecType->isSVEBool() || RHSVecType->isSVEBool()) {
10416     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10417                       << RHS.get()->getSourceRange();
10418     return QualType();
10419   }
10420 
10421   if (Context.hasSameType(LHSType, RHSType))
10422     return LHSType;
10423 
10424   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10425                     << RHS.get()->getSourceRange();
10426   return QualType();
10427 }
10428 
10429 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10430 // expression.  These are mainly cases where the null pointer is used as an
10431 // integer instead of a pointer.
10432 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10433                                 SourceLocation Loc, bool IsCompare) {
10434   // The canonical way to check for a GNU null is with isNullPointerConstant,
10435   // but we use a bit of a hack here for speed; this is a relatively
10436   // hot path, and isNullPointerConstant is slow.
10437   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10438   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10439 
10440   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10441 
10442   // Avoid analyzing cases where the result will either be invalid (and
10443   // diagnosed as such) or entirely valid and not something to warn about.
10444   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10445       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10446     return;
10447 
10448   // Comparison operations would not make sense with a null pointer no matter
10449   // what the other expression is.
10450   if (!IsCompare) {
10451     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10452         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10453         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10454     return;
10455   }
10456 
10457   // The rest of the operations only make sense with a null pointer
10458   // if the other expression is a pointer.
10459   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10460       NonNullType->canDecayToPointerType())
10461     return;
10462 
10463   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10464       << LHSNull /* LHS is NULL */ << NonNullType
10465       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10466 }
10467 
10468 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10469                                           SourceLocation Loc) {
10470   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10471   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10472   if (!LUE || !RUE)
10473     return;
10474   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10475       RUE->getKind() != UETT_SizeOf)
10476     return;
10477 
10478   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10479   QualType LHSTy = LHSArg->getType();
10480   QualType RHSTy;
10481 
10482   if (RUE->isArgumentType())
10483     RHSTy = RUE->getArgumentType().getNonReferenceType();
10484   else
10485     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10486 
10487   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10488     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10489       return;
10490 
10491     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10492     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10493       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10494         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10495             << LHSArgDecl;
10496     }
10497   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10498     QualType ArrayElemTy = ArrayTy->getElementType();
10499     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10500         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10501         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10502         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10503       return;
10504     S.Diag(Loc, diag::warn_division_sizeof_array)
10505         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10506     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10507       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10508         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10509             << LHSArgDecl;
10510     }
10511 
10512     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10513   }
10514 }
10515 
10516 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10517                                                ExprResult &RHS,
10518                                                SourceLocation Loc, bool IsDiv) {
10519   // Check for division/remainder by zero.
10520   Expr::EvalResult RHSValue;
10521   if (!RHS.get()->isValueDependent() &&
10522       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10523       RHSValue.Val.getInt() == 0)
10524     S.DiagRuntimeBehavior(Loc, RHS.get(),
10525                           S.PDiag(diag::warn_remainder_division_by_zero)
10526                             << IsDiv << RHS.get()->getSourceRange());
10527 }
10528 
10529 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10530                                            SourceLocation Loc,
10531                                            bool IsCompAssign, bool IsDiv) {
10532   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10533 
10534   QualType LHSTy = LHS.get()->getType();
10535   QualType RHSTy = RHS.get()->getType();
10536   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10537     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10538                                /*AllowBothBool*/ getLangOpts().AltiVec,
10539                                /*AllowBoolConversions*/ false);
10540   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10541     return CheckSizelessVectorOperands(LHS, RHS, Loc);
10542   if (!IsDiv &&
10543       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10544     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10545   // For division, only matrix-by-scalar is supported. Other combinations with
10546   // matrix types are invalid.
10547   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10548     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10549 
10550   QualType compType = UsualArithmeticConversions(
10551       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10552   if (LHS.isInvalid() || RHS.isInvalid())
10553     return QualType();
10554 
10555 
10556   if (compType.isNull() || !compType->isArithmeticType())
10557     return InvalidOperands(Loc, LHS, RHS);
10558   if (IsDiv) {
10559     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10560     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10561   }
10562   return compType;
10563 }
10564 
10565 QualType Sema::CheckRemainderOperands(
10566   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10567   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10568 
10569   if (LHS.get()->getType()->isVectorType() ||
10570       RHS.get()->getType()->isVectorType()) {
10571     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10572         RHS.get()->getType()->hasIntegerRepresentation())
10573       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10574                                  /*AllowBothBool*/getLangOpts().AltiVec,
10575                                  /*AllowBoolConversions*/false);
10576     return InvalidOperands(Loc, LHS, RHS);
10577   }
10578 
10579   if (LHS.get()->getType()->isVLSTBuiltinType() &&
10580       RHS.get()->getType()->isVLSTBuiltinType()) {
10581     if (LHS.get()
10582             ->getType()
10583             ->getSveEltType(Context)
10584             ->hasIntegerRepresentation() &&
10585         RHS.get()
10586             ->getType()
10587             ->getSveEltType(Context)
10588             ->hasIntegerRepresentation())
10589       return CheckSizelessVectorOperands(LHS, RHS, Loc);
10590 
10591     return InvalidOperands(Loc, LHS, RHS);
10592   }
10593 
10594   QualType compType = UsualArithmeticConversions(
10595       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10596   if (LHS.isInvalid() || RHS.isInvalid())
10597     return QualType();
10598 
10599   if (compType.isNull() || !compType->isIntegerType())
10600     return InvalidOperands(Loc, LHS, RHS);
10601   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10602   return compType;
10603 }
10604 
10605 /// Diagnose invalid arithmetic on two void pointers.
10606 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10607                                                 Expr *LHSExpr, Expr *RHSExpr) {
10608   S.Diag(Loc, S.getLangOpts().CPlusPlus
10609                 ? diag::err_typecheck_pointer_arith_void_type
10610                 : diag::ext_gnu_void_ptr)
10611     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10612                             << RHSExpr->getSourceRange();
10613 }
10614 
10615 /// Diagnose invalid arithmetic on a void pointer.
10616 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10617                                             Expr *Pointer) {
10618   S.Diag(Loc, S.getLangOpts().CPlusPlus
10619                 ? diag::err_typecheck_pointer_arith_void_type
10620                 : diag::ext_gnu_void_ptr)
10621     << 0 /* one pointer */ << Pointer->getSourceRange();
10622 }
10623 
10624 /// Diagnose invalid arithmetic on a null pointer.
10625 ///
10626 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10627 /// idiom, which we recognize as a GNU extension.
10628 ///
10629 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10630                                             Expr *Pointer, bool IsGNUIdiom) {
10631   if (IsGNUIdiom)
10632     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10633       << Pointer->getSourceRange();
10634   else
10635     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10636       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10637 }
10638 
10639 /// Diagnose invalid subraction on a null pointer.
10640 ///
10641 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10642                                              Expr *Pointer, bool BothNull) {
10643   // Null - null is valid in C++ [expr.add]p7
10644   if (BothNull && S.getLangOpts().CPlusPlus)
10645     return;
10646 
10647   // Is this s a macro from a system header?
10648   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10649     return;
10650 
10651   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10652       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10653 }
10654 
10655 /// Diagnose invalid arithmetic on two function pointers.
10656 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10657                                                     Expr *LHS, Expr *RHS) {
10658   assert(LHS->getType()->isAnyPointerType());
10659   assert(RHS->getType()->isAnyPointerType());
10660   S.Diag(Loc, S.getLangOpts().CPlusPlus
10661                 ? diag::err_typecheck_pointer_arith_function_type
10662                 : diag::ext_gnu_ptr_func_arith)
10663     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10664     // We only show the second type if it differs from the first.
10665     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10666                                                    RHS->getType())
10667     << RHS->getType()->getPointeeType()
10668     << LHS->getSourceRange() << RHS->getSourceRange();
10669 }
10670 
10671 /// Diagnose invalid arithmetic on a function pointer.
10672 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10673                                                 Expr *Pointer) {
10674   assert(Pointer->getType()->isAnyPointerType());
10675   S.Diag(Loc, S.getLangOpts().CPlusPlus
10676                 ? diag::err_typecheck_pointer_arith_function_type
10677                 : diag::ext_gnu_ptr_func_arith)
10678     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10679     << 0 /* one pointer, so only one type */
10680     << Pointer->getSourceRange();
10681 }
10682 
10683 /// Emit error if Operand is incomplete pointer type
10684 ///
10685 /// \returns True if pointer has incomplete type
10686 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10687                                                  Expr *Operand) {
10688   QualType ResType = Operand->getType();
10689   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10690     ResType = ResAtomicType->getValueType();
10691 
10692   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10693   QualType PointeeTy = ResType->getPointeeType();
10694   return S.RequireCompleteSizedType(
10695       Loc, PointeeTy,
10696       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10697       Operand->getSourceRange());
10698 }
10699 
10700 /// Check the validity of an arithmetic pointer operand.
10701 ///
10702 /// If the operand has pointer type, this code will check for pointer types
10703 /// which are invalid in arithmetic operations. These will be diagnosed
10704 /// appropriately, including whether or not the use is supported as an
10705 /// extension.
10706 ///
10707 /// \returns True when the operand is valid to use (even if as an extension).
10708 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10709                                             Expr *Operand) {
10710   QualType ResType = Operand->getType();
10711   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10712     ResType = ResAtomicType->getValueType();
10713 
10714   if (!ResType->isAnyPointerType()) return true;
10715 
10716   QualType PointeeTy = ResType->getPointeeType();
10717   if (PointeeTy->isVoidType()) {
10718     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10719     return !S.getLangOpts().CPlusPlus;
10720   }
10721   if (PointeeTy->isFunctionType()) {
10722     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10723     return !S.getLangOpts().CPlusPlus;
10724   }
10725 
10726   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10727 
10728   return true;
10729 }
10730 
10731 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10732 /// operands.
10733 ///
10734 /// This routine will diagnose any invalid arithmetic on pointer operands much
10735 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10736 /// for emitting a single diagnostic even for operations where both LHS and RHS
10737 /// are (potentially problematic) pointers.
10738 ///
10739 /// \returns True when the operand is valid to use (even if as an extension).
10740 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10741                                                 Expr *LHSExpr, Expr *RHSExpr) {
10742   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10743   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10744   if (!isLHSPointer && !isRHSPointer) return true;
10745 
10746   QualType LHSPointeeTy, RHSPointeeTy;
10747   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10748   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10749 
10750   // if both are pointers check if operation is valid wrt address spaces
10751   if (isLHSPointer && isRHSPointer) {
10752     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10753       S.Diag(Loc,
10754              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10755           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10756           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10757       return false;
10758     }
10759   }
10760 
10761   // Check for arithmetic on pointers to incomplete types.
10762   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10763   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10764   if (isLHSVoidPtr || isRHSVoidPtr) {
10765     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10766     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10767     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10768 
10769     return !S.getLangOpts().CPlusPlus;
10770   }
10771 
10772   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10773   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10774   if (isLHSFuncPtr || isRHSFuncPtr) {
10775     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10776     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10777                                                                 RHSExpr);
10778     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10779 
10780     return !S.getLangOpts().CPlusPlus;
10781   }
10782 
10783   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10784     return false;
10785   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10786     return false;
10787 
10788   return true;
10789 }
10790 
10791 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10792 /// literal.
10793 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10794                                   Expr *LHSExpr, Expr *RHSExpr) {
10795   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10796   Expr* IndexExpr = RHSExpr;
10797   if (!StrExpr) {
10798     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10799     IndexExpr = LHSExpr;
10800   }
10801 
10802   bool IsStringPlusInt = StrExpr &&
10803       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10804   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10805     return;
10806 
10807   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10808   Self.Diag(OpLoc, diag::warn_string_plus_int)
10809       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10810 
10811   // Only print a fixit for "str" + int, not for int + "str".
10812   if (IndexExpr == RHSExpr) {
10813     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10814     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10815         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10816         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10817         << FixItHint::CreateInsertion(EndLoc, "]");
10818   } else
10819     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10820 }
10821 
10822 /// Emit a warning when adding a char literal to a string.
10823 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10824                                    Expr *LHSExpr, Expr *RHSExpr) {
10825   const Expr *StringRefExpr = LHSExpr;
10826   const CharacterLiteral *CharExpr =
10827       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10828 
10829   if (!CharExpr) {
10830     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10831     StringRefExpr = RHSExpr;
10832   }
10833 
10834   if (!CharExpr || !StringRefExpr)
10835     return;
10836 
10837   const QualType StringType = StringRefExpr->getType();
10838 
10839   // Return if not a PointerType.
10840   if (!StringType->isAnyPointerType())
10841     return;
10842 
10843   // Return if not a CharacterType.
10844   if (!StringType->getPointeeType()->isAnyCharacterType())
10845     return;
10846 
10847   ASTContext &Ctx = Self.getASTContext();
10848   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10849 
10850   const QualType CharType = CharExpr->getType();
10851   if (!CharType->isAnyCharacterType() &&
10852       CharType->isIntegerType() &&
10853       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10854     Self.Diag(OpLoc, diag::warn_string_plus_char)
10855         << DiagRange << Ctx.CharTy;
10856   } else {
10857     Self.Diag(OpLoc, diag::warn_string_plus_char)
10858         << DiagRange << CharExpr->getType();
10859   }
10860 
10861   // Only print a fixit for str + char, not for char + str.
10862   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10863     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10864     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10865         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10866         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10867         << FixItHint::CreateInsertion(EndLoc, "]");
10868   } else {
10869     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10870   }
10871 }
10872 
10873 /// Emit error when two pointers are incompatible.
10874 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10875                                            Expr *LHSExpr, Expr *RHSExpr) {
10876   assert(LHSExpr->getType()->isAnyPointerType());
10877   assert(RHSExpr->getType()->isAnyPointerType());
10878   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10879     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10880     << RHSExpr->getSourceRange();
10881 }
10882 
10883 // C99 6.5.6
10884 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10885                                      SourceLocation Loc, BinaryOperatorKind Opc,
10886                                      QualType* CompLHSTy) {
10887   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10888 
10889   if (LHS.get()->getType()->isVectorType() ||
10890       RHS.get()->getType()->isVectorType()) {
10891     QualType compType = CheckVectorOperands(
10892         LHS, RHS, Loc, CompLHSTy,
10893         /*AllowBothBool*/getLangOpts().AltiVec,
10894         /*AllowBoolConversions*/getLangOpts().ZVector);
10895     if (CompLHSTy) *CompLHSTy = compType;
10896     return compType;
10897   }
10898 
10899   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10900       RHS.get()->getType()->isVLSTBuiltinType()) {
10901     QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc);
10902     if (CompLHSTy)
10903       *CompLHSTy = compType;
10904     return compType;
10905   }
10906 
10907   if (LHS.get()->getType()->isConstantMatrixType() ||
10908       RHS.get()->getType()->isConstantMatrixType()) {
10909     QualType compType =
10910         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10911     if (CompLHSTy)
10912       *CompLHSTy = compType;
10913     return compType;
10914   }
10915 
10916   QualType compType = UsualArithmeticConversions(
10917       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10918   if (LHS.isInvalid() || RHS.isInvalid())
10919     return QualType();
10920 
10921   // Diagnose "string literal" '+' int and string '+' "char literal".
10922   if (Opc == BO_Add) {
10923     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10924     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10925   }
10926 
10927   // handle the common case first (both operands are arithmetic).
10928   if (!compType.isNull() && compType->isArithmeticType()) {
10929     if (CompLHSTy) *CompLHSTy = compType;
10930     return compType;
10931   }
10932 
10933   // Type-checking.  Ultimately the pointer's going to be in PExp;
10934   // note that we bias towards the LHS being the pointer.
10935   Expr *PExp = LHS.get(), *IExp = RHS.get();
10936 
10937   bool isObjCPointer;
10938   if (PExp->getType()->isPointerType()) {
10939     isObjCPointer = false;
10940   } else if (PExp->getType()->isObjCObjectPointerType()) {
10941     isObjCPointer = true;
10942   } else {
10943     std::swap(PExp, IExp);
10944     if (PExp->getType()->isPointerType()) {
10945       isObjCPointer = false;
10946     } else if (PExp->getType()->isObjCObjectPointerType()) {
10947       isObjCPointer = true;
10948     } else {
10949       return InvalidOperands(Loc, LHS, RHS);
10950     }
10951   }
10952   assert(PExp->getType()->isAnyPointerType());
10953 
10954   if (!IExp->getType()->isIntegerType())
10955     return InvalidOperands(Loc, LHS, RHS);
10956 
10957   // Adding to a null pointer results in undefined behavior.
10958   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10959           Context, Expr::NPC_ValueDependentIsNotNull)) {
10960     // In C++ adding zero to a null pointer is defined.
10961     Expr::EvalResult KnownVal;
10962     if (!getLangOpts().CPlusPlus ||
10963         (!IExp->isValueDependent() &&
10964          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10965           KnownVal.Val.getInt() != 0))) {
10966       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10967       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10968           Context, BO_Add, PExp, IExp);
10969       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10970     }
10971   }
10972 
10973   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10974     return QualType();
10975 
10976   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10977     return QualType();
10978 
10979   // Check array bounds for pointer arithemtic
10980   CheckArrayAccess(PExp, IExp);
10981 
10982   if (CompLHSTy) {
10983     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10984     if (LHSTy.isNull()) {
10985       LHSTy = LHS.get()->getType();
10986       if (LHSTy->isPromotableIntegerType())
10987         LHSTy = Context.getPromotedIntegerType(LHSTy);
10988     }
10989     *CompLHSTy = LHSTy;
10990   }
10991 
10992   return PExp->getType();
10993 }
10994 
10995 // C99 6.5.6
10996 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10997                                         SourceLocation Loc,
10998                                         QualType* CompLHSTy) {
10999   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11000 
11001   if (LHS.get()->getType()->isVectorType() ||
11002       RHS.get()->getType()->isVectorType()) {
11003     QualType compType = CheckVectorOperands(
11004         LHS, RHS, Loc, CompLHSTy,
11005         /*AllowBothBool*/getLangOpts().AltiVec,
11006         /*AllowBoolConversions*/getLangOpts().ZVector);
11007     if (CompLHSTy) *CompLHSTy = compType;
11008     return compType;
11009   }
11010 
11011   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11012       RHS.get()->getType()->isVLSTBuiltinType()) {
11013     QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc);
11014     if (CompLHSTy)
11015       *CompLHSTy = compType;
11016     return compType;
11017   }
11018 
11019   if (LHS.get()->getType()->isConstantMatrixType() ||
11020       RHS.get()->getType()->isConstantMatrixType()) {
11021     QualType compType =
11022         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11023     if (CompLHSTy)
11024       *CompLHSTy = compType;
11025     return compType;
11026   }
11027 
11028   QualType compType = UsualArithmeticConversions(
11029       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11030   if (LHS.isInvalid() || RHS.isInvalid())
11031     return QualType();
11032 
11033   // Enforce type constraints: C99 6.5.6p3.
11034 
11035   // Handle the common case first (both operands are arithmetic).
11036   if (!compType.isNull() && compType->isArithmeticType()) {
11037     if (CompLHSTy) *CompLHSTy = compType;
11038     return compType;
11039   }
11040 
11041   // Either ptr - int   or   ptr - ptr.
11042   if (LHS.get()->getType()->isAnyPointerType()) {
11043     QualType lpointee = LHS.get()->getType()->getPointeeType();
11044 
11045     // Diagnose bad cases where we step over interface counts.
11046     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11047         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11048       return QualType();
11049 
11050     // The result type of a pointer-int computation is the pointer type.
11051     if (RHS.get()->getType()->isIntegerType()) {
11052       // Subtracting from a null pointer should produce a warning.
11053       // The last argument to the diagnose call says this doesn't match the
11054       // GNU int-to-pointer idiom.
11055       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11056                                            Expr::NPC_ValueDependentIsNotNull)) {
11057         // In C++ adding zero to a null pointer is defined.
11058         Expr::EvalResult KnownVal;
11059         if (!getLangOpts().CPlusPlus ||
11060             (!RHS.get()->isValueDependent() &&
11061              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11062               KnownVal.Val.getInt() != 0))) {
11063           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11064         }
11065       }
11066 
11067       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11068         return QualType();
11069 
11070       // Check array bounds for pointer arithemtic
11071       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11072                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11073 
11074       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11075       return LHS.get()->getType();
11076     }
11077 
11078     // Handle pointer-pointer subtractions.
11079     if (const PointerType *RHSPTy
11080           = RHS.get()->getType()->getAs<PointerType>()) {
11081       QualType rpointee = RHSPTy->getPointeeType();
11082 
11083       if (getLangOpts().CPlusPlus) {
11084         // Pointee types must be the same: C++ [expr.add]
11085         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11086           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11087         }
11088       } else {
11089         // Pointee types must be compatible C99 6.5.6p3
11090         if (!Context.typesAreCompatible(
11091                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11092                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11093           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11094           return QualType();
11095         }
11096       }
11097 
11098       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11099                                                LHS.get(), RHS.get()))
11100         return QualType();
11101 
11102       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11103           Context, Expr::NPC_ValueDependentIsNotNull);
11104       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11105           Context, Expr::NPC_ValueDependentIsNotNull);
11106 
11107       // Subtracting nullptr or from nullptr is suspect
11108       if (LHSIsNullPtr)
11109         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11110       if (RHSIsNullPtr)
11111         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11112 
11113       // The pointee type may have zero size.  As an extension, a structure or
11114       // union may have zero size or an array may have zero length.  In this
11115       // case subtraction does not make sense.
11116       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11117         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11118         if (ElementSize.isZero()) {
11119           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11120             << rpointee.getUnqualifiedType()
11121             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11122         }
11123       }
11124 
11125       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11126       return Context.getPointerDiffType();
11127     }
11128   }
11129 
11130   return InvalidOperands(Loc, LHS, RHS);
11131 }
11132 
11133 static bool isScopedEnumerationType(QualType T) {
11134   if (const EnumType *ET = T->getAs<EnumType>())
11135     return ET->getDecl()->isScoped();
11136   return false;
11137 }
11138 
11139 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11140                                    SourceLocation Loc, BinaryOperatorKind Opc,
11141                                    QualType LHSType) {
11142   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11143   // so skip remaining warnings as we don't want to modify values within Sema.
11144   if (S.getLangOpts().OpenCL)
11145     return;
11146 
11147   // Check right/shifter operand
11148   Expr::EvalResult RHSResult;
11149   if (RHS.get()->isValueDependent() ||
11150       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11151     return;
11152   llvm::APSInt Right = RHSResult.Val.getInt();
11153 
11154   if (Right.isNegative()) {
11155     S.DiagRuntimeBehavior(Loc, RHS.get(),
11156                           S.PDiag(diag::warn_shift_negative)
11157                             << RHS.get()->getSourceRange());
11158     return;
11159   }
11160 
11161   QualType LHSExprType = LHS.get()->getType();
11162   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11163   if (LHSExprType->isBitIntType())
11164     LeftSize = S.Context.getIntWidth(LHSExprType);
11165   else if (LHSExprType->isFixedPointType()) {
11166     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11167     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11168   }
11169   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11170   if (Right.uge(LeftBits)) {
11171     S.DiagRuntimeBehavior(Loc, RHS.get(),
11172                           S.PDiag(diag::warn_shift_gt_typewidth)
11173                             << RHS.get()->getSourceRange());
11174     return;
11175   }
11176 
11177   // FIXME: We probably need to handle fixed point types specially here.
11178   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11179     return;
11180 
11181   // When left shifting an ICE which is signed, we can check for overflow which
11182   // according to C++ standards prior to C++2a has undefined behavior
11183   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11184   // more than the maximum value representable in the result type, so never
11185   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11186   // expression is still probably a bug.)
11187   Expr::EvalResult LHSResult;
11188   if (LHS.get()->isValueDependent() ||
11189       LHSType->hasUnsignedIntegerRepresentation() ||
11190       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11191     return;
11192   llvm::APSInt Left = LHSResult.Val.getInt();
11193 
11194   // If LHS does not have a signed type and non-negative value
11195   // then, the behavior is undefined before C++2a. Warn about it.
11196   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11197       !S.getLangOpts().CPlusPlus20) {
11198     S.DiagRuntimeBehavior(Loc, LHS.get(),
11199                           S.PDiag(diag::warn_shift_lhs_negative)
11200                             << LHS.get()->getSourceRange());
11201     return;
11202   }
11203 
11204   llvm::APInt ResultBits =
11205       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11206   if (LeftBits.uge(ResultBits))
11207     return;
11208   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11209   Result = Result.shl(Right);
11210 
11211   // Print the bit representation of the signed integer as an unsigned
11212   // hexadecimal number.
11213   SmallString<40> HexResult;
11214   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11215 
11216   // If we are only missing a sign bit, this is less likely to result in actual
11217   // bugs -- if the result is cast back to an unsigned type, it will have the
11218   // expected value. Thus we place this behind a different warning that can be
11219   // turned off separately if needed.
11220   if (LeftBits == ResultBits - 1) {
11221     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11222         << HexResult << LHSType
11223         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11224     return;
11225   }
11226 
11227   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11228     << HexResult.str() << Result.getMinSignedBits() << LHSType
11229     << Left.getBitWidth() << LHS.get()->getSourceRange()
11230     << RHS.get()->getSourceRange();
11231 }
11232 
11233 /// Return the resulting type when a vector is shifted
11234 ///        by a scalar or vector shift amount.
11235 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11236                                  SourceLocation Loc, bool IsCompAssign) {
11237   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11238   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11239       !LHS.get()->getType()->isVectorType()) {
11240     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11241       << RHS.get()->getType() << LHS.get()->getType()
11242       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11243     return QualType();
11244   }
11245 
11246   if (!IsCompAssign) {
11247     LHS = S.UsualUnaryConversions(LHS.get());
11248     if (LHS.isInvalid()) return QualType();
11249   }
11250 
11251   RHS = S.UsualUnaryConversions(RHS.get());
11252   if (RHS.isInvalid()) return QualType();
11253 
11254   QualType LHSType = LHS.get()->getType();
11255   // Note that LHS might be a scalar because the routine calls not only in
11256   // OpenCL case.
11257   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11258   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11259 
11260   // Note that RHS might not be a vector.
11261   QualType RHSType = RHS.get()->getType();
11262   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11263   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11264 
11265   // The operands need to be integers.
11266   if (!LHSEleType->isIntegerType()) {
11267     S.Diag(Loc, diag::err_typecheck_expect_int)
11268       << LHS.get()->getType() << LHS.get()->getSourceRange();
11269     return QualType();
11270   }
11271 
11272   if (!RHSEleType->isIntegerType()) {
11273     S.Diag(Loc, diag::err_typecheck_expect_int)
11274       << RHS.get()->getType() << RHS.get()->getSourceRange();
11275     return QualType();
11276   }
11277 
11278   if (!LHSVecTy) {
11279     assert(RHSVecTy);
11280     if (IsCompAssign)
11281       return RHSType;
11282     if (LHSEleType != RHSEleType) {
11283       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11284       LHSEleType = RHSEleType;
11285     }
11286     QualType VecTy =
11287         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11288     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11289     LHSType = VecTy;
11290   } else if (RHSVecTy) {
11291     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11292     // are applied component-wise. So if RHS is a vector, then ensure
11293     // that the number of elements is the same as LHS...
11294     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11295       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11296         << LHS.get()->getType() << RHS.get()->getType()
11297         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11298       return QualType();
11299     }
11300     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11301       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11302       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11303       if (LHSBT != RHSBT &&
11304           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11305         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11306             << LHS.get()->getType() << RHS.get()->getType()
11307             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11308       }
11309     }
11310   } else {
11311     // ...else expand RHS to match the number of elements in LHS.
11312     QualType VecTy =
11313       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11314     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11315   }
11316 
11317   return LHSType;
11318 }
11319 
11320 // C99 6.5.7
11321 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11322                                   SourceLocation Loc, BinaryOperatorKind Opc,
11323                                   bool IsCompAssign) {
11324   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11325 
11326   // Vector shifts promote their scalar inputs to vector type.
11327   if (LHS.get()->getType()->isVectorType() ||
11328       RHS.get()->getType()->isVectorType()) {
11329     if (LangOpts.ZVector) {
11330       // The shift operators for the z vector extensions work basically
11331       // like general shifts, except that neither the LHS nor the RHS is
11332       // allowed to be a "vector bool".
11333       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11334         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11335           return InvalidOperands(Loc, LHS, RHS);
11336       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11337         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11338           return InvalidOperands(Loc, LHS, RHS);
11339     }
11340     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11341   }
11342 
11343   // Shifts don't perform usual arithmetic conversions, they just do integer
11344   // promotions on each operand. C99 6.5.7p3
11345 
11346   // For the LHS, do usual unary conversions, but then reset them away
11347   // if this is a compound assignment.
11348   ExprResult OldLHS = LHS;
11349   LHS = UsualUnaryConversions(LHS.get());
11350   if (LHS.isInvalid())
11351     return QualType();
11352   QualType LHSType = LHS.get()->getType();
11353   if (IsCompAssign) LHS = OldLHS;
11354 
11355   // The RHS is simpler.
11356   RHS = UsualUnaryConversions(RHS.get());
11357   if (RHS.isInvalid())
11358     return QualType();
11359   QualType RHSType = RHS.get()->getType();
11360 
11361   // C99 6.5.7p2: Each of the operands shall have integer type.
11362   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11363   if ((!LHSType->isFixedPointOrIntegerType() &&
11364        !LHSType->hasIntegerRepresentation()) ||
11365       !RHSType->hasIntegerRepresentation())
11366     return InvalidOperands(Loc, LHS, RHS);
11367 
11368   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11369   // hasIntegerRepresentation() above instead of this.
11370   if (isScopedEnumerationType(LHSType) ||
11371       isScopedEnumerationType(RHSType)) {
11372     return InvalidOperands(Loc, LHS, RHS);
11373   }
11374   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11375 
11376   // "The type of the result is that of the promoted left operand."
11377   return LHSType;
11378 }
11379 
11380 /// Diagnose bad pointer comparisons.
11381 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11382                                               ExprResult &LHS, ExprResult &RHS,
11383                                               bool IsError) {
11384   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11385                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11386     << LHS.get()->getType() << RHS.get()->getType()
11387     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11388 }
11389 
11390 /// Returns false if the pointers are converted to a composite type,
11391 /// true otherwise.
11392 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11393                                            ExprResult &LHS, ExprResult &RHS) {
11394   // C++ [expr.rel]p2:
11395   //   [...] Pointer conversions (4.10) and qualification
11396   //   conversions (4.4) are performed on pointer operands (or on
11397   //   a pointer operand and a null pointer constant) to bring
11398   //   them to their composite pointer type. [...]
11399   //
11400   // C++ [expr.eq]p1 uses the same notion for (in)equality
11401   // comparisons of pointers.
11402 
11403   QualType LHSType = LHS.get()->getType();
11404   QualType RHSType = RHS.get()->getType();
11405   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11406          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11407 
11408   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11409   if (T.isNull()) {
11410     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11411         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11412       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11413     else
11414       S.InvalidOperands(Loc, LHS, RHS);
11415     return true;
11416   }
11417 
11418   return false;
11419 }
11420 
11421 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11422                                                     ExprResult &LHS,
11423                                                     ExprResult &RHS,
11424                                                     bool IsError) {
11425   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11426                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11427     << LHS.get()->getType() << RHS.get()->getType()
11428     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11429 }
11430 
11431 static bool isObjCObjectLiteral(ExprResult &E) {
11432   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11433   case Stmt::ObjCArrayLiteralClass:
11434   case Stmt::ObjCDictionaryLiteralClass:
11435   case Stmt::ObjCStringLiteralClass:
11436   case Stmt::ObjCBoxedExprClass:
11437     return true;
11438   default:
11439     // Note that ObjCBoolLiteral is NOT an object literal!
11440     return false;
11441   }
11442 }
11443 
11444 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11445   const ObjCObjectPointerType *Type =
11446     LHS->getType()->getAs<ObjCObjectPointerType>();
11447 
11448   // If this is not actually an Objective-C object, bail out.
11449   if (!Type)
11450     return false;
11451 
11452   // Get the LHS object's interface type.
11453   QualType InterfaceType = Type->getPointeeType();
11454 
11455   // If the RHS isn't an Objective-C object, bail out.
11456   if (!RHS->getType()->isObjCObjectPointerType())
11457     return false;
11458 
11459   // Try to find the -isEqual: method.
11460   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11461   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11462                                                       InterfaceType,
11463                                                       /*IsInstance=*/true);
11464   if (!Method) {
11465     if (Type->isObjCIdType()) {
11466       // For 'id', just check the global pool.
11467       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11468                                                   /*receiverId=*/true);
11469     } else {
11470       // Check protocols.
11471       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11472                                              /*IsInstance=*/true);
11473     }
11474   }
11475 
11476   if (!Method)
11477     return false;
11478 
11479   QualType T = Method->parameters()[0]->getType();
11480   if (!T->isObjCObjectPointerType())
11481     return false;
11482 
11483   QualType R = Method->getReturnType();
11484   if (!R->isScalarType())
11485     return false;
11486 
11487   return true;
11488 }
11489 
11490 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11491   FromE = FromE->IgnoreParenImpCasts();
11492   switch (FromE->getStmtClass()) {
11493     default:
11494       break;
11495     case Stmt::ObjCStringLiteralClass:
11496       // "string literal"
11497       return LK_String;
11498     case Stmt::ObjCArrayLiteralClass:
11499       // "array literal"
11500       return LK_Array;
11501     case Stmt::ObjCDictionaryLiteralClass:
11502       // "dictionary literal"
11503       return LK_Dictionary;
11504     case Stmt::BlockExprClass:
11505       return LK_Block;
11506     case Stmt::ObjCBoxedExprClass: {
11507       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11508       switch (Inner->getStmtClass()) {
11509         case Stmt::IntegerLiteralClass:
11510         case Stmt::FloatingLiteralClass:
11511         case Stmt::CharacterLiteralClass:
11512         case Stmt::ObjCBoolLiteralExprClass:
11513         case Stmt::CXXBoolLiteralExprClass:
11514           // "numeric literal"
11515           return LK_Numeric;
11516         case Stmt::ImplicitCastExprClass: {
11517           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11518           // Boolean literals can be represented by implicit casts.
11519           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11520             return LK_Numeric;
11521           break;
11522         }
11523         default:
11524           break;
11525       }
11526       return LK_Boxed;
11527     }
11528   }
11529   return LK_None;
11530 }
11531 
11532 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11533                                           ExprResult &LHS, ExprResult &RHS,
11534                                           BinaryOperator::Opcode Opc){
11535   Expr *Literal;
11536   Expr *Other;
11537   if (isObjCObjectLiteral(LHS)) {
11538     Literal = LHS.get();
11539     Other = RHS.get();
11540   } else {
11541     Literal = RHS.get();
11542     Other = LHS.get();
11543   }
11544 
11545   // Don't warn on comparisons against nil.
11546   Other = Other->IgnoreParenCasts();
11547   if (Other->isNullPointerConstant(S.getASTContext(),
11548                                    Expr::NPC_ValueDependentIsNotNull))
11549     return;
11550 
11551   // This should be kept in sync with warn_objc_literal_comparison.
11552   // LK_String should always be after the other literals, since it has its own
11553   // warning flag.
11554   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11555   assert(LiteralKind != Sema::LK_Block);
11556   if (LiteralKind == Sema::LK_None) {
11557     llvm_unreachable("Unknown Objective-C object literal kind");
11558   }
11559 
11560   if (LiteralKind == Sema::LK_String)
11561     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11562       << Literal->getSourceRange();
11563   else
11564     S.Diag(Loc, diag::warn_objc_literal_comparison)
11565       << LiteralKind << Literal->getSourceRange();
11566 
11567   if (BinaryOperator::isEqualityOp(Opc) &&
11568       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11569     SourceLocation Start = LHS.get()->getBeginLoc();
11570     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11571     CharSourceRange OpRange =
11572       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11573 
11574     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11575       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11576       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11577       << FixItHint::CreateInsertion(End, "]");
11578   }
11579 }
11580 
11581 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11582 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11583                                            ExprResult &RHS, SourceLocation Loc,
11584                                            BinaryOperatorKind Opc) {
11585   // Check that left hand side is !something.
11586   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11587   if (!UO || UO->getOpcode() != UO_LNot) return;
11588 
11589   // Only check if the right hand side is non-bool arithmetic type.
11590   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11591 
11592   // Make sure that the something in !something is not bool.
11593   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11594   if (SubExpr->isKnownToHaveBooleanValue()) return;
11595 
11596   // Emit warning.
11597   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11598   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11599       << Loc << IsBitwiseOp;
11600 
11601   // First note suggest !(x < y)
11602   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11603   SourceLocation FirstClose = RHS.get()->getEndLoc();
11604   FirstClose = S.getLocForEndOfToken(FirstClose);
11605   if (FirstClose.isInvalid())
11606     FirstOpen = SourceLocation();
11607   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11608       << IsBitwiseOp
11609       << FixItHint::CreateInsertion(FirstOpen, "(")
11610       << FixItHint::CreateInsertion(FirstClose, ")");
11611 
11612   // Second note suggests (!x) < y
11613   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11614   SourceLocation SecondClose = LHS.get()->getEndLoc();
11615   SecondClose = S.getLocForEndOfToken(SecondClose);
11616   if (SecondClose.isInvalid())
11617     SecondOpen = SourceLocation();
11618   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11619       << FixItHint::CreateInsertion(SecondOpen, "(")
11620       << FixItHint::CreateInsertion(SecondClose, ")");
11621 }
11622 
11623 // Returns true if E refers to a non-weak array.
11624 static bool checkForArray(const Expr *E) {
11625   const ValueDecl *D = nullptr;
11626   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11627     D = DR->getDecl();
11628   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11629     if (Mem->isImplicitAccess())
11630       D = Mem->getMemberDecl();
11631   }
11632   if (!D)
11633     return false;
11634   return D->getType()->isArrayType() && !D->isWeak();
11635 }
11636 
11637 /// Diagnose some forms of syntactically-obvious tautological comparison.
11638 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11639                                            Expr *LHS, Expr *RHS,
11640                                            BinaryOperatorKind Opc) {
11641   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11642   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11643 
11644   QualType LHSType = LHS->getType();
11645   QualType RHSType = RHS->getType();
11646   if (LHSType->hasFloatingRepresentation() ||
11647       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11648       S.inTemplateInstantiation())
11649     return;
11650 
11651   // Comparisons between two array types are ill-formed for operator<=>, so
11652   // we shouldn't emit any additional warnings about it.
11653   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11654     return;
11655 
11656   // For non-floating point types, check for self-comparisons of the form
11657   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11658   // often indicate logic errors in the program.
11659   //
11660   // NOTE: Don't warn about comparison expressions resulting from macro
11661   // expansion. Also don't warn about comparisons which are only self
11662   // comparisons within a template instantiation. The warnings should catch
11663   // obvious cases in the definition of the template anyways. The idea is to
11664   // warn when the typed comparison operator will always evaluate to the same
11665   // result.
11666 
11667   // Used for indexing into %select in warn_comparison_always
11668   enum {
11669     AlwaysConstant,
11670     AlwaysTrue,
11671     AlwaysFalse,
11672     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11673   };
11674 
11675   // C++2a [depr.array.comp]:
11676   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11677   //   operands of array type are deprecated.
11678   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11679       RHSStripped->getType()->isArrayType()) {
11680     S.Diag(Loc, diag::warn_depr_array_comparison)
11681         << LHS->getSourceRange() << RHS->getSourceRange()
11682         << LHSStripped->getType() << RHSStripped->getType();
11683     // Carry on to produce the tautological comparison warning, if this
11684     // expression is potentially-evaluated, we can resolve the array to a
11685     // non-weak declaration, and so on.
11686   }
11687 
11688   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11689     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11690       unsigned Result;
11691       switch (Opc) {
11692       case BO_EQ:
11693       case BO_LE:
11694       case BO_GE:
11695         Result = AlwaysTrue;
11696         break;
11697       case BO_NE:
11698       case BO_LT:
11699       case BO_GT:
11700         Result = AlwaysFalse;
11701         break;
11702       case BO_Cmp:
11703         Result = AlwaysEqual;
11704         break;
11705       default:
11706         Result = AlwaysConstant;
11707         break;
11708       }
11709       S.DiagRuntimeBehavior(Loc, nullptr,
11710                             S.PDiag(diag::warn_comparison_always)
11711                                 << 0 /*self-comparison*/
11712                                 << Result);
11713     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11714       // What is it always going to evaluate to?
11715       unsigned Result;
11716       switch (Opc) {
11717       case BO_EQ: // e.g. array1 == array2
11718         Result = AlwaysFalse;
11719         break;
11720       case BO_NE: // e.g. array1 != array2
11721         Result = AlwaysTrue;
11722         break;
11723       default: // e.g. array1 <= array2
11724         // The best we can say is 'a constant'
11725         Result = AlwaysConstant;
11726         break;
11727       }
11728       S.DiagRuntimeBehavior(Loc, nullptr,
11729                             S.PDiag(diag::warn_comparison_always)
11730                                 << 1 /*array comparison*/
11731                                 << Result);
11732     }
11733   }
11734 
11735   if (isa<CastExpr>(LHSStripped))
11736     LHSStripped = LHSStripped->IgnoreParenCasts();
11737   if (isa<CastExpr>(RHSStripped))
11738     RHSStripped = RHSStripped->IgnoreParenCasts();
11739 
11740   // Warn about comparisons against a string constant (unless the other
11741   // operand is null); the user probably wants string comparison function.
11742   Expr *LiteralString = nullptr;
11743   Expr *LiteralStringStripped = nullptr;
11744   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11745       !RHSStripped->isNullPointerConstant(S.Context,
11746                                           Expr::NPC_ValueDependentIsNull)) {
11747     LiteralString = LHS;
11748     LiteralStringStripped = LHSStripped;
11749   } else if ((isa<StringLiteral>(RHSStripped) ||
11750               isa<ObjCEncodeExpr>(RHSStripped)) &&
11751              !LHSStripped->isNullPointerConstant(S.Context,
11752                                           Expr::NPC_ValueDependentIsNull)) {
11753     LiteralString = RHS;
11754     LiteralStringStripped = RHSStripped;
11755   }
11756 
11757   if (LiteralString) {
11758     S.DiagRuntimeBehavior(Loc, nullptr,
11759                           S.PDiag(diag::warn_stringcompare)
11760                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11761                               << LiteralString->getSourceRange());
11762   }
11763 }
11764 
11765 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11766   switch (CK) {
11767   default: {
11768 #ifndef NDEBUG
11769     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11770                  << "\n";
11771 #endif
11772     llvm_unreachable("unhandled cast kind");
11773   }
11774   case CK_UserDefinedConversion:
11775     return ICK_Identity;
11776   case CK_LValueToRValue:
11777     return ICK_Lvalue_To_Rvalue;
11778   case CK_ArrayToPointerDecay:
11779     return ICK_Array_To_Pointer;
11780   case CK_FunctionToPointerDecay:
11781     return ICK_Function_To_Pointer;
11782   case CK_IntegralCast:
11783     return ICK_Integral_Conversion;
11784   case CK_FloatingCast:
11785     return ICK_Floating_Conversion;
11786   case CK_IntegralToFloating:
11787   case CK_FloatingToIntegral:
11788     return ICK_Floating_Integral;
11789   case CK_IntegralComplexCast:
11790   case CK_FloatingComplexCast:
11791   case CK_FloatingComplexToIntegralComplex:
11792   case CK_IntegralComplexToFloatingComplex:
11793     return ICK_Complex_Conversion;
11794   case CK_FloatingComplexToReal:
11795   case CK_FloatingRealToComplex:
11796   case CK_IntegralComplexToReal:
11797   case CK_IntegralRealToComplex:
11798     return ICK_Complex_Real;
11799   }
11800 }
11801 
11802 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11803                                              QualType FromType,
11804                                              SourceLocation Loc) {
11805   // Check for a narrowing implicit conversion.
11806   StandardConversionSequence SCS;
11807   SCS.setAsIdentityConversion();
11808   SCS.setToType(0, FromType);
11809   SCS.setToType(1, ToType);
11810   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11811     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11812 
11813   APValue PreNarrowingValue;
11814   QualType PreNarrowingType;
11815   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11816                                PreNarrowingType,
11817                                /*IgnoreFloatToIntegralConversion*/ true)) {
11818   case NK_Dependent_Narrowing:
11819     // Implicit conversion to a narrower type, but the expression is
11820     // value-dependent so we can't tell whether it's actually narrowing.
11821   case NK_Not_Narrowing:
11822     return false;
11823 
11824   case NK_Constant_Narrowing:
11825     // Implicit conversion to a narrower type, and the value is not a constant
11826     // expression.
11827     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11828         << /*Constant*/ 1
11829         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11830     return true;
11831 
11832   case NK_Variable_Narrowing:
11833     // Implicit conversion to a narrower type, and the value is not a constant
11834     // expression.
11835   case NK_Type_Narrowing:
11836     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11837         << /*Constant*/ 0 << FromType << ToType;
11838     // TODO: It's not a constant expression, but what if the user intended it
11839     // to be? Can we produce notes to help them figure out why it isn't?
11840     return true;
11841   }
11842   llvm_unreachable("unhandled case in switch");
11843 }
11844 
11845 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11846                                                          ExprResult &LHS,
11847                                                          ExprResult &RHS,
11848                                                          SourceLocation Loc) {
11849   QualType LHSType = LHS.get()->getType();
11850   QualType RHSType = RHS.get()->getType();
11851   // Dig out the original argument type and expression before implicit casts
11852   // were applied. These are the types/expressions we need to check the
11853   // [expr.spaceship] requirements against.
11854   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11855   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11856   QualType LHSStrippedType = LHSStripped.get()->getType();
11857   QualType RHSStrippedType = RHSStripped.get()->getType();
11858 
11859   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11860   // other is not, the program is ill-formed.
11861   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11862     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11863     return QualType();
11864   }
11865 
11866   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11867   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11868                     RHSStrippedType->isEnumeralType();
11869   if (NumEnumArgs == 1) {
11870     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11871     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11872     if (OtherTy->hasFloatingRepresentation()) {
11873       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11874       return QualType();
11875     }
11876   }
11877   if (NumEnumArgs == 2) {
11878     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11879     // type E, the operator yields the result of converting the operands
11880     // to the underlying type of E and applying <=> to the converted operands.
11881     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11882       S.InvalidOperands(Loc, LHS, RHS);
11883       return QualType();
11884     }
11885     QualType IntType =
11886         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11887     assert(IntType->isArithmeticType());
11888 
11889     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11890     // promote the boolean type, and all other promotable integer types, to
11891     // avoid this.
11892     if (IntType->isPromotableIntegerType())
11893       IntType = S.Context.getPromotedIntegerType(IntType);
11894 
11895     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11896     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11897     LHSType = RHSType = IntType;
11898   }
11899 
11900   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11901   // usual arithmetic conversions are applied to the operands.
11902   QualType Type =
11903       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11904   if (LHS.isInvalid() || RHS.isInvalid())
11905     return QualType();
11906   if (Type.isNull())
11907     return S.InvalidOperands(Loc, LHS, RHS);
11908 
11909   Optional<ComparisonCategoryType> CCT =
11910       getComparisonCategoryForBuiltinCmp(Type);
11911   if (!CCT)
11912     return S.InvalidOperands(Loc, LHS, RHS);
11913 
11914   bool HasNarrowing = checkThreeWayNarrowingConversion(
11915       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11916   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11917                                                    RHS.get()->getBeginLoc());
11918   if (HasNarrowing)
11919     return QualType();
11920 
11921   assert(!Type.isNull() && "composite type for <=> has not been set");
11922 
11923   return S.CheckComparisonCategoryType(
11924       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11925 }
11926 
11927 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11928                                                  ExprResult &RHS,
11929                                                  SourceLocation Loc,
11930                                                  BinaryOperatorKind Opc) {
11931   if (Opc == BO_Cmp)
11932     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11933 
11934   // C99 6.5.8p3 / C99 6.5.9p4
11935   QualType Type =
11936       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11937   if (LHS.isInvalid() || RHS.isInvalid())
11938     return QualType();
11939   if (Type.isNull())
11940     return S.InvalidOperands(Loc, LHS, RHS);
11941   assert(Type->isArithmeticType() || Type->isEnumeralType());
11942 
11943   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11944     return S.InvalidOperands(Loc, LHS, RHS);
11945 
11946   // Check for comparisons of floating point operands using != and ==.
11947   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11948     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11949 
11950   // The result of comparisons is 'bool' in C++, 'int' in C.
11951   return S.Context.getLogicalOperationType();
11952 }
11953 
11954 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11955   if (!NullE.get()->getType()->isAnyPointerType())
11956     return;
11957   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11958   if (!E.get()->getType()->isAnyPointerType() &&
11959       E.get()->isNullPointerConstant(Context,
11960                                      Expr::NPC_ValueDependentIsNotNull) ==
11961         Expr::NPCK_ZeroExpression) {
11962     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11963       if (CL->getValue() == 0)
11964         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11965             << NullValue
11966             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11967                                             NullValue ? "NULL" : "(void *)0");
11968     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11969         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11970         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11971         if (T == Context.CharTy)
11972           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11973               << NullValue
11974               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11975                                               NullValue ? "NULL" : "(void *)0");
11976       }
11977   }
11978 }
11979 
11980 // C99 6.5.8, C++ [expr.rel]
11981 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11982                                     SourceLocation Loc,
11983                                     BinaryOperatorKind Opc) {
11984   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11985   bool IsThreeWay = Opc == BO_Cmp;
11986   bool IsOrdered = IsRelational || IsThreeWay;
11987   auto IsAnyPointerType = [](ExprResult E) {
11988     QualType Ty = E.get()->getType();
11989     return Ty->isPointerType() || Ty->isMemberPointerType();
11990   };
11991 
11992   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11993   // type, array-to-pointer, ..., conversions are performed on both operands to
11994   // bring them to their composite type.
11995   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11996   // any type-related checks.
11997   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11998     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11999     if (LHS.isInvalid())
12000       return QualType();
12001     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12002     if (RHS.isInvalid())
12003       return QualType();
12004   } else {
12005     LHS = DefaultLvalueConversion(LHS.get());
12006     if (LHS.isInvalid())
12007       return QualType();
12008     RHS = DefaultLvalueConversion(RHS.get());
12009     if (RHS.isInvalid())
12010       return QualType();
12011   }
12012 
12013   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12014   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12015     CheckPtrComparisonWithNullChar(LHS, RHS);
12016     CheckPtrComparisonWithNullChar(RHS, LHS);
12017   }
12018 
12019   // Handle vector comparisons separately.
12020   if (LHS.get()->getType()->isVectorType() ||
12021       RHS.get()->getType()->isVectorType())
12022     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12023 
12024   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12025   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12026 
12027   QualType LHSType = LHS.get()->getType();
12028   QualType RHSType = RHS.get()->getType();
12029   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12030       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12031     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12032 
12033   const Expr::NullPointerConstantKind LHSNullKind =
12034       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12035   const Expr::NullPointerConstantKind RHSNullKind =
12036       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12037   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12038   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12039 
12040   auto computeResultTy = [&]() {
12041     if (Opc != BO_Cmp)
12042       return Context.getLogicalOperationType();
12043     assert(getLangOpts().CPlusPlus);
12044     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12045 
12046     QualType CompositeTy = LHS.get()->getType();
12047     assert(!CompositeTy->isReferenceType());
12048 
12049     Optional<ComparisonCategoryType> CCT =
12050         getComparisonCategoryForBuiltinCmp(CompositeTy);
12051     if (!CCT)
12052       return InvalidOperands(Loc, LHS, RHS);
12053 
12054     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12055       // P0946R0: Comparisons between a null pointer constant and an object
12056       // pointer result in std::strong_equality, which is ill-formed under
12057       // P1959R0.
12058       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12059           << (LHSIsNull ? LHS.get()->getSourceRange()
12060                         : RHS.get()->getSourceRange());
12061       return QualType();
12062     }
12063 
12064     return CheckComparisonCategoryType(
12065         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12066   };
12067 
12068   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12069     bool IsEquality = Opc == BO_EQ;
12070     if (RHSIsNull)
12071       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12072                                    RHS.get()->getSourceRange());
12073     else
12074       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12075                                    LHS.get()->getSourceRange());
12076   }
12077 
12078   if (IsOrdered && LHSType->isFunctionPointerType() &&
12079       RHSType->isFunctionPointerType()) {
12080     // Valid unless a relational comparison of function pointers
12081     bool IsError = Opc == BO_Cmp;
12082     auto DiagID =
12083         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12084         : getLangOpts().CPlusPlus
12085             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12086             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12087     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12088                       << RHS.get()->getSourceRange();
12089     if (IsError)
12090       return QualType();
12091   }
12092 
12093   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12094       (RHSType->isIntegerType() && !RHSIsNull)) {
12095     // Skip normal pointer conversion checks in this case; we have better
12096     // diagnostics for this below.
12097   } else if (getLangOpts().CPlusPlus) {
12098     // Equality comparison of a function pointer to a void pointer is invalid,
12099     // but we allow it as an extension.
12100     // FIXME: If we really want to allow this, should it be part of composite
12101     // pointer type computation so it works in conditionals too?
12102     if (!IsOrdered &&
12103         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12104          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12105       // This is a gcc extension compatibility comparison.
12106       // In a SFINAE context, we treat this as a hard error to maintain
12107       // conformance with the C++ standard.
12108       diagnoseFunctionPointerToVoidComparison(
12109           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12110 
12111       if (isSFINAEContext())
12112         return QualType();
12113 
12114       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12115       return computeResultTy();
12116     }
12117 
12118     // C++ [expr.eq]p2:
12119     //   If at least one operand is a pointer [...] bring them to their
12120     //   composite pointer type.
12121     // C++ [expr.spaceship]p6
12122     //  If at least one of the operands is of pointer type, [...] bring them
12123     //  to their composite pointer type.
12124     // C++ [expr.rel]p2:
12125     //   If both operands are pointers, [...] bring them to their composite
12126     //   pointer type.
12127     // For <=>, the only valid non-pointer types are arrays and functions, and
12128     // we already decayed those, so this is really the same as the relational
12129     // comparison rule.
12130     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12131             (IsOrdered ? 2 : 1) &&
12132         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12133                                          RHSType->isObjCObjectPointerType()))) {
12134       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12135         return QualType();
12136       return computeResultTy();
12137     }
12138   } else if (LHSType->isPointerType() &&
12139              RHSType->isPointerType()) { // C99 6.5.8p2
12140     // All of the following pointer-related warnings are GCC extensions, except
12141     // when handling null pointer constants.
12142     QualType LCanPointeeTy =
12143       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12144     QualType RCanPointeeTy =
12145       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12146 
12147     // C99 6.5.9p2 and C99 6.5.8p2
12148     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12149                                    RCanPointeeTy.getUnqualifiedType())) {
12150       if (IsRelational) {
12151         // Pointers both need to point to complete or incomplete types
12152         if ((LCanPointeeTy->isIncompleteType() !=
12153              RCanPointeeTy->isIncompleteType()) &&
12154             !getLangOpts().C11) {
12155           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12156               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12157               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12158               << RCanPointeeTy->isIncompleteType();
12159         }
12160       }
12161     } else if (!IsRelational &&
12162                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12163       // Valid unless comparison between non-null pointer and function pointer
12164       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12165           && !LHSIsNull && !RHSIsNull)
12166         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12167                                                 /*isError*/false);
12168     } else {
12169       // Invalid
12170       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12171     }
12172     if (LCanPointeeTy != RCanPointeeTy) {
12173       // Treat NULL constant as a special case in OpenCL.
12174       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12175         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12176           Diag(Loc,
12177                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12178               << LHSType << RHSType << 0 /* comparison */
12179               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12180         }
12181       }
12182       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12183       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12184       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12185                                                : CK_BitCast;
12186       if (LHSIsNull && !RHSIsNull)
12187         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12188       else
12189         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12190     }
12191     return computeResultTy();
12192   }
12193 
12194   if (getLangOpts().CPlusPlus) {
12195     // C++ [expr.eq]p4:
12196     //   Two operands of type std::nullptr_t or one operand of type
12197     //   std::nullptr_t and the other a null pointer constant compare equal.
12198     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12199       if (LHSType->isNullPtrType()) {
12200         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12201         return computeResultTy();
12202       }
12203       if (RHSType->isNullPtrType()) {
12204         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12205         return computeResultTy();
12206       }
12207     }
12208 
12209     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12210     // These aren't covered by the composite pointer type rules.
12211     if (!IsOrdered && RHSType->isNullPtrType() &&
12212         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12213       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12214       return computeResultTy();
12215     }
12216     if (!IsOrdered && LHSType->isNullPtrType() &&
12217         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12218       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12219       return computeResultTy();
12220     }
12221 
12222     if (IsRelational &&
12223         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12224          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12225       // HACK: Relational comparison of nullptr_t against a pointer type is
12226       // invalid per DR583, but we allow it within std::less<> and friends,
12227       // since otherwise common uses of it break.
12228       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12229       // friends to have std::nullptr_t overload candidates.
12230       DeclContext *DC = CurContext;
12231       if (isa<FunctionDecl>(DC))
12232         DC = DC->getParent();
12233       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12234         if (CTSD->isInStdNamespace() &&
12235             llvm::StringSwitch<bool>(CTSD->getName())
12236                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12237                 .Default(false)) {
12238           if (RHSType->isNullPtrType())
12239             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12240           else
12241             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12242           return computeResultTy();
12243         }
12244       }
12245     }
12246 
12247     // C++ [expr.eq]p2:
12248     //   If at least one operand is a pointer to member, [...] bring them to
12249     //   their composite pointer type.
12250     if (!IsOrdered &&
12251         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12252       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12253         return QualType();
12254       else
12255         return computeResultTy();
12256     }
12257   }
12258 
12259   // Handle block pointer types.
12260   if (!IsOrdered && LHSType->isBlockPointerType() &&
12261       RHSType->isBlockPointerType()) {
12262     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12263     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12264 
12265     if (!LHSIsNull && !RHSIsNull &&
12266         !Context.typesAreCompatible(lpointee, rpointee)) {
12267       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12268         << LHSType << RHSType << LHS.get()->getSourceRange()
12269         << RHS.get()->getSourceRange();
12270     }
12271     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12272     return computeResultTy();
12273   }
12274 
12275   // Allow block pointers to be compared with null pointer constants.
12276   if (!IsOrdered
12277       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12278           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12279     if (!LHSIsNull && !RHSIsNull) {
12280       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12281              ->getPointeeType()->isVoidType())
12282             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12283                 ->getPointeeType()->isVoidType())))
12284         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12285           << LHSType << RHSType << LHS.get()->getSourceRange()
12286           << RHS.get()->getSourceRange();
12287     }
12288     if (LHSIsNull && !RHSIsNull)
12289       LHS = ImpCastExprToType(LHS.get(), RHSType,
12290                               RHSType->isPointerType() ? CK_BitCast
12291                                 : CK_AnyPointerToBlockPointerCast);
12292     else
12293       RHS = ImpCastExprToType(RHS.get(), LHSType,
12294                               LHSType->isPointerType() ? CK_BitCast
12295                                 : CK_AnyPointerToBlockPointerCast);
12296     return computeResultTy();
12297   }
12298 
12299   if (LHSType->isObjCObjectPointerType() ||
12300       RHSType->isObjCObjectPointerType()) {
12301     const PointerType *LPT = LHSType->getAs<PointerType>();
12302     const PointerType *RPT = RHSType->getAs<PointerType>();
12303     if (LPT || RPT) {
12304       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12305       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12306 
12307       if (!LPtrToVoid && !RPtrToVoid &&
12308           !Context.typesAreCompatible(LHSType, RHSType)) {
12309         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12310                                           /*isError*/false);
12311       }
12312       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12313       // the RHS, but we have test coverage for this behavior.
12314       // FIXME: Consider using convertPointersToCompositeType in C++.
12315       if (LHSIsNull && !RHSIsNull) {
12316         Expr *E = LHS.get();
12317         if (getLangOpts().ObjCAutoRefCount)
12318           CheckObjCConversion(SourceRange(), RHSType, E,
12319                               CCK_ImplicitConversion);
12320         LHS = ImpCastExprToType(E, RHSType,
12321                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12322       }
12323       else {
12324         Expr *E = RHS.get();
12325         if (getLangOpts().ObjCAutoRefCount)
12326           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12327                               /*Diagnose=*/true,
12328                               /*DiagnoseCFAudited=*/false, Opc);
12329         RHS = ImpCastExprToType(E, LHSType,
12330                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12331       }
12332       return computeResultTy();
12333     }
12334     if (LHSType->isObjCObjectPointerType() &&
12335         RHSType->isObjCObjectPointerType()) {
12336       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12337         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12338                                           /*isError*/false);
12339       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12340         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12341 
12342       if (LHSIsNull && !RHSIsNull)
12343         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12344       else
12345         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12346       return computeResultTy();
12347     }
12348 
12349     if (!IsOrdered && LHSType->isBlockPointerType() &&
12350         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12351       LHS = ImpCastExprToType(LHS.get(), RHSType,
12352                               CK_BlockPointerToObjCPointerCast);
12353       return computeResultTy();
12354     } else if (!IsOrdered &&
12355                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12356                RHSType->isBlockPointerType()) {
12357       RHS = ImpCastExprToType(RHS.get(), LHSType,
12358                               CK_BlockPointerToObjCPointerCast);
12359       return computeResultTy();
12360     }
12361   }
12362   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12363       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12364     unsigned DiagID = 0;
12365     bool isError = false;
12366     if (LangOpts.DebuggerSupport) {
12367       // Under a debugger, allow the comparison of pointers to integers,
12368       // since users tend to want to compare addresses.
12369     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12370                (RHSIsNull && RHSType->isIntegerType())) {
12371       if (IsOrdered) {
12372         isError = getLangOpts().CPlusPlus;
12373         DiagID =
12374           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12375                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12376       }
12377     } else if (getLangOpts().CPlusPlus) {
12378       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12379       isError = true;
12380     } else if (IsOrdered)
12381       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12382     else
12383       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12384 
12385     if (DiagID) {
12386       Diag(Loc, DiagID)
12387         << LHSType << RHSType << LHS.get()->getSourceRange()
12388         << RHS.get()->getSourceRange();
12389       if (isError)
12390         return QualType();
12391     }
12392 
12393     if (LHSType->isIntegerType())
12394       LHS = ImpCastExprToType(LHS.get(), RHSType,
12395                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12396     else
12397       RHS = ImpCastExprToType(RHS.get(), LHSType,
12398                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12399     return computeResultTy();
12400   }
12401 
12402   // Handle block pointers.
12403   if (!IsOrdered && RHSIsNull
12404       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12405     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12406     return computeResultTy();
12407   }
12408   if (!IsOrdered && LHSIsNull
12409       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12410     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12411     return computeResultTy();
12412   }
12413 
12414   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12415     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12416       return computeResultTy();
12417     }
12418 
12419     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12420       return computeResultTy();
12421     }
12422 
12423     if (LHSIsNull && RHSType->isQueueT()) {
12424       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12425       return computeResultTy();
12426     }
12427 
12428     if (LHSType->isQueueT() && RHSIsNull) {
12429       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12430       return computeResultTy();
12431     }
12432   }
12433 
12434   return InvalidOperands(Loc, LHS, RHS);
12435 }
12436 
12437 // Return a signed ext_vector_type that is of identical size and number of
12438 // elements. For floating point vectors, return an integer type of identical
12439 // size and number of elements. In the non ext_vector_type case, search from
12440 // the largest type to the smallest type to avoid cases where long long == long,
12441 // where long gets picked over long long.
12442 QualType Sema::GetSignedVectorType(QualType V) {
12443   const VectorType *VTy = V->castAs<VectorType>();
12444   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12445 
12446   if (isa<ExtVectorType>(VTy)) {
12447     if (TypeSize == Context.getTypeSize(Context.CharTy))
12448       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12449     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12450       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12451     if (TypeSize == Context.getTypeSize(Context.IntTy))
12452       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12453     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12454       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12455     if (TypeSize == Context.getTypeSize(Context.LongTy))
12456       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12457     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12458            "Unhandled vector element size in vector compare");
12459     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12460   }
12461 
12462   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12463     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12464                                  VectorType::GenericVector);
12465   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12466     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12467                                  VectorType::GenericVector);
12468   if (TypeSize == Context.getTypeSize(Context.LongTy))
12469     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12470                                  VectorType::GenericVector);
12471   if (TypeSize == Context.getTypeSize(Context.IntTy))
12472     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12473                                  VectorType::GenericVector);
12474   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12475     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12476                                  VectorType::GenericVector);
12477   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12478          "Unhandled vector element size in vector compare");
12479   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12480                                VectorType::GenericVector);
12481 }
12482 
12483 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12484 /// operates on extended vector types.  Instead of producing an IntTy result,
12485 /// like a scalar comparison, a vector comparison produces a vector of integer
12486 /// types.
12487 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12488                                           SourceLocation Loc,
12489                                           BinaryOperatorKind Opc) {
12490   if (Opc == BO_Cmp) {
12491     Diag(Loc, diag::err_three_way_vector_comparison);
12492     return QualType();
12493   }
12494 
12495   // Check to make sure we're operating on vectors of the same type and width,
12496   // Allowing one side to be a scalar of element type.
12497   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12498                               /*AllowBothBool*/true,
12499                               /*AllowBoolConversions*/getLangOpts().ZVector);
12500   if (vType.isNull())
12501     return vType;
12502 
12503   QualType LHSType = LHS.get()->getType();
12504 
12505   // Determine the return type of a vector compare. By default clang will return
12506   // a scalar for all vector compares except vector bool and vector pixel.
12507   // With the gcc compiler we will always return a vector type and with the xl
12508   // compiler we will always return a scalar type. This switch allows choosing
12509   // which behavior is prefered.
12510   if (getLangOpts().AltiVec) {
12511     switch (getLangOpts().getAltivecSrcCompat()) {
12512     case LangOptions::AltivecSrcCompatKind::Mixed:
12513       // If AltiVec, the comparison results in a numeric type, i.e.
12514       // bool for C++, int for C
12515       if (vType->castAs<VectorType>()->getVectorKind() ==
12516           VectorType::AltiVecVector)
12517         return Context.getLogicalOperationType();
12518       else
12519         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12520       break;
12521     case LangOptions::AltivecSrcCompatKind::GCC:
12522       // For GCC we always return the vector type.
12523       break;
12524     case LangOptions::AltivecSrcCompatKind::XL:
12525       return Context.getLogicalOperationType();
12526       break;
12527     }
12528   }
12529 
12530   // For non-floating point types, check for self-comparisons of the form
12531   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12532   // often indicate logic errors in the program.
12533   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12534 
12535   // Check for comparisons of floating point operands using != and ==.
12536   if (BinaryOperator::isEqualityOp(Opc) &&
12537       LHSType->hasFloatingRepresentation()) {
12538     assert(RHS.get()->getType()->hasFloatingRepresentation());
12539     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12540   }
12541 
12542   // Return a signed type for the vector.
12543   return GetSignedVectorType(vType);
12544 }
12545 
12546 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12547                                     const ExprResult &XorRHS,
12548                                     const SourceLocation Loc) {
12549   // Do not diagnose macros.
12550   if (Loc.isMacroID())
12551     return;
12552 
12553   // Do not diagnose if both LHS and RHS are macros.
12554   if (XorLHS.get()->getExprLoc().isMacroID() &&
12555       XorRHS.get()->getExprLoc().isMacroID())
12556     return;
12557 
12558   bool Negative = false;
12559   bool ExplicitPlus = false;
12560   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12561   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12562 
12563   if (!LHSInt)
12564     return;
12565   if (!RHSInt) {
12566     // Check negative literals.
12567     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12568       UnaryOperatorKind Opc = UO->getOpcode();
12569       if (Opc != UO_Minus && Opc != UO_Plus)
12570         return;
12571       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12572       if (!RHSInt)
12573         return;
12574       Negative = (Opc == UO_Minus);
12575       ExplicitPlus = !Negative;
12576     } else {
12577       return;
12578     }
12579   }
12580 
12581   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12582   llvm::APInt RightSideValue = RHSInt->getValue();
12583   if (LeftSideValue != 2 && LeftSideValue != 10)
12584     return;
12585 
12586   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12587     return;
12588 
12589   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12590       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12591   llvm::StringRef ExprStr =
12592       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12593 
12594   CharSourceRange XorRange =
12595       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12596   llvm::StringRef XorStr =
12597       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12598   // Do not diagnose if xor keyword/macro is used.
12599   if (XorStr == "xor")
12600     return;
12601 
12602   std::string LHSStr = std::string(Lexer::getSourceText(
12603       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12604       S.getSourceManager(), S.getLangOpts()));
12605   std::string RHSStr = std::string(Lexer::getSourceText(
12606       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12607       S.getSourceManager(), S.getLangOpts()));
12608 
12609   if (Negative) {
12610     RightSideValue = -RightSideValue;
12611     RHSStr = "-" + RHSStr;
12612   } else if (ExplicitPlus) {
12613     RHSStr = "+" + RHSStr;
12614   }
12615 
12616   StringRef LHSStrRef = LHSStr;
12617   StringRef RHSStrRef = RHSStr;
12618   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12619   // literals.
12620   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12621       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12622       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12623       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12624       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12625       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12626       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12627     return;
12628 
12629   bool SuggestXor =
12630       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12631   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12632   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12633   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12634     std::string SuggestedExpr = "1 << " + RHSStr;
12635     bool Overflow = false;
12636     llvm::APInt One = (LeftSideValue - 1);
12637     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12638     if (Overflow) {
12639       if (RightSideIntValue < 64)
12640         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12641             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12642             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12643       else if (RightSideIntValue == 64)
12644         S.Diag(Loc, diag::warn_xor_used_as_pow)
12645             << ExprStr << toString(XorValue, 10, true);
12646       else
12647         return;
12648     } else {
12649       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12650           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12651           << toString(PowValue, 10, true)
12652           << FixItHint::CreateReplacement(
12653                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12654     }
12655 
12656     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12657         << ("0x2 ^ " + RHSStr) << SuggestXor;
12658   } else if (LeftSideValue == 10) {
12659     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12660     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12661         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12662         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12663     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12664         << ("0xA ^ " + RHSStr) << SuggestXor;
12665   }
12666 }
12667 
12668 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12669                                           SourceLocation Loc) {
12670   // Ensure that either both operands are of the same vector type, or
12671   // one operand is of a vector type and the other is of its element type.
12672   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12673                                        /*AllowBothBool*/true,
12674                                        /*AllowBoolConversions*/false);
12675   if (vType.isNull())
12676     return InvalidOperands(Loc, LHS, RHS);
12677   if (getLangOpts().OpenCL &&
12678       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12679       vType->hasFloatingRepresentation())
12680     return InvalidOperands(Loc, LHS, RHS);
12681   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12682   //        usage of the logical operators && and || with vectors in C. This
12683   //        check could be notionally dropped.
12684   if (!getLangOpts().CPlusPlus &&
12685       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12686     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12687 
12688   return GetSignedVectorType(LHS.get()->getType());
12689 }
12690 
12691 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12692                                               SourceLocation Loc,
12693                                               bool IsCompAssign) {
12694   if (!IsCompAssign) {
12695     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12696     if (LHS.isInvalid())
12697       return QualType();
12698   }
12699   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12700   if (RHS.isInvalid())
12701     return QualType();
12702 
12703   // For conversion purposes, we ignore any qualifiers.
12704   // For example, "const float" and "float" are equivalent.
12705   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12706   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12707 
12708   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12709   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12710   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12711 
12712   if (Context.hasSameType(LHSType, RHSType))
12713     return LHSType;
12714 
12715   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12716   // case we have to return InvalidOperands.
12717   ExprResult OriginalLHS = LHS;
12718   ExprResult OriginalRHS = RHS;
12719   if (LHSMatType && !RHSMatType) {
12720     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12721     if (!RHS.isInvalid())
12722       return LHSType;
12723 
12724     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12725   }
12726 
12727   if (!LHSMatType && RHSMatType) {
12728     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12729     if (!LHS.isInvalid())
12730       return RHSType;
12731     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12732   }
12733 
12734   return InvalidOperands(Loc, LHS, RHS);
12735 }
12736 
12737 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12738                                            SourceLocation Loc,
12739                                            bool IsCompAssign) {
12740   if (!IsCompAssign) {
12741     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12742     if (LHS.isInvalid())
12743       return QualType();
12744   }
12745   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12746   if (RHS.isInvalid())
12747     return QualType();
12748 
12749   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12750   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12751   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12752 
12753   if (LHSMatType && RHSMatType) {
12754     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12755       return InvalidOperands(Loc, LHS, RHS);
12756 
12757     if (!Context.hasSameType(LHSMatType->getElementType(),
12758                              RHSMatType->getElementType()))
12759       return InvalidOperands(Loc, LHS, RHS);
12760 
12761     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12762                                          LHSMatType->getNumRows(),
12763                                          RHSMatType->getNumColumns());
12764   }
12765   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12766 }
12767 
12768 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12769                                            SourceLocation Loc,
12770                                            BinaryOperatorKind Opc) {
12771   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12772 
12773   bool IsCompAssign =
12774       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12775 
12776   if (LHS.get()->getType()->isVectorType() ||
12777       RHS.get()->getType()->isVectorType()) {
12778     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12779         RHS.get()->getType()->hasIntegerRepresentation())
12780       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12781                         /*AllowBothBool*/true,
12782                         /*AllowBoolConversions*/getLangOpts().ZVector);
12783     return InvalidOperands(Loc, LHS, RHS);
12784   }
12785 
12786   if (Opc == BO_And)
12787     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12788 
12789   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12790       RHS.get()->getType()->hasFloatingRepresentation())
12791     return InvalidOperands(Loc, LHS, RHS);
12792 
12793   ExprResult LHSResult = LHS, RHSResult = RHS;
12794   QualType compType = UsualArithmeticConversions(
12795       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12796   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12797     return QualType();
12798   LHS = LHSResult.get();
12799   RHS = RHSResult.get();
12800 
12801   if (Opc == BO_Xor)
12802     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12803 
12804   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12805     return compType;
12806   return InvalidOperands(Loc, LHS, RHS);
12807 }
12808 
12809 // C99 6.5.[13,14]
12810 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12811                                            SourceLocation Loc,
12812                                            BinaryOperatorKind Opc) {
12813   // Check vector operands differently.
12814   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12815     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12816 
12817   bool EnumConstantInBoolContext = false;
12818   for (const ExprResult &HS : {LHS, RHS}) {
12819     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12820       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12821       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12822         EnumConstantInBoolContext = true;
12823     }
12824   }
12825 
12826   if (EnumConstantInBoolContext)
12827     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12828 
12829   // Diagnose cases where the user write a logical and/or but probably meant a
12830   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12831   // is a constant.
12832   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12833       !LHS.get()->getType()->isBooleanType() &&
12834       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12835       // Don't warn in macros or template instantiations.
12836       !Loc.isMacroID() && !inTemplateInstantiation()) {
12837     // If the RHS can be constant folded, and if it constant folds to something
12838     // that isn't 0 or 1 (which indicate a potential logical operation that
12839     // happened to fold to true/false) then warn.
12840     // Parens on the RHS are ignored.
12841     Expr::EvalResult EVResult;
12842     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12843       llvm::APSInt Result = EVResult.Val.getInt();
12844       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12845            !RHS.get()->getExprLoc().isMacroID()) ||
12846           (Result != 0 && Result != 1)) {
12847         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12848           << RHS.get()->getSourceRange()
12849           << (Opc == BO_LAnd ? "&&" : "||");
12850         // Suggest replacing the logical operator with the bitwise version
12851         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12852             << (Opc == BO_LAnd ? "&" : "|")
12853             << FixItHint::CreateReplacement(SourceRange(
12854                                                  Loc, getLocForEndOfToken(Loc)),
12855                                             Opc == BO_LAnd ? "&" : "|");
12856         if (Opc == BO_LAnd)
12857           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12858           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12859               << FixItHint::CreateRemoval(
12860                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12861                                  RHS.get()->getEndLoc()));
12862       }
12863     }
12864   }
12865 
12866   if (!Context.getLangOpts().CPlusPlus) {
12867     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12868     // not operate on the built-in scalar and vector float types.
12869     if (Context.getLangOpts().OpenCL &&
12870         Context.getLangOpts().OpenCLVersion < 120) {
12871       if (LHS.get()->getType()->isFloatingType() ||
12872           RHS.get()->getType()->isFloatingType())
12873         return InvalidOperands(Loc, LHS, RHS);
12874     }
12875 
12876     LHS = UsualUnaryConversions(LHS.get());
12877     if (LHS.isInvalid())
12878       return QualType();
12879 
12880     RHS = UsualUnaryConversions(RHS.get());
12881     if (RHS.isInvalid())
12882       return QualType();
12883 
12884     if (!LHS.get()->getType()->isScalarType() ||
12885         !RHS.get()->getType()->isScalarType())
12886       return InvalidOperands(Loc, LHS, RHS);
12887 
12888     return Context.IntTy;
12889   }
12890 
12891   // The following is safe because we only use this method for
12892   // non-overloadable operands.
12893 
12894   // C++ [expr.log.and]p1
12895   // C++ [expr.log.or]p1
12896   // The operands are both contextually converted to type bool.
12897   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12898   if (LHSRes.isInvalid())
12899     return InvalidOperands(Loc, LHS, RHS);
12900   LHS = LHSRes;
12901 
12902   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12903   if (RHSRes.isInvalid())
12904     return InvalidOperands(Loc, LHS, RHS);
12905   RHS = RHSRes;
12906 
12907   // C++ [expr.log.and]p2
12908   // C++ [expr.log.or]p2
12909   // The result is a bool.
12910   return Context.BoolTy;
12911 }
12912 
12913 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12914   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12915   if (!ME) return false;
12916   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12917   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12918       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12919   if (!Base) return false;
12920   return Base->getMethodDecl() != nullptr;
12921 }
12922 
12923 /// Is the given expression (which must be 'const') a reference to a
12924 /// variable which was originally non-const, but which has become
12925 /// 'const' due to being captured within a block?
12926 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12927 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12928   assert(E->isLValue() && E->getType().isConstQualified());
12929   E = E->IgnoreParens();
12930 
12931   // Must be a reference to a declaration from an enclosing scope.
12932   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12933   if (!DRE) return NCCK_None;
12934   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12935 
12936   // The declaration must be a variable which is not declared 'const'.
12937   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12938   if (!var) return NCCK_None;
12939   if (var->getType().isConstQualified()) return NCCK_None;
12940   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12941 
12942   // Decide whether the first capture was for a block or a lambda.
12943   DeclContext *DC = S.CurContext, *Prev = nullptr;
12944   // Decide whether the first capture was for a block or a lambda.
12945   while (DC) {
12946     // For init-capture, it is possible that the variable belongs to the
12947     // template pattern of the current context.
12948     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12949       if (var->isInitCapture() &&
12950           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12951         break;
12952     if (DC == var->getDeclContext())
12953       break;
12954     Prev = DC;
12955     DC = DC->getParent();
12956   }
12957   // Unless we have an init-capture, we've gone one step too far.
12958   if (!var->isInitCapture())
12959     DC = Prev;
12960   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12961 }
12962 
12963 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12964   Ty = Ty.getNonReferenceType();
12965   if (IsDereference && Ty->isPointerType())
12966     Ty = Ty->getPointeeType();
12967   return !Ty.isConstQualified();
12968 }
12969 
12970 // Update err_typecheck_assign_const and note_typecheck_assign_const
12971 // when this enum is changed.
12972 enum {
12973   ConstFunction,
12974   ConstVariable,
12975   ConstMember,
12976   ConstMethod,
12977   NestedConstMember,
12978   ConstUnknown,  // Keep as last element
12979 };
12980 
12981 /// Emit the "read-only variable not assignable" error and print notes to give
12982 /// more information about why the variable is not assignable, such as pointing
12983 /// to the declaration of a const variable, showing that a method is const, or
12984 /// that the function is returning a const reference.
12985 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12986                                     SourceLocation Loc) {
12987   SourceRange ExprRange = E->getSourceRange();
12988 
12989   // Only emit one error on the first const found.  All other consts will emit
12990   // a note to the error.
12991   bool DiagnosticEmitted = false;
12992 
12993   // Track if the current expression is the result of a dereference, and if the
12994   // next checked expression is the result of a dereference.
12995   bool IsDereference = false;
12996   bool NextIsDereference = false;
12997 
12998   // Loop to process MemberExpr chains.
12999   while (true) {
13000     IsDereference = NextIsDereference;
13001 
13002     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13003     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13004       NextIsDereference = ME->isArrow();
13005       const ValueDecl *VD = ME->getMemberDecl();
13006       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13007         // Mutable fields can be modified even if the class is const.
13008         if (Field->isMutable()) {
13009           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13010           break;
13011         }
13012 
13013         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13014           if (!DiagnosticEmitted) {
13015             S.Diag(Loc, diag::err_typecheck_assign_const)
13016                 << ExprRange << ConstMember << false /*static*/ << Field
13017                 << Field->getType();
13018             DiagnosticEmitted = true;
13019           }
13020           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13021               << ConstMember << false /*static*/ << Field << Field->getType()
13022               << Field->getSourceRange();
13023         }
13024         E = ME->getBase();
13025         continue;
13026       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13027         if (VDecl->getType().isConstQualified()) {
13028           if (!DiagnosticEmitted) {
13029             S.Diag(Loc, diag::err_typecheck_assign_const)
13030                 << ExprRange << ConstMember << true /*static*/ << VDecl
13031                 << VDecl->getType();
13032             DiagnosticEmitted = true;
13033           }
13034           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13035               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13036               << VDecl->getSourceRange();
13037         }
13038         // Static fields do not inherit constness from parents.
13039         break;
13040       }
13041       break; // End MemberExpr
13042     } else if (const ArraySubscriptExpr *ASE =
13043                    dyn_cast<ArraySubscriptExpr>(E)) {
13044       E = ASE->getBase()->IgnoreParenImpCasts();
13045       continue;
13046     } else if (const ExtVectorElementExpr *EVE =
13047                    dyn_cast<ExtVectorElementExpr>(E)) {
13048       E = EVE->getBase()->IgnoreParenImpCasts();
13049       continue;
13050     }
13051     break;
13052   }
13053 
13054   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13055     // Function calls
13056     const FunctionDecl *FD = CE->getDirectCallee();
13057     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13058       if (!DiagnosticEmitted) {
13059         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13060                                                       << ConstFunction << FD;
13061         DiagnosticEmitted = true;
13062       }
13063       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13064              diag::note_typecheck_assign_const)
13065           << ConstFunction << FD << FD->getReturnType()
13066           << FD->getReturnTypeSourceRange();
13067     }
13068   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13069     // Point to variable declaration.
13070     if (const ValueDecl *VD = DRE->getDecl()) {
13071       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13072         if (!DiagnosticEmitted) {
13073           S.Diag(Loc, diag::err_typecheck_assign_const)
13074               << ExprRange << ConstVariable << VD << VD->getType();
13075           DiagnosticEmitted = true;
13076         }
13077         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13078             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13079       }
13080     }
13081   } else if (isa<CXXThisExpr>(E)) {
13082     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13083       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13084         if (MD->isConst()) {
13085           if (!DiagnosticEmitted) {
13086             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13087                                                           << ConstMethod << MD;
13088             DiagnosticEmitted = true;
13089           }
13090           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13091               << ConstMethod << MD << MD->getSourceRange();
13092         }
13093       }
13094     }
13095   }
13096 
13097   if (DiagnosticEmitted)
13098     return;
13099 
13100   // Can't determine a more specific message, so display the generic error.
13101   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13102 }
13103 
13104 enum OriginalExprKind {
13105   OEK_Variable,
13106   OEK_Member,
13107   OEK_LValue
13108 };
13109 
13110 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13111                                          const RecordType *Ty,
13112                                          SourceLocation Loc, SourceRange Range,
13113                                          OriginalExprKind OEK,
13114                                          bool &DiagnosticEmitted) {
13115   std::vector<const RecordType *> RecordTypeList;
13116   RecordTypeList.push_back(Ty);
13117   unsigned NextToCheckIndex = 0;
13118   // We walk the record hierarchy breadth-first to ensure that we print
13119   // diagnostics in field nesting order.
13120   while (RecordTypeList.size() > NextToCheckIndex) {
13121     bool IsNested = NextToCheckIndex > 0;
13122     for (const FieldDecl *Field :
13123          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13124       // First, check every field for constness.
13125       QualType FieldTy = Field->getType();
13126       if (FieldTy.isConstQualified()) {
13127         if (!DiagnosticEmitted) {
13128           S.Diag(Loc, diag::err_typecheck_assign_const)
13129               << Range << NestedConstMember << OEK << VD
13130               << IsNested << Field;
13131           DiagnosticEmitted = true;
13132         }
13133         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13134             << NestedConstMember << IsNested << Field
13135             << FieldTy << Field->getSourceRange();
13136       }
13137 
13138       // Then we append it to the list to check next in order.
13139       FieldTy = FieldTy.getCanonicalType();
13140       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13141         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13142           RecordTypeList.push_back(FieldRecTy);
13143       }
13144     }
13145     ++NextToCheckIndex;
13146   }
13147 }
13148 
13149 /// Emit an error for the case where a record we are trying to assign to has a
13150 /// const-qualified field somewhere in its hierarchy.
13151 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13152                                          SourceLocation Loc) {
13153   QualType Ty = E->getType();
13154   assert(Ty->isRecordType() && "lvalue was not record?");
13155   SourceRange Range = E->getSourceRange();
13156   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13157   bool DiagEmitted = false;
13158 
13159   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13160     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13161             Range, OEK_Member, DiagEmitted);
13162   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13163     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13164             Range, OEK_Variable, DiagEmitted);
13165   else
13166     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13167             Range, OEK_LValue, DiagEmitted);
13168   if (!DiagEmitted)
13169     DiagnoseConstAssignment(S, E, Loc);
13170 }
13171 
13172 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13173 /// emit an error and return true.  If so, return false.
13174 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13175   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13176 
13177   S.CheckShadowingDeclModification(E, Loc);
13178 
13179   SourceLocation OrigLoc = Loc;
13180   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13181                                                               &Loc);
13182   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13183     IsLV = Expr::MLV_InvalidMessageExpression;
13184   if (IsLV == Expr::MLV_Valid)
13185     return false;
13186 
13187   unsigned DiagID = 0;
13188   bool NeedType = false;
13189   switch (IsLV) { // C99 6.5.16p2
13190   case Expr::MLV_ConstQualified:
13191     // Use a specialized diagnostic when we're assigning to an object
13192     // from an enclosing function or block.
13193     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13194       if (NCCK == NCCK_Block)
13195         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13196       else
13197         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13198       break;
13199     }
13200 
13201     // In ARC, use some specialized diagnostics for occasions where we
13202     // infer 'const'.  These are always pseudo-strong variables.
13203     if (S.getLangOpts().ObjCAutoRefCount) {
13204       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13205       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13206         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13207 
13208         // Use the normal diagnostic if it's pseudo-__strong but the
13209         // user actually wrote 'const'.
13210         if (var->isARCPseudoStrong() &&
13211             (!var->getTypeSourceInfo() ||
13212              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13213           // There are three pseudo-strong cases:
13214           //  - self
13215           ObjCMethodDecl *method = S.getCurMethodDecl();
13216           if (method && var == method->getSelfDecl()) {
13217             DiagID = method->isClassMethod()
13218               ? diag::err_typecheck_arc_assign_self_class_method
13219               : diag::err_typecheck_arc_assign_self;
13220 
13221           //  - Objective-C externally_retained attribute.
13222           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13223                      isa<ParmVarDecl>(var)) {
13224             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13225 
13226           //  - fast enumeration variables
13227           } else {
13228             DiagID = diag::err_typecheck_arr_assign_enumeration;
13229           }
13230 
13231           SourceRange Assign;
13232           if (Loc != OrigLoc)
13233             Assign = SourceRange(OrigLoc, OrigLoc);
13234           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13235           // We need to preserve the AST regardless, so migration tool
13236           // can do its job.
13237           return false;
13238         }
13239       }
13240     }
13241 
13242     // If none of the special cases above are triggered, then this is a
13243     // simple const assignment.
13244     if (DiagID == 0) {
13245       DiagnoseConstAssignment(S, E, Loc);
13246       return true;
13247     }
13248 
13249     break;
13250   case Expr::MLV_ConstAddrSpace:
13251     DiagnoseConstAssignment(S, E, Loc);
13252     return true;
13253   case Expr::MLV_ConstQualifiedField:
13254     DiagnoseRecursiveConstFields(S, E, Loc);
13255     return true;
13256   case Expr::MLV_ArrayType:
13257   case Expr::MLV_ArrayTemporary:
13258     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13259     NeedType = true;
13260     break;
13261   case Expr::MLV_NotObjectType:
13262     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13263     NeedType = true;
13264     break;
13265   case Expr::MLV_LValueCast:
13266     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13267     break;
13268   case Expr::MLV_Valid:
13269     llvm_unreachable("did not take early return for MLV_Valid");
13270   case Expr::MLV_InvalidExpression:
13271   case Expr::MLV_MemberFunction:
13272   case Expr::MLV_ClassTemporary:
13273     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13274     break;
13275   case Expr::MLV_IncompleteType:
13276   case Expr::MLV_IncompleteVoidType:
13277     return S.RequireCompleteType(Loc, E->getType(),
13278              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13279   case Expr::MLV_DuplicateVectorComponents:
13280     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13281     break;
13282   case Expr::MLV_NoSetterProperty:
13283     llvm_unreachable("readonly properties should be processed differently");
13284   case Expr::MLV_InvalidMessageExpression:
13285     DiagID = diag::err_readonly_message_assignment;
13286     break;
13287   case Expr::MLV_SubObjCPropertySetting:
13288     DiagID = diag::err_no_subobject_property_setting;
13289     break;
13290   }
13291 
13292   SourceRange Assign;
13293   if (Loc != OrigLoc)
13294     Assign = SourceRange(OrigLoc, OrigLoc);
13295   if (NeedType)
13296     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13297   else
13298     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13299   return true;
13300 }
13301 
13302 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13303                                          SourceLocation Loc,
13304                                          Sema &Sema) {
13305   if (Sema.inTemplateInstantiation())
13306     return;
13307   if (Sema.isUnevaluatedContext())
13308     return;
13309   if (Loc.isInvalid() || Loc.isMacroID())
13310     return;
13311   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13312     return;
13313 
13314   // C / C++ fields
13315   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13316   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13317   if (ML && MR) {
13318     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13319       return;
13320     const ValueDecl *LHSDecl =
13321         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13322     const ValueDecl *RHSDecl =
13323         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13324     if (LHSDecl != RHSDecl)
13325       return;
13326     if (LHSDecl->getType().isVolatileQualified())
13327       return;
13328     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13329       if (RefTy->getPointeeType().isVolatileQualified())
13330         return;
13331 
13332     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13333   }
13334 
13335   // Objective-C instance variables
13336   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13337   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13338   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13339     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13340     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13341     if (RL && RR && RL->getDecl() == RR->getDecl())
13342       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13343   }
13344 }
13345 
13346 // C99 6.5.16.1
13347 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13348                                        SourceLocation Loc,
13349                                        QualType CompoundType) {
13350   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13351 
13352   // Verify that LHS is a modifiable lvalue, and emit error if not.
13353   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13354     return QualType();
13355 
13356   QualType LHSType = LHSExpr->getType();
13357   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13358                                              CompoundType;
13359   // OpenCL v1.2 s6.1.1.1 p2:
13360   // The half data type can only be used to declare a pointer to a buffer that
13361   // contains half values
13362   if (getLangOpts().OpenCL &&
13363       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13364       LHSType->isHalfType()) {
13365     Diag(Loc, diag::err_opencl_half_load_store) << 1
13366         << LHSType.getUnqualifiedType();
13367     return QualType();
13368   }
13369 
13370   AssignConvertType ConvTy;
13371   if (CompoundType.isNull()) {
13372     Expr *RHSCheck = RHS.get();
13373 
13374     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13375 
13376     QualType LHSTy(LHSType);
13377     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13378     if (RHS.isInvalid())
13379       return QualType();
13380     // Special case of NSObject attributes on c-style pointer types.
13381     if (ConvTy == IncompatiblePointer &&
13382         ((Context.isObjCNSObjectType(LHSType) &&
13383           RHSType->isObjCObjectPointerType()) ||
13384          (Context.isObjCNSObjectType(RHSType) &&
13385           LHSType->isObjCObjectPointerType())))
13386       ConvTy = Compatible;
13387 
13388     if (ConvTy == Compatible &&
13389         LHSType->isObjCObjectType())
13390         Diag(Loc, diag::err_objc_object_assignment)
13391           << LHSType;
13392 
13393     // If the RHS is a unary plus or minus, check to see if they = and + are
13394     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13395     // instead of "x += 4".
13396     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13397       RHSCheck = ICE->getSubExpr();
13398     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13399       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13400           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13401           // Only if the two operators are exactly adjacent.
13402           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13403           // And there is a space or other character before the subexpr of the
13404           // unary +/-.  We don't want to warn on "x=-1".
13405           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13406           UO->getSubExpr()->getBeginLoc().isFileID()) {
13407         Diag(Loc, diag::warn_not_compound_assign)
13408           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13409           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13410       }
13411     }
13412 
13413     if (ConvTy == Compatible) {
13414       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13415         // Warn about retain cycles where a block captures the LHS, but
13416         // not if the LHS is a simple variable into which the block is
13417         // being stored...unless that variable can be captured by reference!
13418         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13419         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13420         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13421           checkRetainCycles(LHSExpr, RHS.get());
13422       }
13423 
13424       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13425           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13426         // It is safe to assign a weak reference into a strong variable.
13427         // Although this code can still have problems:
13428         //   id x = self.weakProp;
13429         //   id y = self.weakProp;
13430         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13431         // paths through the function. This should be revisited if
13432         // -Wrepeated-use-of-weak is made flow-sensitive.
13433         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13434         // variable, which will be valid for the current autorelease scope.
13435         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13436                              RHS.get()->getBeginLoc()))
13437           getCurFunction()->markSafeWeakUse(RHS.get());
13438 
13439       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13440         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13441       }
13442     }
13443   } else {
13444     // Compound assignment "x += y"
13445     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13446   }
13447 
13448   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13449                                RHS.get(), AA_Assigning))
13450     return QualType();
13451 
13452   CheckForNullPointerDereference(*this, LHSExpr);
13453 
13454   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13455     if (CompoundType.isNull()) {
13456       // C++2a [expr.ass]p5:
13457       //   A simple-assignment whose left operand is of a volatile-qualified
13458       //   type is deprecated unless the assignment is either a discarded-value
13459       //   expression or an unevaluated operand
13460       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13461     } else {
13462       // C++2a [expr.ass]p6:
13463       //   [Compound-assignment] expressions are deprecated if E1 has
13464       //   volatile-qualified type
13465       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13466     }
13467   }
13468 
13469   // C99 6.5.16p3: The type of an assignment expression is the type of the
13470   // left operand unless the left operand has qualified type, in which case
13471   // it is the unqualified version of the type of the left operand.
13472   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13473   // is converted to the type of the assignment expression (above).
13474   // C++ 5.17p1: the type of the assignment expression is that of its left
13475   // operand.
13476   return (getLangOpts().CPlusPlus
13477           ? LHSType : LHSType.getUnqualifiedType());
13478 }
13479 
13480 // Only ignore explicit casts to void.
13481 static bool IgnoreCommaOperand(const Expr *E) {
13482   E = E->IgnoreParens();
13483 
13484   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13485     if (CE->getCastKind() == CK_ToVoid) {
13486       return true;
13487     }
13488 
13489     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13490     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13491         CE->getSubExpr()->getType()->isDependentType()) {
13492       return true;
13493     }
13494   }
13495 
13496   return false;
13497 }
13498 
13499 // Look for instances where it is likely the comma operator is confused with
13500 // another operator.  There is an explicit list of acceptable expressions for
13501 // the left hand side of the comma operator, otherwise emit a warning.
13502 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13503   // No warnings in macros
13504   if (Loc.isMacroID())
13505     return;
13506 
13507   // Don't warn in template instantiations.
13508   if (inTemplateInstantiation())
13509     return;
13510 
13511   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13512   // instead, skip more than needed, then call back into here with the
13513   // CommaVisitor in SemaStmt.cpp.
13514   // The listed locations are the initialization and increment portions
13515   // of a for loop.  The additional checks are on the condition of
13516   // if statements, do/while loops, and for loops.
13517   // Differences in scope flags for C89 mode requires the extra logic.
13518   const unsigned ForIncrementFlags =
13519       getLangOpts().C99 || getLangOpts().CPlusPlus
13520           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13521           : Scope::ContinueScope | Scope::BreakScope;
13522   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13523   const unsigned ScopeFlags = getCurScope()->getFlags();
13524   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13525       (ScopeFlags & ForInitFlags) == ForInitFlags)
13526     return;
13527 
13528   // If there are multiple comma operators used together, get the RHS of the
13529   // of the comma operator as the LHS.
13530   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13531     if (BO->getOpcode() != BO_Comma)
13532       break;
13533     LHS = BO->getRHS();
13534   }
13535 
13536   // Only allow some expressions on LHS to not warn.
13537   if (IgnoreCommaOperand(LHS))
13538     return;
13539 
13540   Diag(Loc, diag::warn_comma_operator);
13541   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13542       << LHS->getSourceRange()
13543       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13544                                     LangOpts.CPlusPlus ? "static_cast<void>("
13545                                                        : "(void)(")
13546       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13547                                     ")");
13548 }
13549 
13550 // C99 6.5.17
13551 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13552                                    SourceLocation Loc) {
13553   LHS = S.CheckPlaceholderExpr(LHS.get());
13554   RHS = S.CheckPlaceholderExpr(RHS.get());
13555   if (LHS.isInvalid() || RHS.isInvalid())
13556     return QualType();
13557 
13558   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13559   // operands, but not unary promotions.
13560   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13561 
13562   // So we treat the LHS as a ignored value, and in C++ we allow the
13563   // containing site to determine what should be done with the RHS.
13564   LHS = S.IgnoredValueConversions(LHS.get());
13565   if (LHS.isInvalid())
13566     return QualType();
13567 
13568   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13569 
13570   if (!S.getLangOpts().CPlusPlus) {
13571     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13572     if (RHS.isInvalid())
13573       return QualType();
13574     if (!RHS.get()->getType()->isVoidType())
13575       S.RequireCompleteType(Loc, RHS.get()->getType(),
13576                             diag::err_incomplete_type);
13577   }
13578 
13579   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13580     S.DiagnoseCommaOperator(LHS.get(), Loc);
13581 
13582   return RHS.get()->getType();
13583 }
13584 
13585 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13586 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13587 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13588                                                ExprValueKind &VK,
13589                                                ExprObjectKind &OK,
13590                                                SourceLocation OpLoc,
13591                                                bool IsInc, bool IsPrefix) {
13592   if (Op->isTypeDependent())
13593     return S.Context.DependentTy;
13594 
13595   QualType ResType = Op->getType();
13596   // Atomic types can be used for increment / decrement where the non-atomic
13597   // versions can, so ignore the _Atomic() specifier for the purpose of
13598   // checking.
13599   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13600     ResType = ResAtomicType->getValueType();
13601 
13602   assert(!ResType.isNull() && "no type for increment/decrement expression");
13603 
13604   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13605     // Decrement of bool is not allowed.
13606     if (!IsInc) {
13607       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13608       return QualType();
13609     }
13610     // Increment of bool sets it to true, but is deprecated.
13611     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13612                                               : diag::warn_increment_bool)
13613       << Op->getSourceRange();
13614   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13615     // Error on enum increments and decrements in C++ mode
13616     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13617     return QualType();
13618   } else if (ResType->isRealType()) {
13619     // OK!
13620   } else if (ResType->isPointerType()) {
13621     // C99 6.5.2.4p2, 6.5.6p2
13622     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13623       return QualType();
13624   } else if (ResType->isObjCObjectPointerType()) {
13625     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13626     // Otherwise, we just need a complete type.
13627     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13628         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13629       return QualType();
13630   } else if (ResType->isAnyComplexType()) {
13631     // C99 does not support ++/-- on complex types, we allow as an extension.
13632     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13633       << ResType << Op->getSourceRange();
13634   } else if (ResType->isPlaceholderType()) {
13635     ExprResult PR = S.CheckPlaceholderExpr(Op);
13636     if (PR.isInvalid()) return QualType();
13637     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13638                                           IsInc, IsPrefix);
13639   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13640     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13641   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13642              (ResType->castAs<VectorType>()->getVectorKind() !=
13643               VectorType::AltiVecBool)) {
13644     // The z vector extensions allow ++ and -- for non-bool vectors.
13645   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13646             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13647     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13648   } else {
13649     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13650       << ResType << int(IsInc) << Op->getSourceRange();
13651     return QualType();
13652   }
13653   // At this point, we know we have a real, complex or pointer type.
13654   // Now make sure the operand is a modifiable lvalue.
13655   if (CheckForModifiableLvalue(Op, OpLoc, S))
13656     return QualType();
13657   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13658     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13659     //   An operand with volatile-qualified type is deprecated
13660     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13661         << IsInc << ResType;
13662   }
13663   // In C++, a prefix increment is the same type as the operand. Otherwise
13664   // (in C or with postfix), the increment is the unqualified type of the
13665   // operand.
13666   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13667     VK = VK_LValue;
13668     OK = Op->getObjectKind();
13669     return ResType;
13670   } else {
13671     VK = VK_PRValue;
13672     return ResType.getUnqualifiedType();
13673   }
13674 }
13675 
13676 
13677 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13678 /// This routine allows us to typecheck complex/recursive expressions
13679 /// where the declaration is needed for type checking. We only need to
13680 /// handle cases when the expression references a function designator
13681 /// or is an lvalue. Here are some examples:
13682 ///  - &(x) => x
13683 ///  - &*****f => f for f a function designator.
13684 ///  - &s.xx => s
13685 ///  - &s.zz[1].yy -> s, if zz is an array
13686 ///  - *(x + 1) -> x, if x is an array
13687 ///  - &"123"[2] -> 0
13688 ///  - & __real__ x -> x
13689 ///
13690 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13691 /// members.
13692 static ValueDecl *getPrimaryDecl(Expr *E) {
13693   switch (E->getStmtClass()) {
13694   case Stmt::DeclRefExprClass:
13695     return cast<DeclRefExpr>(E)->getDecl();
13696   case Stmt::MemberExprClass:
13697     // If this is an arrow operator, the address is an offset from
13698     // the base's value, so the object the base refers to is
13699     // irrelevant.
13700     if (cast<MemberExpr>(E)->isArrow())
13701       return nullptr;
13702     // Otherwise, the expression refers to a part of the base
13703     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13704   case Stmt::ArraySubscriptExprClass: {
13705     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13706     // promotion of register arrays earlier.
13707     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13708     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13709       if (ICE->getSubExpr()->getType()->isArrayType())
13710         return getPrimaryDecl(ICE->getSubExpr());
13711     }
13712     return nullptr;
13713   }
13714   case Stmt::UnaryOperatorClass: {
13715     UnaryOperator *UO = cast<UnaryOperator>(E);
13716 
13717     switch(UO->getOpcode()) {
13718     case UO_Real:
13719     case UO_Imag:
13720     case UO_Extension:
13721       return getPrimaryDecl(UO->getSubExpr());
13722     default:
13723       return nullptr;
13724     }
13725   }
13726   case Stmt::ParenExprClass:
13727     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13728   case Stmt::ImplicitCastExprClass:
13729     // If the result of an implicit cast is an l-value, we care about
13730     // the sub-expression; otherwise, the result here doesn't matter.
13731     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13732   case Stmt::CXXUuidofExprClass:
13733     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13734   default:
13735     return nullptr;
13736   }
13737 }
13738 
13739 namespace {
13740 enum {
13741   AO_Bit_Field = 0,
13742   AO_Vector_Element = 1,
13743   AO_Property_Expansion = 2,
13744   AO_Register_Variable = 3,
13745   AO_Matrix_Element = 4,
13746   AO_No_Error = 5
13747 };
13748 }
13749 /// Diagnose invalid operand for address of operations.
13750 ///
13751 /// \param Type The type of operand which cannot have its address taken.
13752 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13753                                          Expr *E, unsigned Type) {
13754   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13755 }
13756 
13757 /// CheckAddressOfOperand - The operand of & must be either a function
13758 /// designator or an lvalue designating an object. If it is an lvalue, the
13759 /// object cannot be declared with storage class register or be a bit field.
13760 /// Note: The usual conversions are *not* applied to the operand of the &
13761 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13762 /// In C++, the operand might be an overloaded function name, in which case
13763 /// we allow the '&' but retain the overloaded-function type.
13764 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13765   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13766     if (PTy->getKind() == BuiltinType::Overload) {
13767       Expr *E = OrigOp.get()->IgnoreParens();
13768       if (!isa<OverloadExpr>(E)) {
13769         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13770         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13771           << OrigOp.get()->getSourceRange();
13772         return QualType();
13773       }
13774 
13775       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13776       if (isa<UnresolvedMemberExpr>(Ovl))
13777         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13778           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13779             << OrigOp.get()->getSourceRange();
13780           return QualType();
13781         }
13782 
13783       return Context.OverloadTy;
13784     }
13785 
13786     if (PTy->getKind() == BuiltinType::UnknownAny)
13787       return Context.UnknownAnyTy;
13788 
13789     if (PTy->getKind() == BuiltinType::BoundMember) {
13790       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13791         << OrigOp.get()->getSourceRange();
13792       return QualType();
13793     }
13794 
13795     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13796     if (OrigOp.isInvalid()) return QualType();
13797   }
13798 
13799   if (OrigOp.get()->isTypeDependent())
13800     return Context.DependentTy;
13801 
13802   assert(!OrigOp.get()->hasPlaceholderType());
13803 
13804   // Make sure to ignore parentheses in subsequent checks
13805   Expr *op = OrigOp.get()->IgnoreParens();
13806 
13807   // In OpenCL captures for blocks called as lambda functions
13808   // are located in the private address space. Blocks used in
13809   // enqueue_kernel can be located in a different address space
13810   // depending on a vendor implementation. Thus preventing
13811   // taking an address of the capture to avoid invalid AS casts.
13812   if (LangOpts.OpenCL) {
13813     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13814     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13815       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13816       return QualType();
13817     }
13818   }
13819 
13820   if (getLangOpts().C99) {
13821     // Implement C99-only parts of addressof rules.
13822     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13823       if (uOp->getOpcode() == UO_Deref)
13824         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13825         // (assuming the deref expression is valid).
13826         return uOp->getSubExpr()->getType();
13827     }
13828     // Technically, there should be a check for array subscript
13829     // expressions here, but the result of one is always an lvalue anyway.
13830   }
13831   ValueDecl *dcl = getPrimaryDecl(op);
13832 
13833   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13834     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13835                                            op->getBeginLoc()))
13836       return QualType();
13837 
13838   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13839   unsigned AddressOfError = AO_No_Error;
13840 
13841   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13842     bool sfinae = (bool)isSFINAEContext();
13843     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13844                                   : diag::ext_typecheck_addrof_temporary)
13845       << op->getType() << op->getSourceRange();
13846     if (sfinae)
13847       return QualType();
13848     // Materialize the temporary as an lvalue so that we can take its address.
13849     OrigOp = op =
13850         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13851   } else if (isa<ObjCSelectorExpr>(op)) {
13852     return Context.getPointerType(op->getType());
13853   } else if (lval == Expr::LV_MemberFunction) {
13854     // If it's an instance method, make a member pointer.
13855     // The expression must have exactly the form &A::foo.
13856 
13857     // If the underlying expression isn't a decl ref, give up.
13858     if (!isa<DeclRefExpr>(op)) {
13859       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13860         << OrigOp.get()->getSourceRange();
13861       return QualType();
13862     }
13863     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13864     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13865 
13866     // The id-expression was parenthesized.
13867     if (OrigOp.get() != DRE) {
13868       Diag(OpLoc, diag::err_parens_pointer_member_function)
13869         << OrigOp.get()->getSourceRange();
13870 
13871     // The method was named without a qualifier.
13872     } else if (!DRE->getQualifier()) {
13873       if (MD->getParent()->getName().empty())
13874         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13875           << op->getSourceRange();
13876       else {
13877         SmallString<32> Str;
13878         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13879         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13880           << op->getSourceRange()
13881           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13882       }
13883     }
13884 
13885     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13886     if (isa<CXXDestructorDecl>(MD))
13887       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13888 
13889     QualType MPTy = Context.getMemberPointerType(
13890         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13891     // Under the MS ABI, lock down the inheritance model now.
13892     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13893       (void)isCompleteType(OpLoc, MPTy);
13894     return MPTy;
13895   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13896     // C99 6.5.3.2p1
13897     // The operand must be either an l-value or a function designator
13898     if (!op->getType()->isFunctionType()) {
13899       // Use a special diagnostic for loads from property references.
13900       if (isa<PseudoObjectExpr>(op)) {
13901         AddressOfError = AO_Property_Expansion;
13902       } else {
13903         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13904           << op->getType() << op->getSourceRange();
13905         return QualType();
13906       }
13907     }
13908   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13909     // The operand cannot be a bit-field
13910     AddressOfError = AO_Bit_Field;
13911   } else if (op->getObjectKind() == OK_VectorComponent) {
13912     // The operand cannot be an element of a vector
13913     AddressOfError = AO_Vector_Element;
13914   } else if (op->getObjectKind() == OK_MatrixComponent) {
13915     // The operand cannot be an element of a matrix.
13916     AddressOfError = AO_Matrix_Element;
13917   } else if (dcl) { // C99 6.5.3.2p1
13918     // We have an lvalue with a decl. Make sure the decl is not declared
13919     // with the register storage-class specifier.
13920     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13921       // in C++ it is not error to take address of a register
13922       // variable (c++03 7.1.1P3)
13923       if (vd->getStorageClass() == SC_Register &&
13924           !getLangOpts().CPlusPlus) {
13925         AddressOfError = AO_Register_Variable;
13926       }
13927     } else if (isa<MSPropertyDecl>(dcl)) {
13928       AddressOfError = AO_Property_Expansion;
13929     } else if (isa<FunctionTemplateDecl>(dcl)) {
13930       return Context.OverloadTy;
13931     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13932       // Okay: we can take the address of a field.
13933       // Could be a pointer to member, though, if there is an explicit
13934       // scope qualifier for the class.
13935       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13936         DeclContext *Ctx = dcl->getDeclContext();
13937         if (Ctx && Ctx->isRecord()) {
13938           if (dcl->getType()->isReferenceType()) {
13939             Diag(OpLoc,
13940                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13941               << dcl->getDeclName() << dcl->getType();
13942             return QualType();
13943           }
13944 
13945           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13946             Ctx = Ctx->getParent();
13947 
13948           QualType MPTy = Context.getMemberPointerType(
13949               op->getType(),
13950               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13951           // Under the MS ABI, lock down the inheritance model now.
13952           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13953             (void)isCompleteType(OpLoc, MPTy);
13954           return MPTy;
13955         }
13956       }
13957     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13958                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13959       llvm_unreachable("Unknown/unexpected decl type");
13960   }
13961 
13962   if (AddressOfError != AO_No_Error) {
13963     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13964     return QualType();
13965   }
13966 
13967   if (lval == Expr::LV_IncompleteVoidType) {
13968     // Taking the address of a void variable is technically illegal, but we
13969     // allow it in cases which are otherwise valid.
13970     // Example: "extern void x; void* y = &x;".
13971     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13972   }
13973 
13974   // If the operand has type "type", the result has type "pointer to type".
13975   if (op->getType()->isObjCObjectType())
13976     return Context.getObjCObjectPointerType(op->getType());
13977 
13978   CheckAddressOfPackedMember(op);
13979 
13980   return Context.getPointerType(op->getType());
13981 }
13982 
13983 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13984   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13985   if (!DRE)
13986     return;
13987   const Decl *D = DRE->getDecl();
13988   if (!D)
13989     return;
13990   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13991   if (!Param)
13992     return;
13993   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13994     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13995       return;
13996   if (FunctionScopeInfo *FD = S.getCurFunction())
13997     if (!FD->ModifiedNonNullParams.count(Param))
13998       FD->ModifiedNonNullParams.insert(Param);
13999 }
14000 
14001 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14002 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14003                                         SourceLocation OpLoc) {
14004   if (Op->isTypeDependent())
14005     return S.Context.DependentTy;
14006 
14007   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14008   if (ConvResult.isInvalid())
14009     return QualType();
14010   Op = ConvResult.get();
14011   QualType OpTy = Op->getType();
14012   QualType Result;
14013 
14014   if (isa<CXXReinterpretCastExpr>(Op)) {
14015     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14016     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14017                                      Op->getSourceRange());
14018   }
14019 
14020   if (const PointerType *PT = OpTy->getAs<PointerType>())
14021   {
14022     Result = PT->getPointeeType();
14023   }
14024   else if (const ObjCObjectPointerType *OPT =
14025              OpTy->getAs<ObjCObjectPointerType>())
14026     Result = OPT->getPointeeType();
14027   else {
14028     ExprResult PR = S.CheckPlaceholderExpr(Op);
14029     if (PR.isInvalid()) return QualType();
14030     if (PR.get() != Op)
14031       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14032   }
14033 
14034   if (Result.isNull()) {
14035     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14036       << OpTy << Op->getSourceRange();
14037     return QualType();
14038   }
14039 
14040   // Note that per both C89 and C99, indirection is always legal, even if Result
14041   // is an incomplete type or void.  It would be possible to warn about
14042   // dereferencing a void pointer, but it's completely well-defined, and such a
14043   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14044   // for pointers to 'void' but is fine for any other pointer type:
14045   //
14046   // C++ [expr.unary.op]p1:
14047   //   [...] the expression to which [the unary * operator] is applied shall
14048   //   be a pointer to an object type, or a pointer to a function type
14049   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14050     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14051       << OpTy << Op->getSourceRange();
14052 
14053   // Dereferences are usually l-values...
14054   VK = VK_LValue;
14055 
14056   // ...except that certain expressions are never l-values in C.
14057   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14058     VK = VK_PRValue;
14059 
14060   return Result;
14061 }
14062 
14063 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14064   BinaryOperatorKind Opc;
14065   switch (Kind) {
14066   default: llvm_unreachable("Unknown binop!");
14067   case tok::periodstar:           Opc = BO_PtrMemD; break;
14068   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14069   case tok::star:                 Opc = BO_Mul; break;
14070   case tok::slash:                Opc = BO_Div; break;
14071   case tok::percent:              Opc = BO_Rem; break;
14072   case tok::plus:                 Opc = BO_Add; break;
14073   case tok::minus:                Opc = BO_Sub; break;
14074   case tok::lessless:             Opc = BO_Shl; break;
14075   case tok::greatergreater:       Opc = BO_Shr; break;
14076   case tok::lessequal:            Opc = BO_LE; break;
14077   case tok::less:                 Opc = BO_LT; break;
14078   case tok::greaterequal:         Opc = BO_GE; break;
14079   case tok::greater:              Opc = BO_GT; break;
14080   case tok::exclaimequal:         Opc = BO_NE; break;
14081   case tok::equalequal:           Opc = BO_EQ; break;
14082   case tok::spaceship:            Opc = BO_Cmp; break;
14083   case tok::amp:                  Opc = BO_And; break;
14084   case tok::caret:                Opc = BO_Xor; break;
14085   case tok::pipe:                 Opc = BO_Or; break;
14086   case tok::ampamp:               Opc = BO_LAnd; break;
14087   case tok::pipepipe:             Opc = BO_LOr; break;
14088   case tok::equal:                Opc = BO_Assign; break;
14089   case tok::starequal:            Opc = BO_MulAssign; break;
14090   case tok::slashequal:           Opc = BO_DivAssign; break;
14091   case tok::percentequal:         Opc = BO_RemAssign; break;
14092   case tok::plusequal:            Opc = BO_AddAssign; break;
14093   case tok::minusequal:           Opc = BO_SubAssign; break;
14094   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14095   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14096   case tok::ampequal:             Opc = BO_AndAssign; break;
14097   case tok::caretequal:           Opc = BO_XorAssign; break;
14098   case tok::pipeequal:            Opc = BO_OrAssign; break;
14099   case tok::comma:                Opc = BO_Comma; break;
14100   }
14101   return Opc;
14102 }
14103 
14104 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14105   tok::TokenKind Kind) {
14106   UnaryOperatorKind Opc;
14107   switch (Kind) {
14108   default: llvm_unreachable("Unknown unary op!");
14109   case tok::plusplus:     Opc = UO_PreInc; break;
14110   case tok::minusminus:   Opc = UO_PreDec; break;
14111   case tok::amp:          Opc = UO_AddrOf; break;
14112   case tok::star:         Opc = UO_Deref; break;
14113   case tok::plus:         Opc = UO_Plus; break;
14114   case tok::minus:        Opc = UO_Minus; break;
14115   case tok::tilde:        Opc = UO_Not; break;
14116   case tok::exclaim:      Opc = UO_LNot; break;
14117   case tok::kw___real:    Opc = UO_Real; break;
14118   case tok::kw___imag:    Opc = UO_Imag; break;
14119   case tok::kw___extension__: Opc = UO_Extension; break;
14120   }
14121   return Opc;
14122 }
14123 
14124 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14125 /// This warning suppressed in the event of macro expansions.
14126 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14127                                    SourceLocation OpLoc, bool IsBuiltin) {
14128   if (S.inTemplateInstantiation())
14129     return;
14130   if (S.isUnevaluatedContext())
14131     return;
14132   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14133     return;
14134   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14135   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14136   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14137   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14138   if (!LHSDeclRef || !RHSDeclRef ||
14139       LHSDeclRef->getLocation().isMacroID() ||
14140       RHSDeclRef->getLocation().isMacroID())
14141     return;
14142   const ValueDecl *LHSDecl =
14143     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14144   const ValueDecl *RHSDecl =
14145     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14146   if (LHSDecl != RHSDecl)
14147     return;
14148   if (LHSDecl->getType().isVolatileQualified())
14149     return;
14150   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14151     if (RefTy->getPointeeType().isVolatileQualified())
14152       return;
14153 
14154   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14155                           : diag::warn_self_assignment_overloaded)
14156       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14157       << RHSExpr->getSourceRange();
14158 }
14159 
14160 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14161 /// is usually indicative of introspection within the Objective-C pointer.
14162 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14163                                           SourceLocation OpLoc) {
14164   if (!S.getLangOpts().ObjC)
14165     return;
14166 
14167   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14168   const Expr *LHS = L.get();
14169   const Expr *RHS = R.get();
14170 
14171   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14172     ObjCPointerExpr = LHS;
14173     OtherExpr = RHS;
14174   }
14175   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14176     ObjCPointerExpr = RHS;
14177     OtherExpr = LHS;
14178   }
14179 
14180   // This warning is deliberately made very specific to reduce false
14181   // positives with logic that uses '&' for hashing.  This logic mainly
14182   // looks for code trying to introspect into tagged pointers, which
14183   // code should generally never do.
14184   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14185     unsigned Diag = diag::warn_objc_pointer_masking;
14186     // Determine if we are introspecting the result of performSelectorXXX.
14187     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14188     // Special case messages to -performSelector and friends, which
14189     // can return non-pointer values boxed in a pointer value.
14190     // Some clients may wish to silence warnings in this subcase.
14191     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14192       Selector S = ME->getSelector();
14193       StringRef SelArg0 = S.getNameForSlot(0);
14194       if (SelArg0.startswith("performSelector"))
14195         Diag = diag::warn_objc_pointer_masking_performSelector;
14196     }
14197 
14198     S.Diag(OpLoc, Diag)
14199       << ObjCPointerExpr->getSourceRange();
14200   }
14201 }
14202 
14203 static NamedDecl *getDeclFromExpr(Expr *E) {
14204   if (!E)
14205     return nullptr;
14206   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14207     return DRE->getDecl();
14208   if (auto *ME = dyn_cast<MemberExpr>(E))
14209     return ME->getMemberDecl();
14210   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14211     return IRE->getDecl();
14212   return nullptr;
14213 }
14214 
14215 // This helper function promotes a binary operator's operands (which are of a
14216 // half vector type) to a vector of floats and then truncates the result to
14217 // a vector of either half or short.
14218 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14219                                       BinaryOperatorKind Opc, QualType ResultTy,
14220                                       ExprValueKind VK, ExprObjectKind OK,
14221                                       bool IsCompAssign, SourceLocation OpLoc,
14222                                       FPOptionsOverride FPFeatures) {
14223   auto &Context = S.getASTContext();
14224   assert((isVector(ResultTy, Context.HalfTy) ||
14225           isVector(ResultTy, Context.ShortTy)) &&
14226          "Result must be a vector of half or short");
14227   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14228          isVector(RHS.get()->getType(), Context.HalfTy) &&
14229          "both operands expected to be a half vector");
14230 
14231   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14232   QualType BinOpResTy = RHS.get()->getType();
14233 
14234   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14235   // change BinOpResTy to a vector of ints.
14236   if (isVector(ResultTy, Context.ShortTy))
14237     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14238 
14239   if (IsCompAssign)
14240     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14241                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14242                                           BinOpResTy, BinOpResTy);
14243 
14244   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14245   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14246                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14247   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14248 }
14249 
14250 static std::pair<ExprResult, ExprResult>
14251 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14252                            Expr *RHSExpr) {
14253   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14254   if (!S.Context.isDependenceAllowed()) {
14255     // C cannot handle TypoExpr nodes on either side of a binop because it
14256     // doesn't handle dependent types properly, so make sure any TypoExprs have
14257     // been dealt with before checking the operands.
14258     LHS = S.CorrectDelayedTyposInExpr(LHS);
14259     RHS = S.CorrectDelayedTyposInExpr(
14260         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14261         [Opc, LHS](Expr *E) {
14262           if (Opc != BO_Assign)
14263             return ExprResult(E);
14264           // Avoid correcting the RHS to the same Expr as the LHS.
14265           Decl *D = getDeclFromExpr(E);
14266           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14267         });
14268   }
14269   return std::make_pair(LHS, RHS);
14270 }
14271 
14272 /// Returns true if conversion between vectors of halfs and vectors of floats
14273 /// is needed.
14274 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14275                                      Expr *E0, Expr *E1 = nullptr) {
14276   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14277       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14278     return false;
14279 
14280   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14281     QualType Ty = E->IgnoreImplicit()->getType();
14282 
14283     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14284     // to vectors of floats. Although the element type of the vectors is __fp16,
14285     // the vectors shouldn't be treated as storage-only types. See the
14286     // discussion here: https://reviews.llvm.org/rG825235c140e7
14287     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14288       if (VT->getVectorKind() == VectorType::NeonVector)
14289         return false;
14290       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14291     }
14292     return false;
14293   };
14294 
14295   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14296 }
14297 
14298 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14299 /// operator @p Opc at location @c TokLoc. This routine only supports
14300 /// built-in operations; ActOnBinOp handles overloaded operators.
14301 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14302                                     BinaryOperatorKind Opc,
14303                                     Expr *LHSExpr, Expr *RHSExpr) {
14304   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14305     // The syntax only allows initializer lists on the RHS of assignment,
14306     // so we don't need to worry about accepting invalid code for
14307     // non-assignment operators.
14308     // C++11 5.17p9:
14309     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14310     //   of x = {} is x = T().
14311     InitializationKind Kind = InitializationKind::CreateDirectList(
14312         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14313     InitializedEntity Entity =
14314         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14315     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14316     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14317     if (Init.isInvalid())
14318       return Init;
14319     RHSExpr = Init.get();
14320   }
14321 
14322   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14323   QualType ResultTy;     // Result type of the binary operator.
14324   // The following two variables are used for compound assignment operators
14325   QualType CompLHSTy;    // Type of LHS after promotions for computation
14326   QualType CompResultTy; // Type of computation result
14327   ExprValueKind VK = VK_PRValue;
14328   ExprObjectKind OK = OK_Ordinary;
14329   bool ConvertHalfVec = false;
14330 
14331   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14332   if (!LHS.isUsable() || !RHS.isUsable())
14333     return ExprError();
14334 
14335   if (getLangOpts().OpenCL) {
14336     QualType LHSTy = LHSExpr->getType();
14337     QualType RHSTy = RHSExpr->getType();
14338     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14339     // the ATOMIC_VAR_INIT macro.
14340     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14341       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14342       if (BO_Assign == Opc)
14343         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14344       else
14345         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14346       return ExprError();
14347     }
14348 
14349     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14350     // only with a builtin functions and therefore should be disallowed here.
14351     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14352         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14353         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14354         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14355       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14356       return ExprError();
14357     }
14358   }
14359 
14360   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14361   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14362 
14363   switch (Opc) {
14364   case BO_Assign:
14365     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14366     if (getLangOpts().CPlusPlus &&
14367         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14368       VK = LHS.get()->getValueKind();
14369       OK = LHS.get()->getObjectKind();
14370     }
14371     if (!ResultTy.isNull()) {
14372       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14373       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14374 
14375       // Avoid copying a block to the heap if the block is assigned to a local
14376       // auto variable that is declared in the same scope as the block. This
14377       // optimization is unsafe if the local variable is declared in an outer
14378       // scope. For example:
14379       //
14380       // BlockTy b;
14381       // {
14382       //   b = ^{...};
14383       // }
14384       // // It is unsafe to invoke the block here if it wasn't copied to the
14385       // // heap.
14386       // b();
14387 
14388       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14389         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14390           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14391             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14392               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14393 
14394       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14395         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14396                               NTCUC_Assignment, NTCUK_Copy);
14397     }
14398     RecordModifiableNonNullParam(*this, LHS.get());
14399     break;
14400   case BO_PtrMemD:
14401   case BO_PtrMemI:
14402     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14403                                             Opc == BO_PtrMemI);
14404     break;
14405   case BO_Mul:
14406   case BO_Div:
14407     ConvertHalfVec = true;
14408     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14409                                            Opc == BO_Div);
14410     break;
14411   case BO_Rem:
14412     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14413     break;
14414   case BO_Add:
14415     ConvertHalfVec = true;
14416     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14417     break;
14418   case BO_Sub:
14419     ConvertHalfVec = true;
14420     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14421     break;
14422   case BO_Shl:
14423   case BO_Shr:
14424     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14425     break;
14426   case BO_LE:
14427   case BO_LT:
14428   case BO_GE:
14429   case BO_GT:
14430     ConvertHalfVec = true;
14431     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14432     break;
14433   case BO_EQ:
14434   case BO_NE:
14435     ConvertHalfVec = true;
14436     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14437     break;
14438   case BO_Cmp:
14439     ConvertHalfVec = true;
14440     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14441     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14442     break;
14443   case BO_And:
14444     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14445     LLVM_FALLTHROUGH;
14446   case BO_Xor:
14447   case BO_Or:
14448     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14449     break;
14450   case BO_LAnd:
14451   case BO_LOr:
14452     ConvertHalfVec = true;
14453     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14454     break;
14455   case BO_MulAssign:
14456   case BO_DivAssign:
14457     ConvertHalfVec = true;
14458     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14459                                                Opc == BO_DivAssign);
14460     CompLHSTy = CompResultTy;
14461     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14462       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14463     break;
14464   case BO_RemAssign:
14465     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14466     CompLHSTy = CompResultTy;
14467     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14468       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14469     break;
14470   case BO_AddAssign:
14471     ConvertHalfVec = true;
14472     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14473     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14474       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14475     break;
14476   case BO_SubAssign:
14477     ConvertHalfVec = true;
14478     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14479     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14480       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14481     break;
14482   case BO_ShlAssign:
14483   case BO_ShrAssign:
14484     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14485     CompLHSTy = CompResultTy;
14486     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14487       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14488     break;
14489   case BO_AndAssign:
14490   case BO_OrAssign: // fallthrough
14491     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14492     LLVM_FALLTHROUGH;
14493   case BO_XorAssign:
14494     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14495     CompLHSTy = CompResultTy;
14496     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14497       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14498     break;
14499   case BO_Comma:
14500     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14501     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14502       VK = RHS.get()->getValueKind();
14503       OK = RHS.get()->getObjectKind();
14504     }
14505     break;
14506   }
14507   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14508     return ExprError();
14509 
14510   // Some of the binary operations require promoting operands of half vector to
14511   // float vectors and truncating the result back to half vector. For now, we do
14512   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14513   // arm64).
14514   assert(
14515       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14516                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14517       "both sides are half vectors or neither sides are");
14518   ConvertHalfVec =
14519       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14520 
14521   // Check for array bounds violations for both sides of the BinaryOperator
14522   CheckArrayAccess(LHS.get());
14523   CheckArrayAccess(RHS.get());
14524 
14525   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14526     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14527                                                  &Context.Idents.get("object_setClass"),
14528                                                  SourceLocation(), LookupOrdinaryName);
14529     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14530       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14531       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14532           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14533                                         "object_setClass(")
14534           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14535                                           ",")
14536           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14537     }
14538     else
14539       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14540   }
14541   else if (const ObjCIvarRefExpr *OIRE =
14542            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14543     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14544 
14545   // Opc is not a compound assignment if CompResultTy is null.
14546   if (CompResultTy.isNull()) {
14547     if (ConvertHalfVec)
14548       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14549                                  OpLoc, CurFPFeatureOverrides());
14550     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14551                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14552   }
14553 
14554   // Handle compound assignments.
14555   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14556       OK_ObjCProperty) {
14557     VK = VK_LValue;
14558     OK = LHS.get()->getObjectKind();
14559   }
14560 
14561   // The LHS is not converted to the result type for fixed-point compound
14562   // assignment as the common type is computed on demand. Reset the CompLHSTy
14563   // to the LHS type we would have gotten after unary conversions.
14564   if (CompResultTy->isFixedPointType())
14565     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14566 
14567   if (ConvertHalfVec)
14568     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14569                                OpLoc, CurFPFeatureOverrides());
14570 
14571   return CompoundAssignOperator::Create(
14572       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14573       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14574 }
14575 
14576 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14577 /// operators are mixed in a way that suggests that the programmer forgot that
14578 /// comparison operators have higher precedence. The most typical example of
14579 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14580 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14581                                       SourceLocation OpLoc, Expr *LHSExpr,
14582                                       Expr *RHSExpr) {
14583   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14584   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14585 
14586   // Check that one of the sides is a comparison operator and the other isn't.
14587   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14588   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14589   if (isLeftComp == isRightComp)
14590     return;
14591 
14592   // Bitwise operations are sometimes used as eager logical ops.
14593   // Don't diagnose this.
14594   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14595   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14596   if (isLeftBitwise || isRightBitwise)
14597     return;
14598 
14599   SourceRange DiagRange = isLeftComp
14600                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14601                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14602   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14603   SourceRange ParensRange =
14604       isLeftComp
14605           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14606           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14607 
14608   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14609     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14610   SuggestParentheses(Self, OpLoc,
14611     Self.PDiag(diag::note_precedence_silence) << OpStr,
14612     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14613   SuggestParentheses(Self, OpLoc,
14614     Self.PDiag(diag::note_precedence_bitwise_first)
14615       << BinaryOperator::getOpcodeStr(Opc),
14616     ParensRange);
14617 }
14618 
14619 /// It accepts a '&&' expr that is inside a '||' one.
14620 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14621 /// in parentheses.
14622 static void
14623 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14624                                        BinaryOperator *Bop) {
14625   assert(Bop->getOpcode() == BO_LAnd);
14626   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14627       << Bop->getSourceRange() << OpLoc;
14628   SuggestParentheses(Self, Bop->getOperatorLoc(),
14629     Self.PDiag(diag::note_precedence_silence)
14630       << Bop->getOpcodeStr(),
14631     Bop->getSourceRange());
14632 }
14633 
14634 /// Returns true if the given expression can be evaluated as a constant
14635 /// 'true'.
14636 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14637   bool Res;
14638   return !E->isValueDependent() &&
14639          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14640 }
14641 
14642 /// Returns true if the given expression can be evaluated as a constant
14643 /// 'false'.
14644 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14645   bool Res;
14646   return !E->isValueDependent() &&
14647          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14648 }
14649 
14650 /// Look for '&&' in the left hand of a '||' expr.
14651 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14652                                              Expr *LHSExpr, Expr *RHSExpr) {
14653   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14654     if (Bop->getOpcode() == BO_LAnd) {
14655       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14656       if (EvaluatesAsFalse(S, RHSExpr))
14657         return;
14658       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14659       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14660         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14661     } else if (Bop->getOpcode() == BO_LOr) {
14662       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14663         // If it's "a || b && 1 || c" we didn't warn earlier for
14664         // "a || b && 1", but warn now.
14665         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14666           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14667       }
14668     }
14669   }
14670 }
14671 
14672 /// Look for '&&' in the right hand of a '||' expr.
14673 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14674                                              Expr *LHSExpr, Expr *RHSExpr) {
14675   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14676     if (Bop->getOpcode() == BO_LAnd) {
14677       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14678       if (EvaluatesAsFalse(S, LHSExpr))
14679         return;
14680       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14681       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14682         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14683     }
14684   }
14685 }
14686 
14687 /// Look for bitwise op in the left or right hand of a bitwise op with
14688 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14689 /// the '&' expression in parentheses.
14690 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14691                                          SourceLocation OpLoc, Expr *SubExpr) {
14692   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14693     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14694       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14695         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14696         << Bop->getSourceRange() << OpLoc;
14697       SuggestParentheses(S, Bop->getOperatorLoc(),
14698         S.PDiag(diag::note_precedence_silence)
14699           << Bop->getOpcodeStr(),
14700         Bop->getSourceRange());
14701     }
14702   }
14703 }
14704 
14705 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14706                                     Expr *SubExpr, StringRef Shift) {
14707   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14708     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14709       StringRef Op = Bop->getOpcodeStr();
14710       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14711           << Bop->getSourceRange() << OpLoc << Shift << Op;
14712       SuggestParentheses(S, Bop->getOperatorLoc(),
14713           S.PDiag(diag::note_precedence_silence) << Op,
14714           Bop->getSourceRange());
14715     }
14716   }
14717 }
14718 
14719 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14720                                  Expr *LHSExpr, Expr *RHSExpr) {
14721   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14722   if (!OCE)
14723     return;
14724 
14725   FunctionDecl *FD = OCE->getDirectCallee();
14726   if (!FD || !FD->isOverloadedOperator())
14727     return;
14728 
14729   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14730   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14731     return;
14732 
14733   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14734       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14735       << (Kind == OO_LessLess);
14736   SuggestParentheses(S, OCE->getOperatorLoc(),
14737                      S.PDiag(diag::note_precedence_silence)
14738                          << (Kind == OO_LessLess ? "<<" : ">>"),
14739                      OCE->getSourceRange());
14740   SuggestParentheses(
14741       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14742       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14743 }
14744 
14745 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14746 /// precedence.
14747 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14748                                     SourceLocation OpLoc, Expr *LHSExpr,
14749                                     Expr *RHSExpr){
14750   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14751   if (BinaryOperator::isBitwiseOp(Opc))
14752     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14753 
14754   // Diagnose "arg1 & arg2 | arg3"
14755   if ((Opc == BO_Or || Opc == BO_Xor) &&
14756       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14757     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14758     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14759   }
14760 
14761   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14762   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14763   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14764     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14765     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14766   }
14767 
14768   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14769       || Opc == BO_Shr) {
14770     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14771     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14772     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14773   }
14774 
14775   // Warn on overloaded shift operators and comparisons, such as:
14776   // cout << 5 == 4;
14777   if (BinaryOperator::isComparisonOp(Opc))
14778     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14779 }
14780 
14781 // Binary Operators.  'Tok' is the token for the operator.
14782 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14783                             tok::TokenKind Kind,
14784                             Expr *LHSExpr, Expr *RHSExpr) {
14785   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14786   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14787   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14788 
14789   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14790   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14791 
14792   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14793 }
14794 
14795 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14796                        UnresolvedSetImpl &Functions) {
14797   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14798   if (OverOp != OO_None && OverOp != OO_Equal)
14799     LookupOverloadedOperatorName(OverOp, S, Functions);
14800 
14801   // In C++20 onwards, we may have a second operator to look up.
14802   if (getLangOpts().CPlusPlus20) {
14803     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14804       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14805   }
14806 }
14807 
14808 /// Build an overloaded binary operator expression in the given scope.
14809 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14810                                        BinaryOperatorKind Opc,
14811                                        Expr *LHS, Expr *RHS) {
14812   switch (Opc) {
14813   case BO_Assign:
14814   case BO_DivAssign:
14815   case BO_RemAssign:
14816   case BO_SubAssign:
14817   case BO_AndAssign:
14818   case BO_OrAssign:
14819   case BO_XorAssign:
14820     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14821     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14822     break;
14823   default:
14824     break;
14825   }
14826 
14827   // Find all of the overloaded operators visible from this point.
14828   UnresolvedSet<16> Functions;
14829   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14830 
14831   // Build the (potentially-overloaded, potentially-dependent)
14832   // binary operation.
14833   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14834 }
14835 
14836 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14837                             BinaryOperatorKind Opc,
14838                             Expr *LHSExpr, Expr *RHSExpr) {
14839   ExprResult LHS, RHS;
14840   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14841   if (!LHS.isUsable() || !RHS.isUsable())
14842     return ExprError();
14843   LHSExpr = LHS.get();
14844   RHSExpr = RHS.get();
14845 
14846   // We want to end up calling one of checkPseudoObjectAssignment
14847   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14848   // both expressions are overloadable or either is type-dependent),
14849   // or CreateBuiltinBinOp (in any other case).  We also want to get
14850   // any placeholder types out of the way.
14851 
14852   // Handle pseudo-objects in the LHS.
14853   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14854     // Assignments with a pseudo-object l-value need special analysis.
14855     if (pty->getKind() == BuiltinType::PseudoObject &&
14856         BinaryOperator::isAssignmentOp(Opc))
14857       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14858 
14859     // Don't resolve overloads if the other type is overloadable.
14860     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14861       // We can't actually test that if we still have a placeholder,
14862       // though.  Fortunately, none of the exceptions we see in that
14863       // code below are valid when the LHS is an overload set.  Note
14864       // that an overload set can be dependently-typed, but it never
14865       // instantiates to having an overloadable type.
14866       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14867       if (resolvedRHS.isInvalid()) return ExprError();
14868       RHSExpr = resolvedRHS.get();
14869 
14870       if (RHSExpr->isTypeDependent() ||
14871           RHSExpr->getType()->isOverloadableType())
14872         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14873     }
14874 
14875     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14876     // template, diagnose the missing 'template' keyword instead of diagnosing
14877     // an invalid use of a bound member function.
14878     //
14879     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14880     // to C++1z [over.over]/1.4, but we already checked for that case above.
14881     if (Opc == BO_LT && inTemplateInstantiation() &&
14882         (pty->getKind() == BuiltinType::BoundMember ||
14883          pty->getKind() == BuiltinType::Overload)) {
14884       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14885       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14886           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14887             return isa<FunctionTemplateDecl>(ND);
14888           })) {
14889         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14890                                 : OE->getNameLoc(),
14891              diag::err_template_kw_missing)
14892           << OE->getName().getAsString() << "";
14893         return ExprError();
14894       }
14895     }
14896 
14897     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14898     if (LHS.isInvalid()) return ExprError();
14899     LHSExpr = LHS.get();
14900   }
14901 
14902   // Handle pseudo-objects in the RHS.
14903   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14904     // An overload in the RHS can potentially be resolved by the type
14905     // being assigned to.
14906     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14907       if (getLangOpts().CPlusPlus &&
14908           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14909            LHSExpr->getType()->isOverloadableType()))
14910         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14911 
14912       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14913     }
14914 
14915     // Don't resolve overloads if the other type is overloadable.
14916     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14917         LHSExpr->getType()->isOverloadableType())
14918       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14919 
14920     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14921     if (!resolvedRHS.isUsable()) return ExprError();
14922     RHSExpr = resolvedRHS.get();
14923   }
14924 
14925   if (getLangOpts().CPlusPlus) {
14926     // If either expression is type-dependent, always build an
14927     // overloaded op.
14928     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14929       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14930 
14931     // Otherwise, build an overloaded op if either expression has an
14932     // overloadable type.
14933     if (LHSExpr->getType()->isOverloadableType() ||
14934         RHSExpr->getType()->isOverloadableType())
14935       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14936   }
14937 
14938   if (getLangOpts().RecoveryAST &&
14939       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14940     assert(!getLangOpts().CPlusPlus);
14941     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14942            "Should only occur in error-recovery path.");
14943     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14944       // C [6.15.16] p3:
14945       // An assignment expression has the value of the left operand after the
14946       // assignment, but is not an lvalue.
14947       return CompoundAssignOperator::Create(
14948           Context, LHSExpr, RHSExpr, Opc,
14949           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
14950           OpLoc, CurFPFeatureOverrides());
14951     QualType ResultType;
14952     switch (Opc) {
14953     case BO_Assign:
14954       ResultType = LHSExpr->getType().getUnqualifiedType();
14955       break;
14956     case BO_LT:
14957     case BO_GT:
14958     case BO_LE:
14959     case BO_GE:
14960     case BO_EQ:
14961     case BO_NE:
14962     case BO_LAnd:
14963     case BO_LOr:
14964       // These operators have a fixed result type regardless of operands.
14965       ResultType = Context.IntTy;
14966       break;
14967     case BO_Comma:
14968       ResultType = RHSExpr->getType();
14969       break;
14970     default:
14971       ResultType = Context.DependentTy;
14972       break;
14973     }
14974     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14975                                   VK_PRValue, OK_Ordinary, OpLoc,
14976                                   CurFPFeatureOverrides());
14977   }
14978 
14979   // Build a built-in binary operation.
14980   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14981 }
14982 
14983 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14984   if (T.isNull() || T->isDependentType())
14985     return false;
14986 
14987   if (!T->isPromotableIntegerType())
14988     return true;
14989 
14990   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14991 }
14992 
14993 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14994                                       UnaryOperatorKind Opc,
14995                                       Expr *InputExpr) {
14996   ExprResult Input = InputExpr;
14997   ExprValueKind VK = VK_PRValue;
14998   ExprObjectKind OK = OK_Ordinary;
14999   QualType resultType;
15000   bool CanOverflow = false;
15001 
15002   bool ConvertHalfVec = false;
15003   if (getLangOpts().OpenCL) {
15004     QualType Ty = InputExpr->getType();
15005     // The only legal unary operation for atomics is '&'.
15006     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15007     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15008     // only with a builtin functions and therefore should be disallowed here.
15009         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15010         || Ty->isBlockPointerType())) {
15011       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15012                        << InputExpr->getType()
15013                        << Input.get()->getSourceRange());
15014     }
15015   }
15016 
15017   switch (Opc) {
15018   case UO_PreInc:
15019   case UO_PreDec:
15020   case UO_PostInc:
15021   case UO_PostDec:
15022     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15023                                                 OpLoc,
15024                                                 Opc == UO_PreInc ||
15025                                                 Opc == UO_PostInc,
15026                                                 Opc == UO_PreInc ||
15027                                                 Opc == UO_PreDec);
15028     CanOverflow = isOverflowingIntegerType(Context, resultType);
15029     break;
15030   case UO_AddrOf:
15031     resultType = CheckAddressOfOperand(Input, OpLoc);
15032     CheckAddressOfNoDeref(InputExpr);
15033     RecordModifiableNonNullParam(*this, InputExpr);
15034     break;
15035   case UO_Deref: {
15036     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15037     if (Input.isInvalid()) return ExprError();
15038     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15039     break;
15040   }
15041   case UO_Plus:
15042   case UO_Minus:
15043     CanOverflow = Opc == UO_Minus &&
15044                   isOverflowingIntegerType(Context, Input.get()->getType());
15045     Input = UsualUnaryConversions(Input.get());
15046     if (Input.isInvalid()) return ExprError();
15047     // Unary plus and minus require promoting an operand of half vector to a
15048     // float vector and truncating the result back to a half vector. For now, we
15049     // do this only when HalfArgsAndReturns is set (that is, when the target is
15050     // arm or arm64).
15051     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15052 
15053     // If the operand is a half vector, promote it to a float vector.
15054     if (ConvertHalfVec)
15055       Input = convertVector(Input.get(), Context.FloatTy, *this);
15056     resultType = Input.get()->getType();
15057     if (resultType->isDependentType())
15058       break;
15059     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15060       break;
15061     else if (resultType->isVectorType() &&
15062              // The z vector extensions don't allow + or - with bool vectors.
15063              (!Context.getLangOpts().ZVector ||
15064               resultType->castAs<VectorType>()->getVectorKind() !=
15065               VectorType::AltiVecBool))
15066       break;
15067     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15068              Opc == UO_Plus &&
15069              resultType->isPointerType())
15070       break;
15071 
15072     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15073       << resultType << Input.get()->getSourceRange());
15074 
15075   case UO_Not: // bitwise complement
15076     Input = UsualUnaryConversions(Input.get());
15077     if (Input.isInvalid())
15078       return ExprError();
15079     resultType = Input.get()->getType();
15080     if (resultType->isDependentType())
15081       break;
15082     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15083     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15084       // C99 does not support '~' for complex conjugation.
15085       Diag(OpLoc, diag::ext_integer_complement_complex)
15086           << resultType << Input.get()->getSourceRange();
15087     else if (resultType->hasIntegerRepresentation())
15088       break;
15089     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15090       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15091       // on vector float types.
15092       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15093       if (!T->isIntegerType())
15094         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15095                           << resultType << Input.get()->getSourceRange());
15096     } else {
15097       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15098                        << resultType << Input.get()->getSourceRange());
15099     }
15100     break;
15101 
15102   case UO_LNot: // logical negation
15103     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15104     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15105     if (Input.isInvalid()) return ExprError();
15106     resultType = Input.get()->getType();
15107 
15108     // Though we still have to promote half FP to float...
15109     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15110       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15111       resultType = Context.FloatTy;
15112     }
15113 
15114     if (resultType->isDependentType())
15115       break;
15116     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15117       // C99 6.5.3.3p1: ok, fallthrough;
15118       if (Context.getLangOpts().CPlusPlus) {
15119         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15120         // operand contextually converted to bool.
15121         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15122                                   ScalarTypeToBooleanCastKind(resultType));
15123       } else if (Context.getLangOpts().OpenCL &&
15124                  Context.getLangOpts().OpenCLVersion < 120) {
15125         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15126         // operate on scalar float types.
15127         if (!resultType->isIntegerType() && !resultType->isPointerType())
15128           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15129                            << resultType << Input.get()->getSourceRange());
15130       }
15131     } else if (resultType->isExtVectorType()) {
15132       if (Context.getLangOpts().OpenCL &&
15133           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15134         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15135         // operate on vector float types.
15136         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15137         if (!T->isIntegerType())
15138           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15139                            << resultType << Input.get()->getSourceRange());
15140       }
15141       // Vector logical not returns the signed variant of the operand type.
15142       resultType = GetSignedVectorType(resultType);
15143       break;
15144     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15145       const VectorType *VTy = resultType->castAs<VectorType>();
15146       if (VTy->getVectorKind() != VectorType::GenericVector)
15147         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15148                          << resultType << Input.get()->getSourceRange());
15149 
15150       // Vector logical not returns the signed variant of the operand type.
15151       resultType = GetSignedVectorType(resultType);
15152       break;
15153     } else {
15154       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15155         << resultType << Input.get()->getSourceRange());
15156     }
15157 
15158     // LNot always has type int. C99 6.5.3.3p5.
15159     // In C++, it's bool. C++ 5.3.1p8
15160     resultType = Context.getLogicalOperationType();
15161     break;
15162   case UO_Real:
15163   case UO_Imag:
15164     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15165     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15166     // complex l-values to ordinary l-values and all other values to r-values.
15167     if (Input.isInvalid()) return ExprError();
15168     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15169       if (Input.get()->isGLValue() &&
15170           Input.get()->getObjectKind() == OK_Ordinary)
15171         VK = Input.get()->getValueKind();
15172     } else if (!getLangOpts().CPlusPlus) {
15173       // In C, a volatile scalar is read by __imag. In C++, it is not.
15174       Input = DefaultLvalueConversion(Input.get());
15175     }
15176     break;
15177   case UO_Extension:
15178     resultType = Input.get()->getType();
15179     VK = Input.get()->getValueKind();
15180     OK = Input.get()->getObjectKind();
15181     break;
15182   case UO_Coawait:
15183     // It's unnecessary to represent the pass-through operator co_await in the
15184     // AST; just return the input expression instead.
15185     assert(!Input.get()->getType()->isDependentType() &&
15186                    "the co_await expression must be non-dependant before "
15187                    "building operator co_await");
15188     return Input;
15189   }
15190   if (resultType.isNull() || Input.isInvalid())
15191     return ExprError();
15192 
15193   // Check for array bounds violations in the operand of the UnaryOperator,
15194   // except for the '*' and '&' operators that have to be handled specially
15195   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15196   // that are explicitly defined as valid by the standard).
15197   if (Opc != UO_AddrOf && Opc != UO_Deref)
15198     CheckArrayAccess(Input.get());
15199 
15200   auto *UO =
15201       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15202                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15203 
15204   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15205       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15206       !isUnevaluatedContext())
15207     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15208 
15209   // Convert the result back to a half vector.
15210   if (ConvertHalfVec)
15211     return convertVector(UO, Context.HalfTy, *this);
15212   return UO;
15213 }
15214 
15215 /// Determine whether the given expression is a qualified member
15216 /// access expression, of a form that could be turned into a pointer to member
15217 /// with the address-of operator.
15218 bool Sema::isQualifiedMemberAccess(Expr *E) {
15219   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15220     if (!DRE->getQualifier())
15221       return false;
15222 
15223     ValueDecl *VD = DRE->getDecl();
15224     if (!VD->isCXXClassMember())
15225       return false;
15226 
15227     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15228       return true;
15229     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15230       return Method->isInstance();
15231 
15232     return false;
15233   }
15234 
15235   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15236     if (!ULE->getQualifier())
15237       return false;
15238 
15239     for (NamedDecl *D : ULE->decls()) {
15240       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15241         if (Method->isInstance())
15242           return true;
15243       } else {
15244         // Overload set does not contain methods.
15245         break;
15246       }
15247     }
15248 
15249     return false;
15250   }
15251 
15252   return false;
15253 }
15254 
15255 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15256                               UnaryOperatorKind Opc, Expr *Input) {
15257   // First things first: handle placeholders so that the
15258   // overloaded-operator check considers the right type.
15259   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15260     // Increment and decrement of pseudo-object references.
15261     if (pty->getKind() == BuiltinType::PseudoObject &&
15262         UnaryOperator::isIncrementDecrementOp(Opc))
15263       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15264 
15265     // extension is always a builtin operator.
15266     if (Opc == UO_Extension)
15267       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15268 
15269     // & gets special logic for several kinds of placeholder.
15270     // The builtin code knows what to do.
15271     if (Opc == UO_AddrOf &&
15272         (pty->getKind() == BuiltinType::Overload ||
15273          pty->getKind() == BuiltinType::UnknownAny ||
15274          pty->getKind() == BuiltinType::BoundMember))
15275       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15276 
15277     // Anything else needs to be handled now.
15278     ExprResult Result = CheckPlaceholderExpr(Input);
15279     if (Result.isInvalid()) return ExprError();
15280     Input = Result.get();
15281   }
15282 
15283   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15284       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15285       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15286     // Find all of the overloaded operators visible from this point.
15287     UnresolvedSet<16> Functions;
15288     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15289     if (S && OverOp != OO_None)
15290       LookupOverloadedOperatorName(OverOp, S, Functions);
15291 
15292     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15293   }
15294 
15295   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15296 }
15297 
15298 // Unary Operators.  'Tok' is the token for the operator.
15299 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15300                               tok::TokenKind Op, Expr *Input) {
15301   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15302 }
15303 
15304 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15305 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15306                                 LabelDecl *TheDecl) {
15307   TheDecl->markUsed(Context);
15308   // Create the AST node.  The address of a label always has type 'void*'.
15309   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15310                                      Context.getPointerType(Context.VoidTy));
15311 }
15312 
15313 void Sema::ActOnStartStmtExpr() {
15314   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15315 }
15316 
15317 void Sema::ActOnStmtExprError() {
15318   // Note that function is also called by TreeTransform when leaving a
15319   // StmtExpr scope without rebuilding anything.
15320 
15321   DiscardCleanupsInEvaluationContext();
15322   PopExpressionEvaluationContext();
15323 }
15324 
15325 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15326                                SourceLocation RPLoc) {
15327   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15328 }
15329 
15330 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15331                                SourceLocation RPLoc, unsigned TemplateDepth) {
15332   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15333   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15334 
15335   if (hasAnyUnrecoverableErrorsInThisFunction())
15336     DiscardCleanupsInEvaluationContext();
15337   assert(!Cleanup.exprNeedsCleanups() &&
15338          "cleanups within StmtExpr not correctly bound!");
15339   PopExpressionEvaluationContext();
15340 
15341   // FIXME: there are a variety of strange constraints to enforce here, for
15342   // example, it is not possible to goto into a stmt expression apparently.
15343   // More semantic analysis is needed.
15344 
15345   // If there are sub-stmts in the compound stmt, take the type of the last one
15346   // as the type of the stmtexpr.
15347   QualType Ty = Context.VoidTy;
15348   bool StmtExprMayBindToTemp = false;
15349   if (!Compound->body_empty()) {
15350     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15351     if (const auto *LastStmt =
15352             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15353       if (const Expr *Value = LastStmt->getExprStmt()) {
15354         StmtExprMayBindToTemp = true;
15355         Ty = Value->getType();
15356       }
15357     }
15358   }
15359 
15360   // FIXME: Check that expression type is complete/non-abstract; statement
15361   // expressions are not lvalues.
15362   Expr *ResStmtExpr =
15363       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15364   if (StmtExprMayBindToTemp)
15365     return MaybeBindToTemporary(ResStmtExpr);
15366   return ResStmtExpr;
15367 }
15368 
15369 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15370   if (ER.isInvalid())
15371     return ExprError();
15372 
15373   // Do function/array conversion on the last expression, but not
15374   // lvalue-to-rvalue.  However, initialize an unqualified type.
15375   ER = DefaultFunctionArrayConversion(ER.get());
15376   if (ER.isInvalid())
15377     return ExprError();
15378   Expr *E = ER.get();
15379 
15380   if (E->isTypeDependent())
15381     return E;
15382 
15383   // In ARC, if the final expression ends in a consume, splice
15384   // the consume out and bind it later.  In the alternate case
15385   // (when dealing with a retainable type), the result
15386   // initialization will create a produce.  In both cases the
15387   // result will be +1, and we'll need to balance that out with
15388   // a bind.
15389   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15390   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15391     return Cast->getSubExpr();
15392 
15393   // FIXME: Provide a better location for the initialization.
15394   return PerformCopyInitialization(
15395       InitializedEntity::InitializeStmtExprResult(
15396           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15397       SourceLocation(), E);
15398 }
15399 
15400 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15401                                       TypeSourceInfo *TInfo,
15402                                       ArrayRef<OffsetOfComponent> Components,
15403                                       SourceLocation RParenLoc) {
15404   QualType ArgTy = TInfo->getType();
15405   bool Dependent = ArgTy->isDependentType();
15406   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15407 
15408   // We must have at least one component that refers to the type, and the first
15409   // one is known to be a field designator.  Verify that the ArgTy represents
15410   // a struct/union/class.
15411   if (!Dependent && !ArgTy->isRecordType())
15412     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15413                        << ArgTy << TypeRange);
15414 
15415   // Type must be complete per C99 7.17p3 because a declaring a variable
15416   // with an incomplete type would be ill-formed.
15417   if (!Dependent
15418       && RequireCompleteType(BuiltinLoc, ArgTy,
15419                              diag::err_offsetof_incomplete_type, TypeRange))
15420     return ExprError();
15421 
15422   bool DidWarnAboutNonPOD = false;
15423   QualType CurrentType = ArgTy;
15424   SmallVector<OffsetOfNode, 4> Comps;
15425   SmallVector<Expr*, 4> Exprs;
15426   for (const OffsetOfComponent &OC : Components) {
15427     if (OC.isBrackets) {
15428       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15429       if (!CurrentType->isDependentType()) {
15430         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15431         if(!AT)
15432           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15433                            << CurrentType);
15434         CurrentType = AT->getElementType();
15435       } else
15436         CurrentType = Context.DependentTy;
15437 
15438       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15439       if (IdxRval.isInvalid())
15440         return ExprError();
15441       Expr *Idx = IdxRval.get();
15442 
15443       // The expression must be an integral expression.
15444       // FIXME: An integral constant expression?
15445       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15446           !Idx->getType()->isIntegerType())
15447         return ExprError(
15448             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15449             << Idx->getSourceRange());
15450 
15451       // Record this array index.
15452       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15453       Exprs.push_back(Idx);
15454       continue;
15455     }
15456 
15457     // Offset of a field.
15458     if (CurrentType->isDependentType()) {
15459       // We have the offset of a field, but we can't look into the dependent
15460       // type. Just record the identifier of the field.
15461       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15462       CurrentType = Context.DependentTy;
15463       continue;
15464     }
15465 
15466     // We need to have a complete type to look into.
15467     if (RequireCompleteType(OC.LocStart, CurrentType,
15468                             diag::err_offsetof_incomplete_type))
15469       return ExprError();
15470 
15471     // Look for the designated field.
15472     const RecordType *RC = CurrentType->getAs<RecordType>();
15473     if (!RC)
15474       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15475                        << CurrentType);
15476     RecordDecl *RD = RC->getDecl();
15477 
15478     // C++ [lib.support.types]p5:
15479     //   The macro offsetof accepts a restricted set of type arguments in this
15480     //   International Standard. type shall be a POD structure or a POD union
15481     //   (clause 9).
15482     // C++11 [support.types]p4:
15483     //   If type is not a standard-layout class (Clause 9), the results are
15484     //   undefined.
15485     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15486       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15487       unsigned DiagID =
15488         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15489                             : diag::ext_offsetof_non_pod_type;
15490 
15491       if (!IsSafe && !DidWarnAboutNonPOD &&
15492           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15493                               PDiag(DiagID)
15494                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15495                               << CurrentType))
15496         DidWarnAboutNonPOD = true;
15497     }
15498 
15499     // Look for the field.
15500     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15501     LookupQualifiedName(R, RD);
15502     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15503     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15504     if (!MemberDecl) {
15505       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15506         MemberDecl = IndirectMemberDecl->getAnonField();
15507     }
15508 
15509     if (!MemberDecl)
15510       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15511                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15512                                                               OC.LocEnd));
15513 
15514     // C99 7.17p3:
15515     //   (If the specified member is a bit-field, the behavior is undefined.)
15516     //
15517     // We diagnose this as an error.
15518     if (MemberDecl->isBitField()) {
15519       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15520         << MemberDecl->getDeclName()
15521         << SourceRange(BuiltinLoc, RParenLoc);
15522       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15523       return ExprError();
15524     }
15525 
15526     RecordDecl *Parent = MemberDecl->getParent();
15527     if (IndirectMemberDecl)
15528       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15529 
15530     // If the member was found in a base class, introduce OffsetOfNodes for
15531     // the base class indirections.
15532     CXXBasePaths Paths;
15533     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15534                       Paths)) {
15535       if (Paths.getDetectedVirtual()) {
15536         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15537           << MemberDecl->getDeclName()
15538           << SourceRange(BuiltinLoc, RParenLoc);
15539         return ExprError();
15540       }
15541 
15542       CXXBasePath &Path = Paths.front();
15543       for (const CXXBasePathElement &B : Path)
15544         Comps.push_back(OffsetOfNode(B.Base));
15545     }
15546 
15547     if (IndirectMemberDecl) {
15548       for (auto *FI : IndirectMemberDecl->chain()) {
15549         assert(isa<FieldDecl>(FI));
15550         Comps.push_back(OffsetOfNode(OC.LocStart,
15551                                      cast<FieldDecl>(FI), OC.LocEnd));
15552       }
15553     } else
15554       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15555 
15556     CurrentType = MemberDecl->getType().getNonReferenceType();
15557   }
15558 
15559   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15560                               Comps, Exprs, RParenLoc);
15561 }
15562 
15563 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15564                                       SourceLocation BuiltinLoc,
15565                                       SourceLocation TypeLoc,
15566                                       ParsedType ParsedArgTy,
15567                                       ArrayRef<OffsetOfComponent> Components,
15568                                       SourceLocation RParenLoc) {
15569 
15570   TypeSourceInfo *ArgTInfo;
15571   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15572   if (ArgTy.isNull())
15573     return ExprError();
15574 
15575   if (!ArgTInfo)
15576     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15577 
15578   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15579 }
15580 
15581 
15582 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15583                                  Expr *CondExpr,
15584                                  Expr *LHSExpr, Expr *RHSExpr,
15585                                  SourceLocation RPLoc) {
15586   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15587 
15588   ExprValueKind VK = VK_PRValue;
15589   ExprObjectKind OK = OK_Ordinary;
15590   QualType resType;
15591   bool CondIsTrue = false;
15592   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15593     resType = Context.DependentTy;
15594   } else {
15595     // The conditional expression is required to be a constant expression.
15596     llvm::APSInt condEval(32);
15597     ExprResult CondICE = VerifyIntegerConstantExpression(
15598         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15599     if (CondICE.isInvalid())
15600       return ExprError();
15601     CondExpr = CondICE.get();
15602     CondIsTrue = condEval.getZExtValue();
15603 
15604     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15605     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15606 
15607     resType = ActiveExpr->getType();
15608     VK = ActiveExpr->getValueKind();
15609     OK = ActiveExpr->getObjectKind();
15610   }
15611 
15612   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15613                                   resType, VK, OK, RPLoc, CondIsTrue);
15614 }
15615 
15616 //===----------------------------------------------------------------------===//
15617 // Clang Extensions.
15618 //===----------------------------------------------------------------------===//
15619 
15620 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15621 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15622   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15623 
15624   if (LangOpts.CPlusPlus) {
15625     MangleNumberingContext *MCtx;
15626     Decl *ManglingContextDecl;
15627     std::tie(MCtx, ManglingContextDecl) =
15628         getCurrentMangleNumberContext(Block->getDeclContext());
15629     if (MCtx) {
15630       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15631       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15632     }
15633   }
15634 
15635   PushBlockScope(CurScope, Block);
15636   CurContext->addDecl(Block);
15637   if (CurScope)
15638     PushDeclContext(CurScope, Block);
15639   else
15640     CurContext = Block;
15641 
15642   getCurBlock()->HasImplicitReturnType = true;
15643 
15644   // Enter a new evaluation context to insulate the block from any
15645   // cleanups from the enclosing full-expression.
15646   PushExpressionEvaluationContext(
15647       ExpressionEvaluationContext::PotentiallyEvaluated);
15648 }
15649 
15650 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15651                                Scope *CurScope) {
15652   assert(ParamInfo.getIdentifier() == nullptr &&
15653          "block-id should have no identifier!");
15654   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15655   BlockScopeInfo *CurBlock = getCurBlock();
15656 
15657   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15658   QualType T = Sig->getType();
15659 
15660   // FIXME: We should allow unexpanded parameter packs here, but that would,
15661   // in turn, make the block expression contain unexpanded parameter packs.
15662   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15663     // Drop the parameters.
15664     FunctionProtoType::ExtProtoInfo EPI;
15665     EPI.HasTrailingReturn = false;
15666     EPI.TypeQuals.addConst();
15667     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15668     Sig = Context.getTrivialTypeSourceInfo(T);
15669   }
15670 
15671   // GetTypeForDeclarator always produces a function type for a block
15672   // literal signature.  Furthermore, it is always a FunctionProtoType
15673   // unless the function was written with a typedef.
15674   assert(T->isFunctionType() &&
15675          "GetTypeForDeclarator made a non-function block signature");
15676 
15677   // Look for an explicit signature in that function type.
15678   FunctionProtoTypeLoc ExplicitSignature;
15679 
15680   if ((ExplicitSignature = Sig->getTypeLoc()
15681                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15682 
15683     // Check whether that explicit signature was synthesized by
15684     // GetTypeForDeclarator.  If so, don't save that as part of the
15685     // written signature.
15686     if (ExplicitSignature.getLocalRangeBegin() ==
15687         ExplicitSignature.getLocalRangeEnd()) {
15688       // This would be much cheaper if we stored TypeLocs instead of
15689       // TypeSourceInfos.
15690       TypeLoc Result = ExplicitSignature.getReturnLoc();
15691       unsigned Size = Result.getFullDataSize();
15692       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15693       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15694 
15695       ExplicitSignature = FunctionProtoTypeLoc();
15696     }
15697   }
15698 
15699   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15700   CurBlock->FunctionType = T;
15701 
15702   const auto *Fn = T->castAs<FunctionType>();
15703   QualType RetTy = Fn->getReturnType();
15704   bool isVariadic =
15705       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15706 
15707   CurBlock->TheDecl->setIsVariadic(isVariadic);
15708 
15709   // Context.DependentTy is used as a placeholder for a missing block
15710   // return type.  TODO:  what should we do with declarators like:
15711   //   ^ * { ... }
15712   // If the answer is "apply template argument deduction"....
15713   if (RetTy != Context.DependentTy) {
15714     CurBlock->ReturnType = RetTy;
15715     CurBlock->TheDecl->setBlockMissingReturnType(false);
15716     CurBlock->HasImplicitReturnType = false;
15717   }
15718 
15719   // Push block parameters from the declarator if we had them.
15720   SmallVector<ParmVarDecl*, 8> Params;
15721   if (ExplicitSignature) {
15722     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15723       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15724       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15725           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15726         // Diagnose this as an extension in C17 and earlier.
15727         if (!getLangOpts().C2x)
15728           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15729       }
15730       Params.push_back(Param);
15731     }
15732 
15733   // Fake up parameter variables if we have a typedef, like
15734   //   ^ fntype { ... }
15735   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15736     for (const auto &I : Fn->param_types()) {
15737       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15738           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15739       Params.push_back(Param);
15740     }
15741   }
15742 
15743   // Set the parameters on the block decl.
15744   if (!Params.empty()) {
15745     CurBlock->TheDecl->setParams(Params);
15746     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15747                              /*CheckParameterNames=*/false);
15748   }
15749 
15750   // Finally we can process decl attributes.
15751   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15752 
15753   // Put the parameter variables in scope.
15754   for (auto AI : CurBlock->TheDecl->parameters()) {
15755     AI->setOwningFunction(CurBlock->TheDecl);
15756 
15757     // If this has an identifier, add it to the scope stack.
15758     if (AI->getIdentifier()) {
15759       CheckShadow(CurBlock->TheScope, AI);
15760 
15761       PushOnScopeChains(AI, CurBlock->TheScope);
15762     }
15763   }
15764 }
15765 
15766 /// ActOnBlockError - If there is an error parsing a block, this callback
15767 /// is invoked to pop the information about the block from the action impl.
15768 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15769   // Leave the expression-evaluation context.
15770   DiscardCleanupsInEvaluationContext();
15771   PopExpressionEvaluationContext();
15772 
15773   // Pop off CurBlock, handle nested blocks.
15774   PopDeclContext();
15775   PopFunctionScopeInfo();
15776 }
15777 
15778 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15779 /// literal was successfully completed.  ^(int x){...}
15780 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15781                                     Stmt *Body, Scope *CurScope) {
15782   // If blocks are disabled, emit an error.
15783   if (!LangOpts.Blocks)
15784     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15785 
15786   // Leave the expression-evaluation context.
15787   if (hasAnyUnrecoverableErrorsInThisFunction())
15788     DiscardCleanupsInEvaluationContext();
15789   assert(!Cleanup.exprNeedsCleanups() &&
15790          "cleanups within block not correctly bound!");
15791   PopExpressionEvaluationContext();
15792 
15793   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15794   BlockDecl *BD = BSI->TheDecl;
15795 
15796   if (BSI->HasImplicitReturnType)
15797     deduceClosureReturnType(*BSI);
15798 
15799   QualType RetTy = Context.VoidTy;
15800   if (!BSI->ReturnType.isNull())
15801     RetTy = BSI->ReturnType;
15802 
15803   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15804   QualType BlockTy;
15805 
15806   // If the user wrote a function type in some form, try to use that.
15807   if (!BSI->FunctionType.isNull()) {
15808     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15809 
15810     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15811     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15812 
15813     // Turn protoless block types into nullary block types.
15814     if (isa<FunctionNoProtoType>(FTy)) {
15815       FunctionProtoType::ExtProtoInfo EPI;
15816       EPI.ExtInfo = Ext;
15817       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15818 
15819     // Otherwise, if we don't need to change anything about the function type,
15820     // preserve its sugar structure.
15821     } else if (FTy->getReturnType() == RetTy &&
15822                (!NoReturn || FTy->getNoReturnAttr())) {
15823       BlockTy = BSI->FunctionType;
15824 
15825     // Otherwise, make the minimal modifications to the function type.
15826     } else {
15827       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15828       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15829       EPI.TypeQuals = Qualifiers();
15830       EPI.ExtInfo = Ext;
15831       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15832     }
15833 
15834   // If we don't have a function type, just build one from nothing.
15835   } else {
15836     FunctionProtoType::ExtProtoInfo EPI;
15837     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15838     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15839   }
15840 
15841   DiagnoseUnusedParameters(BD->parameters());
15842   BlockTy = Context.getBlockPointerType(BlockTy);
15843 
15844   // If needed, diagnose invalid gotos and switches in the block.
15845   if (getCurFunction()->NeedsScopeChecking() &&
15846       !PP.isCodeCompletionEnabled())
15847     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15848 
15849   BD->setBody(cast<CompoundStmt>(Body));
15850 
15851   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15852     DiagnoseUnguardedAvailabilityViolations(BD);
15853 
15854   // Try to apply the named return value optimization. We have to check again
15855   // if we can do this, though, because blocks keep return statements around
15856   // to deduce an implicit return type.
15857   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15858       !BD->isDependentContext())
15859     computeNRVO(Body, BSI);
15860 
15861   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15862       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15863     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15864                           NTCUK_Destruct|NTCUK_Copy);
15865 
15866   PopDeclContext();
15867 
15868   // Set the captured variables on the block.
15869   SmallVector<BlockDecl::Capture, 4> Captures;
15870   for (Capture &Cap : BSI->Captures) {
15871     if (Cap.isInvalid() || Cap.isThisCapture())
15872       continue;
15873 
15874     VarDecl *Var = Cap.getVariable();
15875     Expr *CopyExpr = nullptr;
15876     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15877       if (const RecordType *Record =
15878               Cap.getCaptureType()->getAs<RecordType>()) {
15879         // The capture logic needs the destructor, so make sure we mark it.
15880         // Usually this is unnecessary because most local variables have
15881         // their destructors marked at declaration time, but parameters are
15882         // an exception because it's technically only the call site that
15883         // actually requires the destructor.
15884         if (isa<ParmVarDecl>(Var))
15885           FinalizeVarWithDestructor(Var, Record);
15886 
15887         // Enter a separate potentially-evaluated context while building block
15888         // initializers to isolate their cleanups from those of the block
15889         // itself.
15890         // FIXME: Is this appropriate even when the block itself occurs in an
15891         // unevaluated operand?
15892         EnterExpressionEvaluationContext EvalContext(
15893             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15894 
15895         SourceLocation Loc = Cap.getLocation();
15896 
15897         ExprResult Result = BuildDeclarationNameExpr(
15898             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15899 
15900         // According to the blocks spec, the capture of a variable from
15901         // the stack requires a const copy constructor.  This is not true
15902         // of the copy/move done to move a __block variable to the heap.
15903         if (!Result.isInvalid() &&
15904             !Result.get()->getType().isConstQualified()) {
15905           Result = ImpCastExprToType(Result.get(),
15906                                      Result.get()->getType().withConst(),
15907                                      CK_NoOp, VK_LValue);
15908         }
15909 
15910         if (!Result.isInvalid()) {
15911           Result = PerformCopyInitialization(
15912               InitializedEntity::InitializeBlock(Var->getLocation(),
15913                                                  Cap.getCaptureType()),
15914               Loc, Result.get());
15915         }
15916 
15917         // Build a full-expression copy expression if initialization
15918         // succeeded and used a non-trivial constructor.  Recover from
15919         // errors by pretending that the copy isn't necessary.
15920         if (!Result.isInvalid() &&
15921             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15922                 ->isTrivial()) {
15923           Result = MaybeCreateExprWithCleanups(Result);
15924           CopyExpr = Result.get();
15925         }
15926       }
15927     }
15928 
15929     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15930                               CopyExpr);
15931     Captures.push_back(NewCap);
15932   }
15933   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15934 
15935   // Pop the block scope now but keep it alive to the end of this function.
15936   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15937   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15938 
15939   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15940 
15941   // If the block isn't obviously global, i.e. it captures anything at
15942   // all, then we need to do a few things in the surrounding context:
15943   if (Result->getBlockDecl()->hasCaptures()) {
15944     // First, this expression has a new cleanup object.
15945     ExprCleanupObjects.push_back(Result->getBlockDecl());
15946     Cleanup.setExprNeedsCleanups(true);
15947 
15948     // It also gets a branch-protected scope if any of the captured
15949     // variables needs destruction.
15950     for (const auto &CI : Result->getBlockDecl()->captures()) {
15951       const VarDecl *var = CI.getVariable();
15952       if (var->getType().isDestructedType() != QualType::DK_none) {
15953         setFunctionHasBranchProtectedScope();
15954         break;
15955       }
15956     }
15957   }
15958 
15959   if (getCurFunction())
15960     getCurFunction()->addBlock(BD);
15961 
15962   return Result;
15963 }
15964 
15965 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15966                             SourceLocation RPLoc) {
15967   TypeSourceInfo *TInfo;
15968   GetTypeFromParser(Ty, &TInfo);
15969   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15970 }
15971 
15972 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15973                                 Expr *E, TypeSourceInfo *TInfo,
15974                                 SourceLocation RPLoc) {
15975   Expr *OrigExpr = E;
15976   bool IsMS = false;
15977 
15978   // CUDA device code does not support varargs.
15979   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15980     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15981       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15982       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15983         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15984     }
15985   }
15986 
15987   // NVPTX does not support va_arg expression.
15988   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15989       Context.getTargetInfo().getTriple().isNVPTX())
15990     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15991 
15992   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15993   // as Microsoft ABI on an actual Microsoft platform, where
15994   // __builtin_ms_va_list and __builtin_va_list are the same.)
15995   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15996       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15997     QualType MSVaListType = Context.getBuiltinMSVaListType();
15998     if (Context.hasSameType(MSVaListType, E->getType())) {
15999       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16000         return ExprError();
16001       IsMS = true;
16002     }
16003   }
16004 
16005   // Get the va_list type
16006   QualType VaListType = Context.getBuiltinVaListType();
16007   if (!IsMS) {
16008     if (VaListType->isArrayType()) {
16009       // Deal with implicit array decay; for example, on x86-64,
16010       // va_list is an array, but it's supposed to decay to
16011       // a pointer for va_arg.
16012       VaListType = Context.getArrayDecayedType(VaListType);
16013       // Make sure the input expression also decays appropriately.
16014       ExprResult Result = UsualUnaryConversions(E);
16015       if (Result.isInvalid())
16016         return ExprError();
16017       E = Result.get();
16018     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16019       // If va_list is a record type and we are compiling in C++ mode,
16020       // check the argument using reference binding.
16021       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16022           Context, Context.getLValueReferenceType(VaListType), false);
16023       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16024       if (Init.isInvalid())
16025         return ExprError();
16026       E = Init.getAs<Expr>();
16027     } else {
16028       // Otherwise, the va_list argument must be an l-value because
16029       // it is modified by va_arg.
16030       if (!E->isTypeDependent() &&
16031           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16032         return ExprError();
16033     }
16034   }
16035 
16036   if (!IsMS && !E->isTypeDependent() &&
16037       !Context.hasSameType(VaListType, E->getType()))
16038     return ExprError(
16039         Diag(E->getBeginLoc(),
16040              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16041         << OrigExpr->getType() << E->getSourceRange());
16042 
16043   if (!TInfo->getType()->isDependentType()) {
16044     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16045                             diag::err_second_parameter_to_va_arg_incomplete,
16046                             TInfo->getTypeLoc()))
16047       return ExprError();
16048 
16049     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16050                                TInfo->getType(),
16051                                diag::err_second_parameter_to_va_arg_abstract,
16052                                TInfo->getTypeLoc()))
16053       return ExprError();
16054 
16055     if (!TInfo->getType().isPODType(Context)) {
16056       Diag(TInfo->getTypeLoc().getBeginLoc(),
16057            TInfo->getType()->isObjCLifetimeType()
16058              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16059              : diag::warn_second_parameter_to_va_arg_not_pod)
16060         << TInfo->getType()
16061         << TInfo->getTypeLoc().getSourceRange();
16062     }
16063 
16064     // Check for va_arg where arguments of the given type will be promoted
16065     // (i.e. this va_arg is guaranteed to have undefined behavior).
16066     QualType PromoteType;
16067     if (TInfo->getType()->isPromotableIntegerType()) {
16068       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16069       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16070       // and C2x 7.16.1.1p2 says, in part:
16071       //   If type is not compatible with the type of the actual next argument
16072       //   (as promoted according to the default argument promotions), the
16073       //   behavior is undefined, except for the following cases:
16074       //     - both types are pointers to qualified or unqualified versions of
16075       //       compatible types;
16076       //     - one type is a signed integer type, the other type is the
16077       //       corresponding unsigned integer type, and the value is
16078       //       representable in both types;
16079       //     - one type is pointer to qualified or unqualified void and the
16080       //       other is a pointer to a qualified or unqualified character type.
16081       // Given that type compatibility is the primary requirement (ignoring
16082       // qualifications), you would think we could call typesAreCompatible()
16083       // directly to test this. However, in C++, that checks for *same type*,
16084       // which causes false positives when passing an enumeration type to
16085       // va_arg. Instead, get the underlying type of the enumeration and pass
16086       // that.
16087       QualType UnderlyingType = TInfo->getType();
16088       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16089         UnderlyingType = ET->getDecl()->getIntegerType();
16090       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16091                                      /*CompareUnqualified*/ true))
16092         PromoteType = QualType();
16093 
16094       // If the types are still not compatible, we need to test whether the
16095       // promoted type and the underlying type are the same except for
16096       // signedness. Ask the AST for the correctly corresponding type and see
16097       // if that's compatible.
16098       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16099           PromoteType->isUnsignedIntegerType() !=
16100               UnderlyingType->isUnsignedIntegerType()) {
16101         UnderlyingType =
16102             UnderlyingType->isUnsignedIntegerType()
16103                 ? Context.getCorrespondingSignedType(UnderlyingType)
16104                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16105         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16106                                        /*CompareUnqualified*/ true))
16107           PromoteType = QualType();
16108       }
16109     }
16110     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16111       PromoteType = Context.DoubleTy;
16112     if (!PromoteType.isNull())
16113       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16114                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16115                           << TInfo->getType()
16116                           << PromoteType
16117                           << TInfo->getTypeLoc().getSourceRange());
16118   }
16119 
16120   QualType T = TInfo->getType().getNonLValueExprType(Context);
16121   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16122 }
16123 
16124 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16125   // The type of __null will be int or long, depending on the size of
16126   // pointers on the target.
16127   QualType Ty;
16128   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16129   if (pw == Context.getTargetInfo().getIntWidth())
16130     Ty = Context.IntTy;
16131   else if (pw == Context.getTargetInfo().getLongWidth())
16132     Ty = Context.LongTy;
16133   else if (pw == Context.getTargetInfo().getLongLongWidth())
16134     Ty = Context.LongLongTy;
16135   else {
16136     llvm_unreachable("I don't know size of pointer!");
16137   }
16138 
16139   return new (Context) GNUNullExpr(Ty, TokenLoc);
16140 }
16141 
16142 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16143                                     SourceLocation BuiltinLoc,
16144                                     SourceLocation RPLoc) {
16145   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
16146 }
16147 
16148 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16149                                     SourceLocation BuiltinLoc,
16150                                     SourceLocation RPLoc,
16151                                     DeclContext *ParentContext) {
16152   return new (Context)
16153       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
16154 }
16155 
16156 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16157                                         bool Diagnose) {
16158   if (!getLangOpts().ObjC)
16159     return false;
16160 
16161   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16162   if (!PT)
16163     return false;
16164   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16165 
16166   // Ignore any parens, implicit casts (should only be
16167   // array-to-pointer decays), and not-so-opaque values.  The last is
16168   // important for making this trigger for property assignments.
16169   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16170   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16171     if (OV->getSourceExpr())
16172       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16173 
16174   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16175     if (!PT->isObjCIdType() &&
16176         !(ID && ID->getIdentifier()->isStr("NSString")))
16177       return false;
16178     if (!SL->isAscii())
16179       return false;
16180 
16181     if (Diagnose) {
16182       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16183           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16184       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16185     }
16186     return true;
16187   }
16188 
16189   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16190       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16191       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16192       !SrcExpr->isNullPointerConstant(
16193           getASTContext(), Expr::NPC_NeverValueDependent)) {
16194     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16195       return false;
16196     if (Diagnose) {
16197       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16198           << /*number*/1
16199           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16200       Expr *NumLit =
16201           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16202       if (NumLit)
16203         Exp = NumLit;
16204     }
16205     return true;
16206   }
16207 
16208   return false;
16209 }
16210 
16211 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16212                                               const Expr *SrcExpr) {
16213   if (!DstType->isFunctionPointerType() ||
16214       !SrcExpr->getType()->isFunctionType())
16215     return false;
16216 
16217   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16218   if (!DRE)
16219     return false;
16220 
16221   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16222   if (!FD)
16223     return false;
16224 
16225   return !S.checkAddressOfFunctionIsAvailable(FD,
16226                                               /*Complain=*/true,
16227                                               SrcExpr->getBeginLoc());
16228 }
16229 
16230 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16231                                     SourceLocation Loc,
16232                                     QualType DstType, QualType SrcType,
16233                                     Expr *SrcExpr, AssignmentAction Action,
16234                                     bool *Complained) {
16235   if (Complained)
16236     *Complained = false;
16237 
16238   // Decode the result (notice that AST's are still created for extensions).
16239   bool CheckInferredResultType = false;
16240   bool isInvalid = false;
16241   unsigned DiagKind = 0;
16242   ConversionFixItGenerator ConvHints;
16243   bool MayHaveConvFixit = false;
16244   bool MayHaveFunctionDiff = false;
16245   const ObjCInterfaceDecl *IFace = nullptr;
16246   const ObjCProtocolDecl *PDecl = nullptr;
16247 
16248   switch (ConvTy) {
16249   case Compatible:
16250       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16251       return false;
16252 
16253   case PointerToInt:
16254     if (getLangOpts().CPlusPlus) {
16255       DiagKind = diag::err_typecheck_convert_pointer_int;
16256       isInvalid = true;
16257     } else {
16258       DiagKind = diag::ext_typecheck_convert_pointer_int;
16259     }
16260     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16261     MayHaveConvFixit = true;
16262     break;
16263   case IntToPointer:
16264     if (getLangOpts().CPlusPlus) {
16265       DiagKind = diag::err_typecheck_convert_int_pointer;
16266       isInvalid = true;
16267     } else {
16268       DiagKind = diag::ext_typecheck_convert_int_pointer;
16269     }
16270     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16271     MayHaveConvFixit = true;
16272     break;
16273   case IncompatibleFunctionPointer:
16274     if (getLangOpts().CPlusPlus) {
16275       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16276       isInvalid = true;
16277     } else {
16278       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16279     }
16280     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16281     MayHaveConvFixit = true;
16282     break;
16283   case IncompatiblePointer:
16284     if (Action == AA_Passing_CFAudited) {
16285       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16286     } else if (getLangOpts().CPlusPlus) {
16287       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16288       isInvalid = true;
16289     } else {
16290       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16291     }
16292     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16293       SrcType->isObjCObjectPointerType();
16294     if (!CheckInferredResultType) {
16295       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16296     } else if (CheckInferredResultType) {
16297       SrcType = SrcType.getUnqualifiedType();
16298       DstType = DstType.getUnqualifiedType();
16299     }
16300     MayHaveConvFixit = true;
16301     break;
16302   case IncompatiblePointerSign:
16303     if (getLangOpts().CPlusPlus) {
16304       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16305       isInvalid = true;
16306     } else {
16307       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16308     }
16309     break;
16310   case FunctionVoidPointer:
16311     if (getLangOpts().CPlusPlus) {
16312       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16313       isInvalid = true;
16314     } else {
16315       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16316     }
16317     break;
16318   case IncompatiblePointerDiscardsQualifiers: {
16319     // Perform array-to-pointer decay if necessary.
16320     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16321 
16322     isInvalid = true;
16323 
16324     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16325     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16326     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16327       DiagKind = diag::err_typecheck_incompatible_address_space;
16328       break;
16329 
16330     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16331       DiagKind = diag::err_typecheck_incompatible_ownership;
16332       break;
16333     }
16334 
16335     llvm_unreachable("unknown error case for discarding qualifiers!");
16336     // fallthrough
16337   }
16338   case CompatiblePointerDiscardsQualifiers:
16339     // If the qualifiers lost were because we were applying the
16340     // (deprecated) C++ conversion from a string literal to a char*
16341     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16342     // Ideally, this check would be performed in
16343     // checkPointerTypesForAssignment. However, that would require a
16344     // bit of refactoring (so that the second argument is an
16345     // expression, rather than a type), which should be done as part
16346     // of a larger effort to fix checkPointerTypesForAssignment for
16347     // C++ semantics.
16348     if (getLangOpts().CPlusPlus &&
16349         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16350       return false;
16351     if (getLangOpts().CPlusPlus) {
16352       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16353       isInvalid = true;
16354     } else {
16355       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16356     }
16357 
16358     break;
16359   case IncompatibleNestedPointerQualifiers:
16360     if (getLangOpts().CPlusPlus) {
16361       isInvalid = true;
16362       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16363     } else {
16364       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16365     }
16366     break;
16367   case IncompatibleNestedPointerAddressSpaceMismatch:
16368     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16369     isInvalid = true;
16370     break;
16371   case IntToBlockPointer:
16372     DiagKind = diag::err_int_to_block_pointer;
16373     isInvalid = true;
16374     break;
16375   case IncompatibleBlockPointer:
16376     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16377     isInvalid = true;
16378     break;
16379   case IncompatibleObjCQualifiedId: {
16380     if (SrcType->isObjCQualifiedIdType()) {
16381       const ObjCObjectPointerType *srcOPT =
16382                 SrcType->castAs<ObjCObjectPointerType>();
16383       for (auto *srcProto : srcOPT->quals()) {
16384         PDecl = srcProto;
16385         break;
16386       }
16387       if (const ObjCInterfaceType *IFaceT =
16388             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16389         IFace = IFaceT->getDecl();
16390     }
16391     else if (DstType->isObjCQualifiedIdType()) {
16392       const ObjCObjectPointerType *dstOPT =
16393         DstType->castAs<ObjCObjectPointerType>();
16394       for (auto *dstProto : dstOPT->quals()) {
16395         PDecl = dstProto;
16396         break;
16397       }
16398       if (const ObjCInterfaceType *IFaceT =
16399             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16400         IFace = IFaceT->getDecl();
16401     }
16402     if (getLangOpts().CPlusPlus) {
16403       DiagKind = diag::err_incompatible_qualified_id;
16404       isInvalid = true;
16405     } else {
16406       DiagKind = diag::warn_incompatible_qualified_id;
16407     }
16408     break;
16409   }
16410   case IncompatibleVectors:
16411     if (getLangOpts().CPlusPlus) {
16412       DiagKind = diag::err_incompatible_vectors;
16413       isInvalid = true;
16414     } else {
16415       DiagKind = diag::warn_incompatible_vectors;
16416     }
16417     break;
16418   case IncompatibleObjCWeakRef:
16419     DiagKind = diag::err_arc_weak_unavailable_assign;
16420     isInvalid = true;
16421     break;
16422   case Incompatible:
16423     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16424       if (Complained)
16425         *Complained = true;
16426       return true;
16427     }
16428 
16429     DiagKind = diag::err_typecheck_convert_incompatible;
16430     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16431     MayHaveConvFixit = true;
16432     isInvalid = true;
16433     MayHaveFunctionDiff = true;
16434     break;
16435   }
16436 
16437   QualType FirstType, SecondType;
16438   switch (Action) {
16439   case AA_Assigning:
16440   case AA_Initializing:
16441     // The destination type comes first.
16442     FirstType = DstType;
16443     SecondType = SrcType;
16444     break;
16445 
16446   case AA_Returning:
16447   case AA_Passing:
16448   case AA_Passing_CFAudited:
16449   case AA_Converting:
16450   case AA_Sending:
16451   case AA_Casting:
16452     // The source type comes first.
16453     FirstType = SrcType;
16454     SecondType = DstType;
16455     break;
16456   }
16457 
16458   PartialDiagnostic FDiag = PDiag(DiagKind);
16459   if (Action == AA_Passing_CFAudited)
16460     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16461   else
16462     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16463 
16464   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16465       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16466     auto isPlainChar = [](const clang::Type *Type) {
16467       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16468              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16469     };
16470     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16471               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16472   }
16473 
16474   // If we can fix the conversion, suggest the FixIts.
16475   if (!ConvHints.isNull()) {
16476     for (FixItHint &H : ConvHints.Hints)
16477       FDiag << H;
16478   }
16479 
16480   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16481 
16482   if (MayHaveFunctionDiff)
16483     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16484 
16485   Diag(Loc, FDiag);
16486   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16487        DiagKind == diag::err_incompatible_qualified_id) &&
16488       PDecl && IFace && !IFace->hasDefinition())
16489     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16490         << IFace << PDecl;
16491 
16492   if (SecondType == Context.OverloadTy)
16493     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16494                               FirstType, /*TakingAddress=*/true);
16495 
16496   if (CheckInferredResultType)
16497     EmitRelatedResultTypeNote(SrcExpr);
16498 
16499   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16500     EmitRelatedResultTypeNoteForReturn(DstType);
16501 
16502   if (Complained)
16503     *Complained = true;
16504   return isInvalid;
16505 }
16506 
16507 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16508                                                  llvm::APSInt *Result,
16509                                                  AllowFoldKind CanFold) {
16510   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16511   public:
16512     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16513                                              QualType T) override {
16514       return S.Diag(Loc, diag::err_ice_not_integral)
16515              << T << S.LangOpts.CPlusPlus;
16516     }
16517     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16518       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16519     }
16520   } Diagnoser;
16521 
16522   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16523 }
16524 
16525 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16526                                                  llvm::APSInt *Result,
16527                                                  unsigned DiagID,
16528                                                  AllowFoldKind CanFold) {
16529   class IDDiagnoser : public VerifyICEDiagnoser {
16530     unsigned DiagID;
16531 
16532   public:
16533     IDDiagnoser(unsigned DiagID)
16534       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16535 
16536     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16537       return S.Diag(Loc, DiagID);
16538     }
16539   } Diagnoser(DiagID);
16540 
16541   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16542 }
16543 
16544 Sema::SemaDiagnosticBuilder
16545 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16546                                              QualType T) {
16547   return diagnoseNotICE(S, Loc);
16548 }
16549 
16550 Sema::SemaDiagnosticBuilder
16551 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16552   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16553 }
16554 
16555 ExprResult
16556 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16557                                       VerifyICEDiagnoser &Diagnoser,
16558                                       AllowFoldKind CanFold) {
16559   SourceLocation DiagLoc = E->getBeginLoc();
16560 
16561   if (getLangOpts().CPlusPlus11) {
16562     // C++11 [expr.const]p5:
16563     //   If an expression of literal class type is used in a context where an
16564     //   integral constant expression is required, then that class type shall
16565     //   have a single non-explicit conversion function to an integral or
16566     //   unscoped enumeration type
16567     ExprResult Converted;
16568     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16569       VerifyICEDiagnoser &BaseDiagnoser;
16570     public:
16571       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16572           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16573                                 BaseDiagnoser.Suppress, true),
16574             BaseDiagnoser(BaseDiagnoser) {}
16575 
16576       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16577                                            QualType T) override {
16578         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16579       }
16580 
16581       SemaDiagnosticBuilder diagnoseIncomplete(
16582           Sema &S, SourceLocation Loc, QualType T) override {
16583         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16584       }
16585 
16586       SemaDiagnosticBuilder diagnoseExplicitConv(
16587           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16588         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16589       }
16590 
16591       SemaDiagnosticBuilder noteExplicitConv(
16592           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16593         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16594                  << ConvTy->isEnumeralType() << ConvTy;
16595       }
16596 
16597       SemaDiagnosticBuilder diagnoseAmbiguous(
16598           Sema &S, SourceLocation Loc, QualType T) override {
16599         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16600       }
16601 
16602       SemaDiagnosticBuilder noteAmbiguous(
16603           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16604         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16605                  << ConvTy->isEnumeralType() << ConvTy;
16606       }
16607 
16608       SemaDiagnosticBuilder diagnoseConversion(
16609           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16610         llvm_unreachable("conversion functions are permitted");
16611       }
16612     } ConvertDiagnoser(Diagnoser);
16613 
16614     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16615                                                     ConvertDiagnoser);
16616     if (Converted.isInvalid())
16617       return Converted;
16618     E = Converted.get();
16619     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16620       return ExprError();
16621   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16622     // An ICE must be of integral or unscoped enumeration type.
16623     if (!Diagnoser.Suppress)
16624       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16625           << E->getSourceRange();
16626     return ExprError();
16627   }
16628 
16629   ExprResult RValueExpr = DefaultLvalueConversion(E);
16630   if (RValueExpr.isInvalid())
16631     return ExprError();
16632 
16633   E = RValueExpr.get();
16634 
16635   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16636   // in the non-ICE case.
16637   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16638     if (Result)
16639       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16640     if (!isa<ConstantExpr>(E))
16641       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16642                  : ConstantExpr::Create(Context, E);
16643     return E;
16644   }
16645 
16646   Expr::EvalResult EvalResult;
16647   SmallVector<PartialDiagnosticAt, 8> Notes;
16648   EvalResult.Diag = &Notes;
16649 
16650   // Try to evaluate the expression, and produce diagnostics explaining why it's
16651   // not a constant expression as a side-effect.
16652   bool Folded =
16653       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16654       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16655 
16656   if (!isa<ConstantExpr>(E))
16657     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16658 
16659   // In C++11, we can rely on diagnostics being produced for any expression
16660   // which is not a constant expression. If no diagnostics were produced, then
16661   // this is a constant expression.
16662   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16663     if (Result)
16664       *Result = EvalResult.Val.getInt();
16665     return E;
16666   }
16667 
16668   // If our only note is the usual "invalid subexpression" note, just point
16669   // the caret at its location rather than producing an essentially
16670   // redundant note.
16671   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16672         diag::note_invalid_subexpr_in_const_expr) {
16673     DiagLoc = Notes[0].first;
16674     Notes.clear();
16675   }
16676 
16677   if (!Folded || !CanFold) {
16678     if (!Diagnoser.Suppress) {
16679       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16680       for (const PartialDiagnosticAt &Note : Notes)
16681         Diag(Note.first, Note.second);
16682     }
16683 
16684     return ExprError();
16685   }
16686 
16687   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16688   for (const PartialDiagnosticAt &Note : Notes)
16689     Diag(Note.first, Note.second);
16690 
16691   if (Result)
16692     *Result = EvalResult.Val.getInt();
16693   return E;
16694 }
16695 
16696 namespace {
16697   // Handle the case where we conclude a expression which we speculatively
16698   // considered to be unevaluated is actually evaluated.
16699   class TransformToPE : public TreeTransform<TransformToPE> {
16700     typedef TreeTransform<TransformToPE> BaseTransform;
16701 
16702   public:
16703     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16704 
16705     // Make sure we redo semantic analysis
16706     bool AlwaysRebuild() { return true; }
16707     bool ReplacingOriginal() { return true; }
16708 
16709     // We need to special-case DeclRefExprs referring to FieldDecls which
16710     // are not part of a member pointer formation; normal TreeTransforming
16711     // doesn't catch this case because of the way we represent them in the AST.
16712     // FIXME: This is a bit ugly; is it really the best way to handle this
16713     // case?
16714     //
16715     // Error on DeclRefExprs referring to FieldDecls.
16716     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16717       if (isa<FieldDecl>(E->getDecl()) &&
16718           !SemaRef.isUnevaluatedContext())
16719         return SemaRef.Diag(E->getLocation(),
16720                             diag::err_invalid_non_static_member_use)
16721             << E->getDecl() << E->getSourceRange();
16722 
16723       return BaseTransform::TransformDeclRefExpr(E);
16724     }
16725 
16726     // Exception: filter out member pointer formation
16727     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16728       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16729         return E;
16730 
16731       return BaseTransform::TransformUnaryOperator(E);
16732     }
16733 
16734     // The body of a lambda-expression is in a separate expression evaluation
16735     // context so never needs to be transformed.
16736     // FIXME: Ideally we wouldn't transform the closure type either, and would
16737     // just recreate the capture expressions and lambda expression.
16738     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16739       return SkipLambdaBody(E, Body);
16740     }
16741   };
16742 }
16743 
16744 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16745   assert(isUnevaluatedContext() &&
16746          "Should only transform unevaluated expressions");
16747   ExprEvalContexts.back().Context =
16748       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16749   if (isUnevaluatedContext())
16750     return E;
16751   return TransformToPE(*this).TransformExpr(E);
16752 }
16753 
16754 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
16755   assert(isUnevaluatedContext() &&
16756          "Should only transform unevaluated expressions");
16757   ExprEvalContexts.back().Context =
16758       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
16759   if (isUnevaluatedContext())
16760     return TInfo;
16761   return TransformToPE(*this).TransformType(TInfo);
16762 }
16763 
16764 void
16765 Sema::PushExpressionEvaluationContext(
16766     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16767     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16768   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16769                                 LambdaContextDecl, ExprContext);
16770 
16771   // Discarded statements and immediate contexts nested in other
16772   // discarded statements or immediate context are themselves
16773   // a discarded statement or an immediate context, respectively.
16774   ExprEvalContexts.back().InDiscardedStatement =
16775       ExprEvalContexts[ExprEvalContexts.size() - 2]
16776           .isDiscardedStatementContext();
16777   ExprEvalContexts.back().InImmediateFunctionContext =
16778       ExprEvalContexts[ExprEvalContexts.size() - 2]
16779           .isImmediateFunctionContext();
16780 
16781   Cleanup.reset();
16782   if (!MaybeODRUseExprs.empty())
16783     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16784 }
16785 
16786 void
16787 Sema::PushExpressionEvaluationContext(
16788     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16789     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16790   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16791   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16792 }
16793 
16794 namespace {
16795 
16796 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16797   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16798   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16799     if (E->getOpcode() == UO_Deref)
16800       return CheckPossibleDeref(S, E->getSubExpr());
16801   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16802     return CheckPossibleDeref(S, E->getBase());
16803   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16804     return CheckPossibleDeref(S, E->getBase());
16805   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16806     QualType Inner;
16807     QualType Ty = E->getType();
16808     if (const auto *Ptr = Ty->getAs<PointerType>())
16809       Inner = Ptr->getPointeeType();
16810     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16811       Inner = Arr->getElementType();
16812     else
16813       return nullptr;
16814 
16815     if (Inner->hasAttr(attr::NoDeref))
16816       return E;
16817   }
16818   return nullptr;
16819 }
16820 
16821 } // namespace
16822 
16823 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16824   for (const Expr *E : Rec.PossibleDerefs) {
16825     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16826     if (DeclRef) {
16827       const ValueDecl *Decl = DeclRef->getDecl();
16828       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16829           << Decl->getName() << E->getSourceRange();
16830       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16831     } else {
16832       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16833           << E->getSourceRange();
16834     }
16835   }
16836   Rec.PossibleDerefs.clear();
16837 }
16838 
16839 /// Check whether E, which is either a discarded-value expression or an
16840 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16841 /// and if so, remove it from the list of volatile-qualified assignments that
16842 /// we are going to warn are deprecated.
16843 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16844   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16845     return;
16846 
16847   // Note: ignoring parens here is not justified by the standard rules, but
16848   // ignoring parentheses seems like a more reasonable approach, and this only
16849   // drives a deprecation warning so doesn't affect conformance.
16850   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16851     if (BO->getOpcode() == BO_Assign) {
16852       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16853       llvm::erase_value(LHSs, BO->getLHS());
16854     }
16855   }
16856 }
16857 
16858 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16859   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
16860       !Decl->isConsteval() || isConstantEvaluated() ||
16861       RebuildingImmediateInvocation || isImmediateFunctionContext())
16862     return E;
16863 
16864   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16865   /// It's OK if this fails; we'll also remove this in
16866   /// HandleImmediateInvocations, but catching it here allows us to avoid
16867   /// walking the AST looking for it in simple cases.
16868   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16869     if (auto *DeclRef =
16870             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16871       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16872 
16873   E = MaybeCreateExprWithCleanups(E);
16874 
16875   ConstantExpr *Res = ConstantExpr::Create(
16876       getASTContext(), E.get(),
16877       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16878                                    getASTContext()),
16879       /*IsImmediateInvocation*/ true);
16880   /// Value-dependent constant expressions should not be immediately
16881   /// evaluated until they are instantiated.
16882   if (!Res->isValueDependent())
16883     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16884   return Res;
16885 }
16886 
16887 static void EvaluateAndDiagnoseImmediateInvocation(
16888     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16889   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16890   Expr::EvalResult Eval;
16891   Eval.Diag = &Notes;
16892   ConstantExpr *CE = Candidate.getPointer();
16893   bool Result = CE->EvaluateAsConstantExpr(
16894       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16895   if (!Result || !Notes.empty()) {
16896     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16897     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16898       InnerExpr = FunctionalCast->getSubExpr();
16899     FunctionDecl *FD = nullptr;
16900     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16901       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16902     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16903       FD = Call->getConstructor();
16904     else
16905       llvm_unreachable("unhandled decl kind");
16906     assert(FD->isConsteval());
16907     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16908     for (auto &Note : Notes)
16909       SemaRef.Diag(Note.first, Note.second);
16910     return;
16911   }
16912   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16913 }
16914 
16915 static void RemoveNestedImmediateInvocation(
16916     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16917     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16918   struct ComplexRemove : TreeTransform<ComplexRemove> {
16919     using Base = TreeTransform<ComplexRemove>;
16920     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16921     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16922     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16923         CurrentII;
16924     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16925                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16926                   SmallVector<Sema::ImmediateInvocationCandidate,
16927                               4>::reverse_iterator Current)
16928         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16929     void RemoveImmediateInvocation(ConstantExpr* E) {
16930       auto It = std::find_if(CurrentII, IISet.rend(),
16931                              [E](Sema::ImmediateInvocationCandidate Elem) {
16932                                return Elem.getPointer() == E;
16933                              });
16934       assert(It != IISet.rend() &&
16935              "ConstantExpr marked IsImmediateInvocation should "
16936              "be present");
16937       It->setInt(1); // Mark as deleted
16938     }
16939     ExprResult TransformConstantExpr(ConstantExpr *E) {
16940       if (!E->isImmediateInvocation())
16941         return Base::TransformConstantExpr(E);
16942       RemoveImmediateInvocation(E);
16943       return Base::TransformExpr(E->getSubExpr());
16944     }
16945     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16946     /// we need to remove its DeclRefExpr from the DRSet.
16947     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16948       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16949       return Base::TransformCXXOperatorCallExpr(E);
16950     }
16951     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16952     /// here.
16953     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16954       if (!Init)
16955         return Init;
16956       /// ConstantExpr are the first layer of implicit node to be removed so if
16957       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16958       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16959         if (CE->isImmediateInvocation())
16960           RemoveImmediateInvocation(CE);
16961       return Base::TransformInitializer(Init, NotCopyInit);
16962     }
16963     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16964       DRSet.erase(E);
16965       return E;
16966     }
16967     bool AlwaysRebuild() { return false; }
16968     bool ReplacingOriginal() { return true; }
16969     bool AllowSkippingCXXConstructExpr() {
16970       bool Res = AllowSkippingFirstCXXConstructExpr;
16971       AllowSkippingFirstCXXConstructExpr = true;
16972       return Res;
16973     }
16974     bool AllowSkippingFirstCXXConstructExpr = true;
16975   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16976                 Rec.ImmediateInvocationCandidates, It);
16977 
16978   /// CXXConstructExpr with a single argument are getting skipped by
16979   /// TreeTransform in some situtation because they could be implicit. This
16980   /// can only occur for the top-level CXXConstructExpr because it is used
16981   /// nowhere in the expression being transformed therefore will not be rebuilt.
16982   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16983   /// skipping the first CXXConstructExpr.
16984   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16985     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16986 
16987   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16988   assert(Res.isUsable());
16989   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16990   It->getPointer()->setSubExpr(Res.get());
16991 }
16992 
16993 static void
16994 HandleImmediateInvocations(Sema &SemaRef,
16995                            Sema::ExpressionEvaluationContextRecord &Rec) {
16996   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16997        Rec.ReferenceToConsteval.size() == 0) ||
16998       SemaRef.RebuildingImmediateInvocation)
16999     return;
17000 
17001   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17002   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17003   /// need to remove ReferenceToConsteval in the immediate invocation.
17004   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17005 
17006     /// Prevent sema calls during the tree transform from adding pointers that
17007     /// are already in the sets.
17008     llvm::SaveAndRestore<bool> DisableIITracking(
17009         SemaRef.RebuildingImmediateInvocation, true);
17010 
17011     /// Prevent diagnostic during tree transfrom as they are duplicates
17012     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17013 
17014     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17015          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17016       if (!It->getInt())
17017         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17018   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17019              Rec.ReferenceToConsteval.size()) {
17020     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17021       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17022       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17023       bool VisitDeclRefExpr(DeclRefExpr *E) {
17024         DRSet.erase(E);
17025         return DRSet.size();
17026       }
17027     } Visitor(Rec.ReferenceToConsteval);
17028     Visitor.TraverseStmt(
17029         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17030   }
17031   for (auto CE : Rec.ImmediateInvocationCandidates)
17032     if (!CE.getInt())
17033       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17034   for (auto DR : Rec.ReferenceToConsteval) {
17035     auto *FD = cast<FunctionDecl>(DR->getDecl());
17036     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17037         << FD;
17038     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17039   }
17040 }
17041 
17042 void Sema::PopExpressionEvaluationContext() {
17043   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17044   unsigned NumTypos = Rec.NumTypos;
17045 
17046   if (!Rec.Lambdas.empty()) {
17047     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17048     if (!getLangOpts().CPlusPlus20 &&
17049         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17050          Rec.isUnevaluated() ||
17051          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17052       unsigned D;
17053       if (Rec.isUnevaluated()) {
17054         // C++11 [expr.prim.lambda]p2:
17055         //   A lambda-expression shall not appear in an unevaluated operand
17056         //   (Clause 5).
17057         D = diag::err_lambda_unevaluated_operand;
17058       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17059         // C++1y [expr.const]p2:
17060         //   A conditional-expression e is a core constant expression unless the
17061         //   evaluation of e, following the rules of the abstract machine, would
17062         //   evaluate [...] a lambda-expression.
17063         D = diag::err_lambda_in_constant_expression;
17064       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17065         // C++17 [expr.prim.lamda]p2:
17066         // A lambda-expression shall not appear [...] in a template-argument.
17067         D = diag::err_lambda_in_invalid_context;
17068       } else
17069         llvm_unreachable("Couldn't infer lambda error message.");
17070 
17071       for (const auto *L : Rec.Lambdas)
17072         Diag(L->getBeginLoc(), D);
17073     }
17074   }
17075 
17076   WarnOnPendingNoDerefs(Rec);
17077   HandleImmediateInvocations(*this, Rec);
17078 
17079   // Warn on any volatile-qualified simple-assignments that are not discarded-
17080   // value expressions nor unevaluated operands (those cases get removed from
17081   // this list by CheckUnusedVolatileAssignment).
17082   for (auto *BO : Rec.VolatileAssignmentLHSs)
17083     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17084         << BO->getType();
17085 
17086   // When are coming out of an unevaluated context, clear out any
17087   // temporaries that we may have created as part of the evaluation of
17088   // the expression in that context: they aren't relevant because they
17089   // will never be constructed.
17090   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17091     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17092                              ExprCleanupObjects.end());
17093     Cleanup = Rec.ParentCleanup;
17094     CleanupVarDeclMarking();
17095     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17096   // Otherwise, merge the contexts together.
17097   } else {
17098     Cleanup.mergeFrom(Rec.ParentCleanup);
17099     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17100                             Rec.SavedMaybeODRUseExprs.end());
17101   }
17102 
17103   // Pop the current expression evaluation context off the stack.
17104   ExprEvalContexts.pop_back();
17105 
17106   // The global expression evaluation context record is never popped.
17107   ExprEvalContexts.back().NumTypos += NumTypos;
17108 }
17109 
17110 void Sema::DiscardCleanupsInEvaluationContext() {
17111   ExprCleanupObjects.erase(
17112          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17113          ExprCleanupObjects.end());
17114   Cleanup.reset();
17115   MaybeODRUseExprs.clear();
17116 }
17117 
17118 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17119   ExprResult Result = CheckPlaceholderExpr(E);
17120   if (Result.isInvalid())
17121     return ExprError();
17122   E = Result.get();
17123   if (!E->getType()->isVariablyModifiedType())
17124     return E;
17125   return TransformToPotentiallyEvaluated(E);
17126 }
17127 
17128 /// Are we in a context that is potentially constant evaluated per C++20
17129 /// [expr.const]p12?
17130 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17131   /// C++2a [expr.const]p12:
17132   //   An expression or conversion is potentially constant evaluated if it is
17133   switch (SemaRef.ExprEvalContexts.back().Context) {
17134     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17135     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17136 
17137       // -- a manifestly constant-evaluated expression,
17138     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17139     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17140     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17141       // -- a potentially-evaluated expression,
17142     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17143       // -- an immediate subexpression of a braced-init-list,
17144 
17145       // -- [FIXME] an expression of the form & cast-expression that occurs
17146       //    within a templated entity
17147       // -- a subexpression of one of the above that is not a subexpression of
17148       // a nested unevaluated operand.
17149       return true;
17150 
17151     case Sema::ExpressionEvaluationContext::Unevaluated:
17152     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17153       // Expressions in this context are never evaluated.
17154       return false;
17155   }
17156   llvm_unreachable("Invalid context");
17157 }
17158 
17159 /// Return true if this function has a calling convention that requires mangling
17160 /// in the size of the parameter pack.
17161 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17162   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17163   // we don't need parameter type sizes.
17164   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17165   if (!TT.isOSWindows() || !TT.isX86())
17166     return false;
17167 
17168   // If this is C++ and this isn't an extern "C" function, parameters do not
17169   // need to be complete. In this case, C++ mangling will apply, which doesn't
17170   // use the size of the parameters.
17171   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17172     return false;
17173 
17174   // Stdcall, fastcall, and vectorcall need this special treatment.
17175   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17176   switch (CC) {
17177   case CC_X86StdCall:
17178   case CC_X86FastCall:
17179   case CC_X86VectorCall:
17180     return true;
17181   default:
17182     break;
17183   }
17184   return false;
17185 }
17186 
17187 /// Require that all of the parameter types of function be complete. Normally,
17188 /// parameter types are only required to be complete when a function is called
17189 /// or defined, but to mangle functions with certain calling conventions, the
17190 /// mangler needs to know the size of the parameter list. In this situation,
17191 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17192 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17193 /// result in a linker error. Clang doesn't implement this behavior, and instead
17194 /// attempts to error at compile time.
17195 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17196                                                   SourceLocation Loc) {
17197   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17198     FunctionDecl *FD;
17199     ParmVarDecl *Param;
17200 
17201   public:
17202     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17203         : FD(FD), Param(Param) {}
17204 
17205     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17206       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17207       StringRef CCName;
17208       switch (CC) {
17209       case CC_X86StdCall:
17210         CCName = "stdcall";
17211         break;
17212       case CC_X86FastCall:
17213         CCName = "fastcall";
17214         break;
17215       case CC_X86VectorCall:
17216         CCName = "vectorcall";
17217         break;
17218       default:
17219         llvm_unreachable("CC does not need mangling");
17220       }
17221 
17222       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17223           << Param->getDeclName() << FD->getDeclName() << CCName;
17224     }
17225   };
17226 
17227   for (ParmVarDecl *Param : FD->parameters()) {
17228     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17229     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17230   }
17231 }
17232 
17233 namespace {
17234 enum class OdrUseContext {
17235   /// Declarations in this context are not odr-used.
17236   None,
17237   /// Declarations in this context are formally odr-used, but this is a
17238   /// dependent context.
17239   Dependent,
17240   /// Declarations in this context are odr-used but not actually used (yet).
17241   FormallyOdrUsed,
17242   /// Declarations in this context are used.
17243   Used
17244 };
17245 }
17246 
17247 /// Are we within a context in which references to resolved functions or to
17248 /// variables result in odr-use?
17249 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17250   OdrUseContext Result;
17251 
17252   switch (SemaRef.ExprEvalContexts.back().Context) {
17253     case Sema::ExpressionEvaluationContext::Unevaluated:
17254     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17255     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17256       return OdrUseContext::None;
17257 
17258     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17259     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17260     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17261       Result = OdrUseContext::Used;
17262       break;
17263 
17264     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17265       Result = OdrUseContext::FormallyOdrUsed;
17266       break;
17267 
17268     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17269       // A default argument formally results in odr-use, but doesn't actually
17270       // result in a use in any real sense until it itself is used.
17271       Result = OdrUseContext::FormallyOdrUsed;
17272       break;
17273   }
17274 
17275   if (SemaRef.CurContext->isDependentContext())
17276     return OdrUseContext::Dependent;
17277 
17278   return Result;
17279 }
17280 
17281 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17282   if (!Func->isConstexpr())
17283     return false;
17284 
17285   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17286     return true;
17287   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17288   return CCD && CCD->getInheritedConstructor();
17289 }
17290 
17291 /// Mark a function referenced, and check whether it is odr-used
17292 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17293 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17294                                   bool MightBeOdrUse) {
17295   assert(Func && "No function?");
17296 
17297   Func->setReferenced();
17298 
17299   // Recursive functions aren't really used until they're used from some other
17300   // context.
17301   bool IsRecursiveCall = CurContext == Func;
17302 
17303   // C++11 [basic.def.odr]p3:
17304   //   A function whose name appears as a potentially-evaluated expression is
17305   //   odr-used if it is the unique lookup result or the selected member of a
17306   //   set of overloaded functions [...].
17307   //
17308   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17309   // can just check that here.
17310   OdrUseContext OdrUse =
17311       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17312   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17313     OdrUse = OdrUseContext::FormallyOdrUsed;
17314 
17315   // Trivial default constructors and destructors are never actually used.
17316   // FIXME: What about other special members?
17317   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17318       OdrUse == OdrUseContext::Used) {
17319     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17320       if (Constructor->isDefaultConstructor())
17321         OdrUse = OdrUseContext::FormallyOdrUsed;
17322     if (isa<CXXDestructorDecl>(Func))
17323       OdrUse = OdrUseContext::FormallyOdrUsed;
17324   }
17325 
17326   // C++20 [expr.const]p12:
17327   //   A function [...] is needed for constant evaluation if it is [...] a
17328   //   constexpr function that is named by an expression that is potentially
17329   //   constant evaluated
17330   bool NeededForConstantEvaluation =
17331       isPotentiallyConstantEvaluatedContext(*this) &&
17332       isImplicitlyDefinableConstexprFunction(Func);
17333 
17334   // Determine whether we require a function definition to exist, per
17335   // C++11 [temp.inst]p3:
17336   //   Unless a function template specialization has been explicitly
17337   //   instantiated or explicitly specialized, the function template
17338   //   specialization is implicitly instantiated when the specialization is
17339   //   referenced in a context that requires a function definition to exist.
17340   // C++20 [temp.inst]p7:
17341   //   The existence of a definition of a [...] function is considered to
17342   //   affect the semantics of the program if the [...] function is needed for
17343   //   constant evaluation by an expression
17344   // C++20 [basic.def.odr]p10:
17345   //   Every program shall contain exactly one definition of every non-inline
17346   //   function or variable that is odr-used in that program outside of a
17347   //   discarded statement
17348   // C++20 [special]p1:
17349   //   The implementation will implicitly define [defaulted special members]
17350   //   if they are odr-used or needed for constant evaluation.
17351   //
17352   // Note that we skip the implicit instantiation of templates that are only
17353   // used in unused default arguments or by recursive calls to themselves.
17354   // This is formally non-conforming, but seems reasonable in practice.
17355   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17356                                              NeededForConstantEvaluation);
17357 
17358   // C++14 [temp.expl.spec]p6:
17359   //   If a template [...] is explicitly specialized then that specialization
17360   //   shall be declared before the first use of that specialization that would
17361   //   cause an implicit instantiation to take place, in every translation unit
17362   //   in which such a use occurs
17363   if (NeedDefinition &&
17364       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17365        Func->getMemberSpecializationInfo()))
17366     checkSpecializationVisibility(Loc, Func);
17367 
17368   if (getLangOpts().CUDA)
17369     CheckCUDACall(Loc, Func);
17370 
17371   if (getLangOpts().SYCLIsDevice)
17372     checkSYCLDeviceFunction(Loc, Func);
17373 
17374   // If we need a definition, try to create one.
17375   if (NeedDefinition && !Func->getBody()) {
17376     runWithSufficientStackSpace(Loc, [&] {
17377       if (CXXConstructorDecl *Constructor =
17378               dyn_cast<CXXConstructorDecl>(Func)) {
17379         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17380         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17381           if (Constructor->isDefaultConstructor()) {
17382             if (Constructor->isTrivial() &&
17383                 !Constructor->hasAttr<DLLExportAttr>())
17384               return;
17385             DefineImplicitDefaultConstructor(Loc, Constructor);
17386           } else if (Constructor->isCopyConstructor()) {
17387             DefineImplicitCopyConstructor(Loc, Constructor);
17388           } else if (Constructor->isMoveConstructor()) {
17389             DefineImplicitMoveConstructor(Loc, Constructor);
17390           }
17391         } else if (Constructor->getInheritedConstructor()) {
17392           DefineInheritingConstructor(Loc, Constructor);
17393         }
17394       } else if (CXXDestructorDecl *Destructor =
17395                      dyn_cast<CXXDestructorDecl>(Func)) {
17396         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17397         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17398           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17399             return;
17400           DefineImplicitDestructor(Loc, Destructor);
17401         }
17402         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17403           MarkVTableUsed(Loc, Destructor->getParent());
17404       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17405         if (MethodDecl->isOverloadedOperator() &&
17406             MethodDecl->getOverloadedOperator() == OO_Equal) {
17407           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17408           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17409             if (MethodDecl->isCopyAssignmentOperator())
17410               DefineImplicitCopyAssignment(Loc, MethodDecl);
17411             else if (MethodDecl->isMoveAssignmentOperator())
17412               DefineImplicitMoveAssignment(Loc, MethodDecl);
17413           }
17414         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17415                    MethodDecl->getParent()->isLambda()) {
17416           CXXConversionDecl *Conversion =
17417               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17418           if (Conversion->isLambdaToBlockPointerConversion())
17419             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17420           else
17421             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17422         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17423           MarkVTableUsed(Loc, MethodDecl->getParent());
17424       }
17425 
17426       if (Func->isDefaulted() && !Func->isDeleted()) {
17427         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17428         if (DCK != DefaultedComparisonKind::None)
17429           DefineDefaultedComparison(Loc, Func, DCK);
17430       }
17431 
17432       // Implicit instantiation of function templates and member functions of
17433       // class templates.
17434       if (Func->isImplicitlyInstantiable()) {
17435         TemplateSpecializationKind TSK =
17436             Func->getTemplateSpecializationKindForInstantiation();
17437         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17438         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17439         if (FirstInstantiation) {
17440           PointOfInstantiation = Loc;
17441           if (auto *MSI = Func->getMemberSpecializationInfo())
17442             MSI->setPointOfInstantiation(Loc);
17443             // FIXME: Notify listener.
17444           else
17445             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17446         } else if (TSK != TSK_ImplicitInstantiation) {
17447           // Use the point of use as the point of instantiation, instead of the
17448           // point of explicit instantiation (which we track as the actual point
17449           // of instantiation). This gives better backtraces in diagnostics.
17450           PointOfInstantiation = Loc;
17451         }
17452 
17453         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17454             Func->isConstexpr()) {
17455           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17456               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17457               CodeSynthesisContexts.size())
17458             PendingLocalImplicitInstantiations.push_back(
17459                 std::make_pair(Func, PointOfInstantiation));
17460           else if (Func->isConstexpr())
17461             // Do not defer instantiations of constexpr functions, to avoid the
17462             // expression evaluator needing to call back into Sema if it sees a
17463             // call to such a function.
17464             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17465           else {
17466             Func->setInstantiationIsPending(true);
17467             PendingInstantiations.push_back(
17468                 std::make_pair(Func, PointOfInstantiation));
17469             // Notify the consumer that a function was implicitly instantiated.
17470             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17471           }
17472         }
17473       } else {
17474         // Walk redefinitions, as some of them may be instantiable.
17475         for (auto i : Func->redecls()) {
17476           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17477             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17478         }
17479       }
17480     });
17481   }
17482 
17483   // C++14 [except.spec]p17:
17484   //   An exception-specification is considered to be needed when:
17485   //   - the function is odr-used or, if it appears in an unevaluated operand,
17486   //     would be odr-used if the expression were potentially-evaluated;
17487   //
17488   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17489   // function is a pure virtual function we're calling, and in that case the
17490   // function was selected by overload resolution and we need to resolve its
17491   // exception specification for a different reason.
17492   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17493   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17494     ResolveExceptionSpec(Loc, FPT);
17495 
17496   // If this is the first "real" use, act on that.
17497   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17498     // Keep track of used but undefined functions.
17499     if (!Func->isDefined()) {
17500       if (mightHaveNonExternalLinkage(Func))
17501         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17502       else if (Func->getMostRecentDecl()->isInlined() &&
17503                !LangOpts.GNUInline &&
17504                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17505         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17506       else if (isExternalWithNoLinkageType(Func))
17507         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17508     }
17509 
17510     // Some x86 Windows calling conventions mangle the size of the parameter
17511     // pack into the name. Computing the size of the parameters requires the
17512     // parameter types to be complete. Check that now.
17513     if (funcHasParameterSizeMangling(*this, Func))
17514       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17515 
17516     // In the MS C++ ABI, the compiler emits destructor variants where they are
17517     // used. If the destructor is used here but defined elsewhere, mark the
17518     // virtual base destructors referenced. If those virtual base destructors
17519     // are inline, this will ensure they are defined when emitting the complete
17520     // destructor variant. This checking may be redundant if the destructor is
17521     // provided later in this TU.
17522     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17523       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17524         CXXRecordDecl *Parent = Dtor->getParent();
17525         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17526           CheckCompleteDestructorVariant(Loc, Dtor);
17527       }
17528     }
17529 
17530     Func->markUsed(Context);
17531   }
17532 }
17533 
17534 /// Directly mark a variable odr-used. Given a choice, prefer to use
17535 /// MarkVariableReferenced since it does additional checks and then
17536 /// calls MarkVarDeclODRUsed.
17537 /// If the variable must be captured:
17538 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17539 ///  - else capture it in the DeclContext that maps to the
17540 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17541 static void
17542 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17543                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17544   // Keep track of used but undefined variables.
17545   // FIXME: We shouldn't suppress this warning for static data members.
17546   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17547       (!Var->isExternallyVisible() || Var->isInline() ||
17548        SemaRef.isExternalWithNoLinkageType(Var)) &&
17549       !(Var->isStaticDataMember() && Var->hasInit())) {
17550     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17551     if (old.isInvalid())
17552       old = Loc;
17553   }
17554   QualType CaptureType, DeclRefType;
17555   if (SemaRef.LangOpts.OpenMP)
17556     SemaRef.tryCaptureOpenMPLambdas(Var);
17557   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17558     /*EllipsisLoc*/ SourceLocation(),
17559     /*BuildAndDiagnose*/ true,
17560     CaptureType, DeclRefType,
17561     FunctionScopeIndexToStopAt);
17562 
17563   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
17564     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17565     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17566     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17567     if (VarTarget == Sema::CVT_Host &&
17568         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17569          UserTarget == Sema::CFT_Global)) {
17570       // Diagnose ODR-use of host global variables in device functions.
17571       // Reference of device global variables in host functions is allowed
17572       // through shadow variables therefore it is not diagnosed.
17573       if (SemaRef.LangOpts.CUDAIsDevice) {
17574         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17575             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17576         SemaRef.targetDiag(Var->getLocation(),
17577                            Var->getType().isConstQualified()
17578                                ? diag::note_cuda_const_var_unpromoted
17579                                : diag::note_cuda_host_var);
17580       }
17581     } else if (VarTarget == Sema::CVT_Device &&
17582                (UserTarget == Sema::CFT_Host ||
17583                 UserTarget == Sema::CFT_HostDevice) &&
17584                !Var->hasExternalStorage()) {
17585       // Record a CUDA/HIP device side variable if it is ODR-used
17586       // by host code. This is done conservatively, when the variable is
17587       // referenced in any of the following contexts:
17588       //   - a non-function context
17589       //   - a host function
17590       //   - a host device function
17591       // This makes the ODR-use of the device side variable by host code to
17592       // be visible in the device compilation for the compiler to be able to
17593       // emit template variables instantiated by host code only and to
17594       // externalize the static device side variable ODR-used by host code.
17595       SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17596     }
17597   }
17598 
17599   Var->markUsed(SemaRef.Context);
17600 }
17601 
17602 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17603                                              SourceLocation Loc,
17604                                              unsigned CapturingScopeIndex) {
17605   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17606 }
17607 
17608 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17609                                                ValueDecl *var) {
17610   DeclContext *VarDC = var->getDeclContext();
17611 
17612   //  If the parameter still belongs to the translation unit, then
17613   //  we're actually just using one parameter in the declaration of
17614   //  the next.
17615   if (isa<ParmVarDecl>(var) &&
17616       isa<TranslationUnitDecl>(VarDC))
17617     return;
17618 
17619   // For C code, don't diagnose about capture if we're not actually in code
17620   // right now; it's impossible to write a non-constant expression outside of
17621   // function context, so we'll get other (more useful) diagnostics later.
17622   //
17623   // For C++, things get a bit more nasty... it would be nice to suppress this
17624   // diagnostic for certain cases like using a local variable in an array bound
17625   // for a member of a local class, but the correct predicate is not obvious.
17626   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17627     return;
17628 
17629   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17630   unsigned ContextKind = 3; // unknown
17631   if (isa<CXXMethodDecl>(VarDC) &&
17632       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17633     ContextKind = 2;
17634   } else if (isa<FunctionDecl>(VarDC)) {
17635     ContextKind = 0;
17636   } else if (isa<BlockDecl>(VarDC)) {
17637     ContextKind = 1;
17638   }
17639 
17640   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17641     << var << ValueKind << ContextKind << VarDC;
17642   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17643       << var;
17644 
17645   // FIXME: Add additional diagnostic info about class etc. which prevents
17646   // capture.
17647 }
17648 
17649 
17650 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17651                                       bool &SubCapturesAreNested,
17652                                       QualType &CaptureType,
17653                                       QualType &DeclRefType) {
17654    // Check whether we've already captured it.
17655   if (CSI->CaptureMap.count(Var)) {
17656     // If we found a capture, any subcaptures are nested.
17657     SubCapturesAreNested = true;
17658 
17659     // Retrieve the capture type for this variable.
17660     CaptureType = CSI->getCapture(Var).getCaptureType();
17661 
17662     // Compute the type of an expression that refers to this variable.
17663     DeclRefType = CaptureType.getNonReferenceType();
17664 
17665     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17666     // are mutable in the sense that user can change their value - they are
17667     // private instances of the captured declarations.
17668     const Capture &Cap = CSI->getCapture(Var);
17669     if (Cap.isCopyCapture() &&
17670         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17671         !(isa<CapturedRegionScopeInfo>(CSI) &&
17672           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17673       DeclRefType.addConst();
17674     return true;
17675   }
17676   return false;
17677 }
17678 
17679 // Only block literals, captured statements, and lambda expressions can
17680 // capture; other scopes don't work.
17681 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17682                                  SourceLocation Loc,
17683                                  const bool Diagnose, Sema &S) {
17684   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17685     return getLambdaAwareParentOfDeclContext(DC);
17686   else if (Var->hasLocalStorage()) {
17687     if (Diagnose)
17688        diagnoseUncapturableValueReference(S, Loc, Var);
17689   }
17690   return nullptr;
17691 }
17692 
17693 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17694 // certain types of variables (unnamed, variably modified types etc.)
17695 // so check for eligibility.
17696 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17697                                  SourceLocation Loc,
17698                                  const bool Diagnose, Sema &S) {
17699 
17700   bool IsBlock = isa<BlockScopeInfo>(CSI);
17701   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17702 
17703   // Lambdas are not allowed to capture unnamed variables
17704   // (e.g. anonymous unions).
17705   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17706   // assuming that's the intent.
17707   if (IsLambda && !Var->getDeclName()) {
17708     if (Diagnose) {
17709       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17710       S.Diag(Var->getLocation(), diag::note_declared_at);
17711     }
17712     return false;
17713   }
17714 
17715   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17716   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17717     if (Diagnose) {
17718       S.Diag(Loc, diag::err_ref_vm_type);
17719       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17720     }
17721     return false;
17722   }
17723   // Prohibit structs with flexible array members too.
17724   // We cannot capture what is in the tail end of the struct.
17725   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17726     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17727       if (Diagnose) {
17728         if (IsBlock)
17729           S.Diag(Loc, diag::err_ref_flexarray_type);
17730         else
17731           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17732         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17733       }
17734       return false;
17735     }
17736   }
17737   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17738   // Lambdas and captured statements are not allowed to capture __block
17739   // variables; they don't support the expected semantics.
17740   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17741     if (Diagnose) {
17742       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17743       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17744     }
17745     return false;
17746   }
17747   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17748   if (S.getLangOpts().OpenCL && IsBlock &&
17749       Var->getType()->isBlockPointerType()) {
17750     if (Diagnose)
17751       S.Diag(Loc, diag::err_opencl_block_ref_block);
17752     return false;
17753   }
17754 
17755   return true;
17756 }
17757 
17758 // Returns true if the capture by block was successful.
17759 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17760                                  SourceLocation Loc,
17761                                  const bool BuildAndDiagnose,
17762                                  QualType &CaptureType,
17763                                  QualType &DeclRefType,
17764                                  const bool Nested,
17765                                  Sema &S, bool Invalid) {
17766   bool ByRef = false;
17767 
17768   // Blocks are not allowed to capture arrays, excepting OpenCL.
17769   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17770   // (decayed to pointers).
17771   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17772     if (BuildAndDiagnose) {
17773       S.Diag(Loc, diag::err_ref_array_type);
17774       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17775       Invalid = true;
17776     } else {
17777       return false;
17778     }
17779   }
17780 
17781   // Forbid the block-capture of autoreleasing variables.
17782   if (!Invalid &&
17783       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17784     if (BuildAndDiagnose) {
17785       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17786         << /*block*/ 0;
17787       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17788       Invalid = true;
17789     } else {
17790       return false;
17791     }
17792   }
17793 
17794   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17795   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17796     QualType PointeeTy = PT->getPointeeType();
17797 
17798     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17799         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17800         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17801       if (BuildAndDiagnose) {
17802         SourceLocation VarLoc = Var->getLocation();
17803         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17804         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17805       }
17806     }
17807   }
17808 
17809   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17810   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17811       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17812     // Block capture by reference does not change the capture or
17813     // declaration reference types.
17814     ByRef = true;
17815   } else {
17816     // Block capture by copy introduces 'const'.
17817     CaptureType = CaptureType.getNonReferenceType().withConst();
17818     DeclRefType = CaptureType;
17819   }
17820 
17821   // Actually capture the variable.
17822   if (BuildAndDiagnose)
17823     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17824                     CaptureType, Invalid);
17825 
17826   return !Invalid;
17827 }
17828 
17829 
17830 /// Capture the given variable in the captured region.
17831 static bool captureInCapturedRegion(
17832     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17833     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17834     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17835     bool IsTopScope, Sema &S, bool Invalid) {
17836   // By default, capture variables by reference.
17837   bool ByRef = true;
17838   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17839     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17840   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17841     // Using an LValue reference type is consistent with Lambdas (see below).
17842     if (S.isOpenMPCapturedDecl(Var)) {
17843       bool HasConst = DeclRefType.isConstQualified();
17844       DeclRefType = DeclRefType.getUnqualifiedType();
17845       // Don't lose diagnostics about assignments to const.
17846       if (HasConst)
17847         DeclRefType.addConst();
17848     }
17849     // Do not capture firstprivates in tasks.
17850     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17851         OMPC_unknown)
17852       return true;
17853     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17854                                     RSI->OpenMPCaptureLevel);
17855   }
17856 
17857   if (ByRef)
17858     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17859   else
17860     CaptureType = DeclRefType;
17861 
17862   // Actually capture the variable.
17863   if (BuildAndDiagnose)
17864     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17865                     Loc, SourceLocation(), CaptureType, Invalid);
17866 
17867   return !Invalid;
17868 }
17869 
17870 /// Capture the given variable in the lambda.
17871 static bool captureInLambda(LambdaScopeInfo *LSI,
17872                             VarDecl *Var,
17873                             SourceLocation Loc,
17874                             const bool BuildAndDiagnose,
17875                             QualType &CaptureType,
17876                             QualType &DeclRefType,
17877                             const bool RefersToCapturedVariable,
17878                             const Sema::TryCaptureKind Kind,
17879                             SourceLocation EllipsisLoc,
17880                             const bool IsTopScope,
17881                             Sema &S, bool Invalid) {
17882   // Determine whether we are capturing by reference or by value.
17883   bool ByRef = false;
17884   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17885     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17886   } else {
17887     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17888   }
17889 
17890   // Compute the type of the field that will capture this variable.
17891   if (ByRef) {
17892     // C++11 [expr.prim.lambda]p15:
17893     //   An entity is captured by reference if it is implicitly or
17894     //   explicitly captured but not captured by copy. It is
17895     //   unspecified whether additional unnamed non-static data
17896     //   members are declared in the closure type for entities
17897     //   captured by reference.
17898     //
17899     // FIXME: It is not clear whether we want to build an lvalue reference
17900     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17901     // to do the former, while EDG does the latter. Core issue 1249 will
17902     // clarify, but for now we follow GCC because it's a more permissive and
17903     // easily defensible position.
17904     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17905   } else {
17906     // C++11 [expr.prim.lambda]p14:
17907     //   For each entity captured by copy, an unnamed non-static
17908     //   data member is declared in the closure type. The
17909     //   declaration order of these members is unspecified. The type
17910     //   of such a data member is the type of the corresponding
17911     //   captured entity if the entity is not a reference to an
17912     //   object, or the referenced type otherwise. [Note: If the
17913     //   captured entity is a reference to a function, the
17914     //   corresponding data member is also a reference to a
17915     //   function. - end note ]
17916     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17917       if (!RefType->getPointeeType()->isFunctionType())
17918         CaptureType = RefType->getPointeeType();
17919     }
17920 
17921     // Forbid the lambda copy-capture of autoreleasing variables.
17922     if (!Invalid &&
17923         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17924       if (BuildAndDiagnose) {
17925         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17926         S.Diag(Var->getLocation(), diag::note_previous_decl)
17927           << Var->getDeclName();
17928         Invalid = true;
17929       } else {
17930         return false;
17931       }
17932     }
17933 
17934     // Make sure that by-copy captures are of a complete and non-abstract type.
17935     if (!Invalid && BuildAndDiagnose) {
17936       if (!CaptureType->isDependentType() &&
17937           S.RequireCompleteSizedType(
17938               Loc, CaptureType,
17939               diag::err_capture_of_incomplete_or_sizeless_type,
17940               Var->getDeclName()))
17941         Invalid = true;
17942       else if (S.RequireNonAbstractType(Loc, CaptureType,
17943                                         diag::err_capture_of_abstract_type))
17944         Invalid = true;
17945     }
17946   }
17947 
17948   // Compute the type of a reference to this captured variable.
17949   if (ByRef)
17950     DeclRefType = CaptureType.getNonReferenceType();
17951   else {
17952     // C++ [expr.prim.lambda]p5:
17953     //   The closure type for a lambda-expression has a public inline
17954     //   function call operator [...]. This function call operator is
17955     //   declared const (9.3.1) if and only if the lambda-expression's
17956     //   parameter-declaration-clause is not followed by mutable.
17957     DeclRefType = CaptureType.getNonReferenceType();
17958     if (!LSI->Mutable && !CaptureType->isReferenceType())
17959       DeclRefType.addConst();
17960   }
17961 
17962   // Add the capture.
17963   if (BuildAndDiagnose)
17964     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17965                     Loc, EllipsisLoc, CaptureType, Invalid);
17966 
17967   return !Invalid;
17968 }
17969 
17970 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17971   // Offer a Copy fix even if the type is dependent.
17972   if (Var->getType()->isDependentType())
17973     return true;
17974   QualType T = Var->getType().getNonReferenceType();
17975   if (T.isTriviallyCopyableType(Context))
17976     return true;
17977   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17978 
17979     if (!(RD = RD->getDefinition()))
17980       return false;
17981     if (RD->hasSimpleCopyConstructor())
17982       return true;
17983     if (RD->hasUserDeclaredCopyConstructor())
17984       for (CXXConstructorDecl *Ctor : RD->ctors())
17985         if (Ctor->isCopyConstructor())
17986           return !Ctor->isDeleted();
17987   }
17988   return false;
17989 }
17990 
17991 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17992 /// default capture. Fixes may be omitted if they aren't allowed by the
17993 /// standard, for example we can't emit a default copy capture fix-it if we
17994 /// already explicitly copy capture capture another variable.
17995 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17996                                     VarDecl *Var) {
17997   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17998   // Don't offer Capture by copy of default capture by copy fixes if Var is
17999   // known not to be copy constructible.
18000   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18001 
18002   SmallString<32> FixBuffer;
18003   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18004   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18005     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18006     if (ShouldOfferCopyFix) {
18007       // Offer fixes to insert an explicit capture for the variable.
18008       // [] -> [VarName]
18009       // [OtherCapture] -> [OtherCapture, VarName]
18010       FixBuffer.assign({Separator, Var->getName()});
18011       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18012           << Var << /*value*/ 0
18013           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18014     }
18015     // As above but capture by reference.
18016     FixBuffer.assign({Separator, "&", Var->getName()});
18017     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18018         << Var << /*reference*/ 1
18019         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18020   }
18021 
18022   // Only try to offer default capture if there are no captures excluding this
18023   // and init captures.
18024   // [this]: OK.
18025   // [X = Y]: OK.
18026   // [&A, &B]: Don't offer.
18027   // [A, B]: Don't offer.
18028   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18029         return !C.isThisCapture() && !C.isInitCapture();
18030       }))
18031     return;
18032 
18033   // The default capture specifiers, '=' or '&', must appear first in the
18034   // capture body.
18035   SourceLocation DefaultInsertLoc =
18036       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18037 
18038   if (ShouldOfferCopyFix) {
18039     bool CanDefaultCopyCapture = true;
18040     // [=, *this] OK since c++17
18041     // [=, this] OK since c++20
18042     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18043       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18044                                   ? LSI->getCXXThisCapture().isCopyCapture()
18045                                   : false;
18046     // We can't use default capture by copy if any captures already specified
18047     // capture by copy.
18048     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18049           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18050         })) {
18051       FixBuffer.assign({"=", Separator});
18052       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18053           << /*value*/ 0
18054           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18055     }
18056   }
18057 
18058   // We can't use default capture by reference if any captures already specified
18059   // capture by reference.
18060   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18061         return !C.isInitCapture() && C.isReferenceCapture() &&
18062                !C.isThisCapture();
18063       })) {
18064     FixBuffer.assign({"&", Separator});
18065     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18066         << /*reference*/ 1
18067         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18068   }
18069 }
18070 
18071 bool Sema::tryCaptureVariable(
18072     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18073     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18074     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18075   // An init-capture is notionally from the context surrounding its
18076   // declaration, but its parent DC is the lambda class.
18077   DeclContext *VarDC = Var->getDeclContext();
18078   if (Var->isInitCapture())
18079     VarDC = VarDC->getParent();
18080 
18081   DeclContext *DC = CurContext;
18082   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18083       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18084   // We need to sync up the Declaration Context with the
18085   // FunctionScopeIndexToStopAt
18086   if (FunctionScopeIndexToStopAt) {
18087     unsigned FSIndex = FunctionScopes.size() - 1;
18088     while (FSIndex != MaxFunctionScopesIndex) {
18089       DC = getLambdaAwareParentOfDeclContext(DC);
18090       --FSIndex;
18091     }
18092   }
18093 
18094 
18095   // If the variable is declared in the current context, there is no need to
18096   // capture it.
18097   if (VarDC == DC) return true;
18098 
18099   // Capture global variables if it is required to use private copy of this
18100   // variable.
18101   bool IsGlobal = !Var->hasLocalStorage();
18102   if (IsGlobal &&
18103       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18104                                                 MaxFunctionScopesIndex)))
18105     return true;
18106   Var = Var->getCanonicalDecl();
18107 
18108   // Walk up the stack to determine whether we can capture the variable,
18109   // performing the "simple" checks that don't depend on type. We stop when
18110   // we've either hit the declared scope of the variable or find an existing
18111   // capture of that variable.  We start from the innermost capturing-entity
18112   // (the DC) and ensure that all intervening capturing-entities
18113   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18114   // declcontext can either capture the variable or have already captured
18115   // the variable.
18116   CaptureType = Var->getType();
18117   DeclRefType = CaptureType.getNonReferenceType();
18118   bool Nested = false;
18119   bool Explicit = (Kind != TryCapture_Implicit);
18120   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18121   do {
18122     // Only block literals, captured statements, and lambda expressions can
18123     // capture; other scopes don't work.
18124     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18125                                                               ExprLoc,
18126                                                               BuildAndDiagnose,
18127                                                               *this);
18128     // We need to check for the parent *first* because, if we *have*
18129     // private-captured a global variable, we need to recursively capture it in
18130     // intermediate blocks, lambdas, etc.
18131     if (!ParentDC) {
18132       if (IsGlobal) {
18133         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18134         break;
18135       }
18136       return true;
18137     }
18138 
18139     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18140     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18141 
18142 
18143     // Check whether we've already captured it.
18144     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18145                                              DeclRefType)) {
18146       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18147       break;
18148     }
18149     // If we are instantiating a generic lambda call operator body,
18150     // we do not want to capture new variables.  What was captured
18151     // during either a lambdas transformation or initial parsing
18152     // should be used.
18153     if (isGenericLambdaCallOperatorSpecialization(DC)) {
18154       if (BuildAndDiagnose) {
18155         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18156         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18157           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18158           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18159           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18160           buildLambdaCaptureFixit(*this, LSI, Var);
18161         } else
18162           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18163       }
18164       return true;
18165     }
18166 
18167     // Try to capture variable-length arrays types.
18168     if (Var->getType()->isVariablyModifiedType()) {
18169       // We're going to walk down into the type and look for VLA
18170       // expressions.
18171       QualType QTy = Var->getType();
18172       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18173         QTy = PVD->getOriginalType();
18174       captureVariablyModifiedType(Context, QTy, CSI);
18175     }
18176 
18177     if (getLangOpts().OpenMP) {
18178       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18179         // OpenMP private variables should not be captured in outer scope, so
18180         // just break here. Similarly, global variables that are captured in a
18181         // target region should not be captured outside the scope of the region.
18182         if (RSI->CapRegionKind == CR_OpenMP) {
18183           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18184               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18185           // If the variable is private (i.e. not captured) and has variably
18186           // modified type, we still need to capture the type for correct
18187           // codegen in all regions, associated with the construct. Currently,
18188           // it is captured in the innermost captured region only.
18189           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18190               Var->getType()->isVariablyModifiedType()) {
18191             QualType QTy = Var->getType();
18192             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18193               QTy = PVD->getOriginalType();
18194             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18195                  I < E; ++I) {
18196               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18197                   FunctionScopes[FunctionScopesIndex - I]);
18198               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18199                      "Wrong number of captured regions associated with the "
18200                      "OpenMP construct.");
18201               captureVariablyModifiedType(Context, QTy, OuterRSI);
18202             }
18203           }
18204           bool IsTargetCap =
18205               IsOpenMPPrivateDecl != OMPC_private &&
18206               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18207                                          RSI->OpenMPCaptureLevel);
18208           // Do not capture global if it is not privatized in outer regions.
18209           bool IsGlobalCap =
18210               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18211                                                      RSI->OpenMPCaptureLevel);
18212 
18213           // When we detect target captures we are looking from inside the
18214           // target region, therefore we need to propagate the capture from the
18215           // enclosing region. Therefore, the capture is not initially nested.
18216           if (IsTargetCap)
18217             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18218 
18219           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18220               (IsGlobal && !IsGlobalCap)) {
18221             Nested = !IsTargetCap;
18222             bool HasConst = DeclRefType.isConstQualified();
18223             DeclRefType = DeclRefType.getUnqualifiedType();
18224             // Don't lose diagnostics about assignments to const.
18225             if (HasConst)
18226               DeclRefType.addConst();
18227             CaptureType = Context.getLValueReferenceType(DeclRefType);
18228             break;
18229           }
18230         }
18231       }
18232     }
18233     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18234       // No capture-default, and this is not an explicit capture
18235       // so cannot capture this variable.
18236       if (BuildAndDiagnose) {
18237         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18238         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18239         auto *LSI = cast<LambdaScopeInfo>(CSI);
18240         if (LSI->Lambda) {
18241           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18242           buildLambdaCaptureFixit(*this, LSI, Var);
18243         }
18244         // FIXME: If we error out because an outer lambda can not implicitly
18245         // capture a variable that an inner lambda explicitly captures, we
18246         // should have the inner lambda do the explicit capture - because
18247         // it makes for cleaner diagnostics later.  This would purely be done
18248         // so that the diagnostic does not misleadingly claim that a variable
18249         // can not be captured by a lambda implicitly even though it is captured
18250         // explicitly.  Suggestion:
18251         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18252         //    at the function head
18253         //  - cache the StartingDeclContext - this must be a lambda
18254         //  - captureInLambda in the innermost lambda the variable.
18255       }
18256       return true;
18257     }
18258 
18259     FunctionScopesIndex--;
18260     DC = ParentDC;
18261     Explicit = false;
18262   } while (!VarDC->Equals(DC));
18263 
18264   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18265   // computing the type of the capture at each step, checking type-specific
18266   // requirements, and adding captures if requested.
18267   // If the variable had already been captured previously, we start capturing
18268   // at the lambda nested within that one.
18269   bool Invalid = false;
18270   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18271        ++I) {
18272     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18273 
18274     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18275     // certain types of variables (unnamed, variably modified types etc.)
18276     // so check for eligibility.
18277     if (!Invalid)
18278       Invalid =
18279           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18280 
18281     // After encountering an error, if we're actually supposed to capture, keep
18282     // capturing in nested contexts to suppress any follow-on diagnostics.
18283     if (Invalid && !BuildAndDiagnose)
18284       return true;
18285 
18286     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18287       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18288                                DeclRefType, Nested, *this, Invalid);
18289       Nested = true;
18290     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18291       Invalid = !captureInCapturedRegion(
18292           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18293           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18294       Nested = true;
18295     } else {
18296       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18297       Invalid =
18298           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18299                            DeclRefType, Nested, Kind, EllipsisLoc,
18300                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18301       Nested = true;
18302     }
18303 
18304     if (Invalid && !BuildAndDiagnose)
18305       return true;
18306   }
18307   return Invalid;
18308 }
18309 
18310 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18311                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18312   QualType CaptureType;
18313   QualType DeclRefType;
18314   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18315                             /*BuildAndDiagnose=*/true, CaptureType,
18316                             DeclRefType, nullptr);
18317 }
18318 
18319 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18320   QualType CaptureType;
18321   QualType DeclRefType;
18322   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18323                              /*BuildAndDiagnose=*/false, CaptureType,
18324                              DeclRefType, nullptr);
18325 }
18326 
18327 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18328   QualType CaptureType;
18329   QualType DeclRefType;
18330 
18331   // Determine whether we can capture this variable.
18332   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18333                          /*BuildAndDiagnose=*/false, CaptureType,
18334                          DeclRefType, nullptr))
18335     return QualType();
18336 
18337   return DeclRefType;
18338 }
18339 
18340 namespace {
18341 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18342 // The produced TemplateArgumentListInfo* points to data stored within this
18343 // object, so should only be used in contexts where the pointer will not be
18344 // used after the CopiedTemplateArgs object is destroyed.
18345 class CopiedTemplateArgs {
18346   bool HasArgs;
18347   TemplateArgumentListInfo TemplateArgStorage;
18348 public:
18349   template<typename RefExpr>
18350   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18351     if (HasArgs)
18352       E->copyTemplateArgumentsInto(TemplateArgStorage);
18353   }
18354   operator TemplateArgumentListInfo*()
18355 #ifdef __has_cpp_attribute
18356 #if __has_cpp_attribute(clang::lifetimebound)
18357   [[clang::lifetimebound]]
18358 #endif
18359 #endif
18360   {
18361     return HasArgs ? &TemplateArgStorage : nullptr;
18362   }
18363 };
18364 }
18365 
18366 /// Walk the set of potential results of an expression and mark them all as
18367 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18368 ///
18369 /// \return A new expression if we found any potential results, ExprEmpty() if
18370 ///         not, and ExprError() if we diagnosed an error.
18371 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18372                                                       NonOdrUseReason NOUR) {
18373   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18374   // an object that satisfies the requirements for appearing in a
18375   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18376   // is immediately applied."  This function handles the lvalue-to-rvalue
18377   // conversion part.
18378   //
18379   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18380   // transform it into the relevant kind of non-odr-use node and rebuild the
18381   // tree of nodes leading to it.
18382   //
18383   // This is a mini-TreeTransform that only transforms a restricted subset of
18384   // nodes (and only certain operands of them).
18385 
18386   // Rebuild a subexpression.
18387   auto Rebuild = [&](Expr *Sub) {
18388     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18389   };
18390 
18391   // Check whether a potential result satisfies the requirements of NOUR.
18392   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18393     // Any entity other than a VarDecl is always odr-used whenever it's named
18394     // in a potentially-evaluated expression.
18395     auto *VD = dyn_cast<VarDecl>(D);
18396     if (!VD)
18397       return true;
18398 
18399     // C++2a [basic.def.odr]p4:
18400     //   A variable x whose name appears as a potentially-evalauted expression
18401     //   e is odr-used by e unless
18402     //   -- x is a reference that is usable in constant expressions, or
18403     //   -- x is a variable of non-reference type that is usable in constant
18404     //      expressions and has no mutable subobjects, and e is an element of
18405     //      the set of potential results of an expression of
18406     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18407     //      conversion is applied, or
18408     //   -- x is a variable of non-reference type, and e is an element of the
18409     //      set of potential results of a discarded-value expression to which
18410     //      the lvalue-to-rvalue conversion is not applied
18411     //
18412     // We check the first bullet and the "potentially-evaluated" condition in
18413     // BuildDeclRefExpr. We check the type requirements in the second bullet
18414     // in CheckLValueToRValueConversionOperand below.
18415     switch (NOUR) {
18416     case NOUR_None:
18417     case NOUR_Unevaluated:
18418       llvm_unreachable("unexpected non-odr-use-reason");
18419 
18420     case NOUR_Constant:
18421       // Constant references were handled when they were built.
18422       if (VD->getType()->isReferenceType())
18423         return true;
18424       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18425         if (RD->hasMutableFields())
18426           return true;
18427       if (!VD->isUsableInConstantExpressions(S.Context))
18428         return true;
18429       break;
18430 
18431     case NOUR_Discarded:
18432       if (VD->getType()->isReferenceType())
18433         return true;
18434       break;
18435     }
18436     return false;
18437   };
18438 
18439   // Mark that this expression does not constitute an odr-use.
18440   auto MarkNotOdrUsed = [&] {
18441     S.MaybeODRUseExprs.remove(E);
18442     if (LambdaScopeInfo *LSI = S.getCurLambda())
18443       LSI->markVariableExprAsNonODRUsed(E);
18444   };
18445 
18446   // C++2a [basic.def.odr]p2:
18447   //   The set of potential results of an expression e is defined as follows:
18448   switch (E->getStmtClass()) {
18449   //   -- If e is an id-expression, ...
18450   case Expr::DeclRefExprClass: {
18451     auto *DRE = cast<DeclRefExpr>(E);
18452     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18453       break;
18454 
18455     // Rebuild as a non-odr-use DeclRefExpr.
18456     MarkNotOdrUsed();
18457     return DeclRefExpr::Create(
18458         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18459         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18460         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18461         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18462   }
18463 
18464   case Expr::FunctionParmPackExprClass: {
18465     auto *FPPE = cast<FunctionParmPackExpr>(E);
18466     // If any of the declarations in the pack is odr-used, then the expression
18467     // as a whole constitutes an odr-use.
18468     for (VarDecl *D : *FPPE)
18469       if (IsPotentialResultOdrUsed(D))
18470         return ExprEmpty();
18471 
18472     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18473     // nothing cares about whether we marked this as an odr-use, but it might
18474     // be useful for non-compiler tools.
18475     MarkNotOdrUsed();
18476     break;
18477   }
18478 
18479   //   -- If e is a subscripting operation with an array operand...
18480   case Expr::ArraySubscriptExprClass: {
18481     auto *ASE = cast<ArraySubscriptExpr>(E);
18482     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18483     if (!OldBase->getType()->isArrayType())
18484       break;
18485     ExprResult Base = Rebuild(OldBase);
18486     if (!Base.isUsable())
18487       return Base;
18488     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18489     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18490     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18491     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18492                                      ASE->getRBracketLoc());
18493   }
18494 
18495   case Expr::MemberExprClass: {
18496     auto *ME = cast<MemberExpr>(E);
18497     // -- If e is a class member access expression [...] naming a non-static
18498     //    data member...
18499     if (isa<FieldDecl>(ME->getMemberDecl())) {
18500       ExprResult Base = Rebuild(ME->getBase());
18501       if (!Base.isUsable())
18502         return Base;
18503       return MemberExpr::Create(
18504           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18505           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18506           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18507           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18508           ME->getObjectKind(), ME->isNonOdrUse());
18509     }
18510 
18511     if (ME->getMemberDecl()->isCXXInstanceMember())
18512       break;
18513 
18514     // -- If e is a class member access expression naming a static data member,
18515     //    ...
18516     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18517       break;
18518 
18519     // Rebuild as a non-odr-use MemberExpr.
18520     MarkNotOdrUsed();
18521     return MemberExpr::Create(
18522         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18523         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18524         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18525         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18526   }
18527 
18528   case Expr::BinaryOperatorClass: {
18529     auto *BO = cast<BinaryOperator>(E);
18530     Expr *LHS = BO->getLHS();
18531     Expr *RHS = BO->getRHS();
18532     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18533     if (BO->getOpcode() == BO_PtrMemD) {
18534       ExprResult Sub = Rebuild(LHS);
18535       if (!Sub.isUsable())
18536         return Sub;
18537       LHS = Sub.get();
18538     //   -- If e is a comma expression, ...
18539     } else if (BO->getOpcode() == BO_Comma) {
18540       ExprResult Sub = Rebuild(RHS);
18541       if (!Sub.isUsable())
18542         return Sub;
18543       RHS = Sub.get();
18544     } else {
18545       break;
18546     }
18547     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18548                         LHS, RHS);
18549   }
18550 
18551   //   -- If e has the form (e1)...
18552   case Expr::ParenExprClass: {
18553     auto *PE = cast<ParenExpr>(E);
18554     ExprResult Sub = Rebuild(PE->getSubExpr());
18555     if (!Sub.isUsable())
18556       return Sub;
18557     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18558   }
18559 
18560   //   -- If e is a glvalue conditional expression, ...
18561   // We don't apply this to a binary conditional operator. FIXME: Should we?
18562   case Expr::ConditionalOperatorClass: {
18563     auto *CO = cast<ConditionalOperator>(E);
18564     ExprResult LHS = Rebuild(CO->getLHS());
18565     if (LHS.isInvalid())
18566       return ExprError();
18567     ExprResult RHS = Rebuild(CO->getRHS());
18568     if (RHS.isInvalid())
18569       return ExprError();
18570     if (!LHS.isUsable() && !RHS.isUsable())
18571       return ExprEmpty();
18572     if (!LHS.isUsable())
18573       LHS = CO->getLHS();
18574     if (!RHS.isUsable())
18575       RHS = CO->getRHS();
18576     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18577                                 CO->getCond(), LHS.get(), RHS.get());
18578   }
18579 
18580   // [Clang extension]
18581   //   -- If e has the form __extension__ e1...
18582   case Expr::UnaryOperatorClass: {
18583     auto *UO = cast<UnaryOperator>(E);
18584     if (UO->getOpcode() != UO_Extension)
18585       break;
18586     ExprResult Sub = Rebuild(UO->getSubExpr());
18587     if (!Sub.isUsable())
18588       return Sub;
18589     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18590                           Sub.get());
18591   }
18592 
18593   // [Clang extension]
18594   //   -- If e has the form _Generic(...), the set of potential results is the
18595   //      union of the sets of potential results of the associated expressions.
18596   case Expr::GenericSelectionExprClass: {
18597     auto *GSE = cast<GenericSelectionExpr>(E);
18598 
18599     SmallVector<Expr *, 4> AssocExprs;
18600     bool AnyChanged = false;
18601     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18602       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18603       if (AssocExpr.isInvalid())
18604         return ExprError();
18605       if (AssocExpr.isUsable()) {
18606         AssocExprs.push_back(AssocExpr.get());
18607         AnyChanged = true;
18608       } else {
18609         AssocExprs.push_back(OrigAssocExpr);
18610       }
18611     }
18612 
18613     return AnyChanged ? S.CreateGenericSelectionExpr(
18614                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18615                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18616                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18617                       : ExprEmpty();
18618   }
18619 
18620   // [Clang extension]
18621   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18622   //      results is the union of the sets of potential results of the
18623   //      second and third subexpressions.
18624   case Expr::ChooseExprClass: {
18625     auto *CE = cast<ChooseExpr>(E);
18626 
18627     ExprResult LHS = Rebuild(CE->getLHS());
18628     if (LHS.isInvalid())
18629       return ExprError();
18630 
18631     ExprResult RHS = Rebuild(CE->getLHS());
18632     if (RHS.isInvalid())
18633       return ExprError();
18634 
18635     if (!LHS.get() && !RHS.get())
18636       return ExprEmpty();
18637     if (!LHS.isUsable())
18638       LHS = CE->getLHS();
18639     if (!RHS.isUsable())
18640       RHS = CE->getRHS();
18641 
18642     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18643                              RHS.get(), CE->getRParenLoc());
18644   }
18645 
18646   // Step through non-syntactic nodes.
18647   case Expr::ConstantExprClass: {
18648     auto *CE = cast<ConstantExpr>(E);
18649     ExprResult Sub = Rebuild(CE->getSubExpr());
18650     if (!Sub.isUsable())
18651       return Sub;
18652     return ConstantExpr::Create(S.Context, Sub.get());
18653   }
18654 
18655   // We could mostly rely on the recursive rebuilding to rebuild implicit
18656   // casts, but not at the top level, so rebuild them here.
18657   case Expr::ImplicitCastExprClass: {
18658     auto *ICE = cast<ImplicitCastExpr>(E);
18659     // Only step through the narrow set of cast kinds we expect to encounter.
18660     // Anything else suggests we've left the region in which potential results
18661     // can be found.
18662     switch (ICE->getCastKind()) {
18663     case CK_NoOp:
18664     case CK_DerivedToBase:
18665     case CK_UncheckedDerivedToBase: {
18666       ExprResult Sub = Rebuild(ICE->getSubExpr());
18667       if (!Sub.isUsable())
18668         return Sub;
18669       CXXCastPath Path(ICE->path());
18670       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18671                                  ICE->getValueKind(), &Path);
18672     }
18673 
18674     default:
18675       break;
18676     }
18677     break;
18678   }
18679 
18680   default:
18681     break;
18682   }
18683 
18684   // Can't traverse through this node. Nothing to do.
18685   return ExprEmpty();
18686 }
18687 
18688 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18689   // Check whether the operand is or contains an object of non-trivial C union
18690   // type.
18691   if (E->getType().isVolatileQualified() &&
18692       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18693        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18694     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18695                           Sema::NTCUC_LValueToRValueVolatile,
18696                           NTCUK_Destruct|NTCUK_Copy);
18697 
18698   // C++2a [basic.def.odr]p4:
18699   //   [...] an expression of non-volatile-qualified non-class type to which
18700   //   the lvalue-to-rvalue conversion is applied [...]
18701   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18702     return E;
18703 
18704   ExprResult Result =
18705       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18706   if (Result.isInvalid())
18707     return ExprError();
18708   return Result.get() ? Result : E;
18709 }
18710 
18711 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18712   Res = CorrectDelayedTyposInExpr(Res);
18713 
18714   if (!Res.isUsable())
18715     return Res;
18716 
18717   // If a constant-expression is a reference to a variable where we delay
18718   // deciding whether it is an odr-use, just assume we will apply the
18719   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18720   // (a non-type template argument), we have special handling anyway.
18721   return CheckLValueToRValueConversionOperand(Res.get());
18722 }
18723 
18724 void Sema::CleanupVarDeclMarking() {
18725   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18726   // call.
18727   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18728   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18729 
18730   for (Expr *E : LocalMaybeODRUseExprs) {
18731     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18732       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18733                          DRE->getLocation(), *this);
18734     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18735       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18736                          *this);
18737     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18738       for (VarDecl *VD : *FP)
18739         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18740     } else {
18741       llvm_unreachable("Unexpected expression");
18742     }
18743   }
18744 
18745   assert(MaybeODRUseExprs.empty() &&
18746          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18747 }
18748 
18749 static void DoMarkVarDeclReferenced(
18750     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
18751     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18752   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18753           isa<FunctionParmPackExpr>(E)) &&
18754          "Invalid Expr argument to DoMarkVarDeclReferenced");
18755   Var->setReferenced();
18756 
18757   if (Var->isInvalidDecl())
18758     return;
18759 
18760   auto *MSI = Var->getMemberSpecializationInfo();
18761   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18762                                        : Var->getTemplateSpecializationKind();
18763 
18764   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18765   bool UsableInConstantExpr =
18766       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18767 
18768   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
18769     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
18770   }
18771 
18772   // C++20 [expr.const]p12:
18773   //   A variable [...] is needed for constant evaluation if it is [...] a
18774   //   variable whose name appears as a potentially constant evaluated
18775   //   expression that is either a contexpr variable or is of non-volatile
18776   //   const-qualified integral type or of reference type
18777   bool NeededForConstantEvaluation =
18778       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18779 
18780   bool NeedDefinition =
18781       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18782 
18783   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18784          "Can't instantiate a partial template specialization.");
18785 
18786   // If this might be a member specialization of a static data member, check
18787   // the specialization is visible. We already did the checks for variable
18788   // template specializations when we created them.
18789   if (NeedDefinition && TSK != TSK_Undeclared &&
18790       !isa<VarTemplateSpecializationDecl>(Var))
18791     SemaRef.checkSpecializationVisibility(Loc, Var);
18792 
18793   // Perform implicit instantiation of static data members, static data member
18794   // templates of class templates, and variable template specializations. Delay
18795   // instantiations of variable templates, except for those that could be used
18796   // in a constant expression.
18797   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18798     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18799     // instantiation declaration if a variable is usable in a constant
18800     // expression (among other cases).
18801     bool TryInstantiating =
18802         TSK == TSK_ImplicitInstantiation ||
18803         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18804 
18805     if (TryInstantiating) {
18806       SourceLocation PointOfInstantiation =
18807           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18808       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18809       if (FirstInstantiation) {
18810         PointOfInstantiation = Loc;
18811         if (MSI)
18812           MSI->setPointOfInstantiation(PointOfInstantiation);
18813           // FIXME: Notify listener.
18814         else
18815           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18816       }
18817 
18818       if (UsableInConstantExpr) {
18819         // Do not defer instantiations of variables that could be used in a
18820         // constant expression.
18821         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18822           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18823         });
18824 
18825         // Re-set the member to trigger a recomputation of the dependence bits
18826         // for the expression.
18827         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18828           DRE->setDecl(DRE->getDecl());
18829         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18830           ME->setMemberDecl(ME->getMemberDecl());
18831       } else if (FirstInstantiation ||
18832                  isa<VarTemplateSpecializationDecl>(Var)) {
18833         // FIXME: For a specialization of a variable template, we don't
18834         // distinguish between "declaration and type implicitly instantiated"
18835         // and "implicit instantiation of definition requested", so we have
18836         // no direct way to avoid enqueueing the pending instantiation
18837         // multiple times.
18838         SemaRef.PendingInstantiations
18839             .push_back(std::make_pair(Var, PointOfInstantiation));
18840       }
18841     }
18842   }
18843 
18844   // C++2a [basic.def.odr]p4:
18845   //   A variable x whose name appears as a potentially-evaluated expression e
18846   //   is odr-used by e unless
18847   //   -- x is a reference that is usable in constant expressions
18848   //   -- x is a variable of non-reference type that is usable in constant
18849   //      expressions and has no mutable subobjects [FIXME], and e is an
18850   //      element of the set of potential results of an expression of
18851   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18852   //      conversion is applied
18853   //   -- x is a variable of non-reference type, and e is an element of the set
18854   //      of potential results of a discarded-value expression to which the
18855   //      lvalue-to-rvalue conversion is not applied [FIXME]
18856   //
18857   // We check the first part of the second bullet here, and
18858   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18859   // FIXME: To get the third bullet right, we need to delay this even for
18860   // variables that are not usable in constant expressions.
18861 
18862   // If we already know this isn't an odr-use, there's nothing more to do.
18863   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18864     if (DRE->isNonOdrUse())
18865       return;
18866   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18867     if (ME->isNonOdrUse())
18868       return;
18869 
18870   switch (OdrUse) {
18871   case OdrUseContext::None:
18872     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18873            "missing non-odr-use marking for unevaluated decl ref");
18874     break;
18875 
18876   case OdrUseContext::FormallyOdrUsed:
18877     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18878     // behavior.
18879     break;
18880 
18881   case OdrUseContext::Used:
18882     // If we might later find that this expression isn't actually an odr-use,
18883     // delay the marking.
18884     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18885       SemaRef.MaybeODRUseExprs.insert(E);
18886     else
18887       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18888     break;
18889 
18890   case OdrUseContext::Dependent:
18891     // If this is a dependent context, we don't need to mark variables as
18892     // odr-used, but we may still need to track them for lambda capture.
18893     // FIXME: Do we also need to do this inside dependent typeid expressions
18894     // (which are modeled as unevaluated at this point)?
18895     const bool RefersToEnclosingScope =
18896         (SemaRef.CurContext != Var->getDeclContext() &&
18897          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18898     if (RefersToEnclosingScope) {
18899       LambdaScopeInfo *const LSI =
18900           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18901       if (LSI && (!LSI->CallOperator ||
18902                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18903         // If a variable could potentially be odr-used, defer marking it so
18904         // until we finish analyzing the full expression for any
18905         // lvalue-to-rvalue
18906         // or discarded value conversions that would obviate odr-use.
18907         // Add it to the list of potential captures that will be analyzed
18908         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18909         // unless the variable is a reference that was initialized by a constant
18910         // expression (this will never need to be captured or odr-used).
18911         //
18912         // FIXME: We can simplify this a lot after implementing P0588R1.
18913         assert(E && "Capture variable should be used in an expression.");
18914         if (!Var->getType()->isReferenceType() ||
18915             !Var->isUsableInConstantExpressions(SemaRef.Context))
18916           LSI->addPotentialCapture(E->IgnoreParens());
18917       }
18918     }
18919     break;
18920   }
18921 }
18922 
18923 /// Mark a variable referenced, and check whether it is odr-used
18924 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18925 /// used directly for normal expressions referring to VarDecl.
18926 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18927   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
18928 }
18929 
18930 static void
18931 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
18932                    bool MightBeOdrUse,
18933                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
18934   if (SemaRef.isInOpenMPDeclareTargetContext())
18935     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18936 
18937   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18938     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
18939     return;
18940   }
18941 
18942   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18943 
18944   // If this is a call to a method via a cast, also mark the method in the
18945   // derived class used in case codegen can devirtualize the call.
18946   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18947   if (!ME)
18948     return;
18949   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18950   if (!MD)
18951     return;
18952   // Only attempt to devirtualize if this is truly a virtual call.
18953   bool IsVirtualCall = MD->isVirtual() &&
18954                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18955   if (!IsVirtualCall)
18956     return;
18957 
18958   // If it's possible to devirtualize the call, mark the called function
18959   // referenced.
18960   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18961       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18962   if (DM)
18963     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18964 }
18965 
18966 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18967 ///
18968 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18969 /// handled with care if the DeclRefExpr is not newly-created.
18970 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18971   // TODO: update this with DR# once a defect report is filed.
18972   // C++11 defect. The address of a pure member should not be an ODR use, even
18973   // if it's a qualified reference.
18974   bool OdrUse = true;
18975   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18976     if (Method->isVirtual() &&
18977         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18978       OdrUse = false;
18979 
18980   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18981     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
18982         FD->isConsteval() && !RebuildingImmediateInvocation)
18983       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18984   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
18985                      RefsMinusAssignments);
18986 }
18987 
18988 /// Perform reference-marking and odr-use handling for a MemberExpr.
18989 void Sema::MarkMemberReferenced(MemberExpr *E) {
18990   // C++11 [basic.def.odr]p2:
18991   //   A non-overloaded function whose name appears as a potentially-evaluated
18992   //   expression or a member of a set of candidate functions, if selected by
18993   //   overload resolution when referred to from a potentially-evaluated
18994   //   expression, is odr-used, unless it is a pure virtual function and its
18995   //   name is not explicitly qualified.
18996   bool MightBeOdrUse = true;
18997   if (E->performsVirtualDispatch(getLangOpts())) {
18998     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18999       if (Method->isPure())
19000         MightBeOdrUse = false;
19001   }
19002   SourceLocation Loc =
19003       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19004   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19005                      RefsMinusAssignments);
19006 }
19007 
19008 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19009 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19010   for (VarDecl *VD : *E)
19011     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19012                        RefsMinusAssignments);
19013 }
19014 
19015 /// Perform marking for a reference to an arbitrary declaration.  It
19016 /// marks the declaration referenced, and performs odr-use checking for
19017 /// functions and variables. This method should not be used when building a
19018 /// normal expression which refers to a variable.
19019 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19020                                  bool MightBeOdrUse) {
19021   if (MightBeOdrUse) {
19022     if (auto *VD = dyn_cast<VarDecl>(D)) {
19023       MarkVariableReferenced(Loc, VD);
19024       return;
19025     }
19026   }
19027   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19028     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19029     return;
19030   }
19031   D->setReferenced();
19032 }
19033 
19034 namespace {
19035   // Mark all of the declarations used by a type as referenced.
19036   // FIXME: Not fully implemented yet! We need to have a better understanding
19037   // of when we're entering a context we should not recurse into.
19038   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19039   // TreeTransforms rebuilding the type in a new context. Rather than
19040   // duplicating the TreeTransform logic, we should consider reusing it here.
19041   // Currently that causes problems when rebuilding LambdaExprs.
19042   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19043     Sema &S;
19044     SourceLocation Loc;
19045 
19046   public:
19047     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19048 
19049     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19050 
19051     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19052   };
19053 }
19054 
19055 bool MarkReferencedDecls::TraverseTemplateArgument(
19056     const TemplateArgument &Arg) {
19057   {
19058     // A non-type template argument is a constant-evaluated context.
19059     EnterExpressionEvaluationContext Evaluated(
19060         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19061     if (Arg.getKind() == TemplateArgument::Declaration) {
19062       if (Decl *D = Arg.getAsDecl())
19063         S.MarkAnyDeclReferenced(Loc, D, true);
19064     } else if (Arg.getKind() == TemplateArgument::Expression) {
19065       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19066     }
19067   }
19068 
19069   return Inherited::TraverseTemplateArgument(Arg);
19070 }
19071 
19072 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19073   MarkReferencedDecls Marker(*this, Loc);
19074   Marker.TraverseType(T);
19075 }
19076 
19077 namespace {
19078 /// Helper class that marks all of the declarations referenced by
19079 /// potentially-evaluated subexpressions as "referenced".
19080 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19081 public:
19082   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19083   bool SkipLocalVariables;
19084   ArrayRef<const Expr *> StopAt;
19085 
19086   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19087                       ArrayRef<const Expr *> StopAt)
19088       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19089 
19090   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19091     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19092   }
19093 
19094   void Visit(Expr *E) {
19095     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19096       return;
19097     Inherited::Visit(E);
19098   }
19099 
19100   void VisitDeclRefExpr(DeclRefExpr *E) {
19101     // If we were asked not to visit local variables, don't.
19102     if (SkipLocalVariables) {
19103       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19104         if (VD->hasLocalStorage())
19105           return;
19106     }
19107 
19108     // FIXME: This can trigger the instantiation of the initializer of a
19109     // variable, which can cause the expression to become value-dependent
19110     // or error-dependent. Do we need to propagate the new dependence bits?
19111     S.MarkDeclRefReferenced(E);
19112   }
19113 
19114   void VisitMemberExpr(MemberExpr *E) {
19115     S.MarkMemberReferenced(E);
19116     Visit(E->getBase());
19117   }
19118 };
19119 } // namespace
19120 
19121 /// Mark any declarations that appear within this expression or any
19122 /// potentially-evaluated subexpressions as "referenced".
19123 ///
19124 /// \param SkipLocalVariables If true, don't mark local variables as
19125 /// 'referenced'.
19126 /// \param StopAt Subexpressions that we shouldn't recurse into.
19127 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19128                                             bool SkipLocalVariables,
19129                                             ArrayRef<const Expr*> StopAt) {
19130   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19131 }
19132 
19133 /// Emit a diagnostic when statements are reachable.
19134 /// FIXME: check for reachability even in expressions for which we don't build a
19135 ///        CFG (eg, in the initializer of a global or in a constant expression).
19136 ///        For example,
19137 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19138 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19139                            const PartialDiagnostic &PD) {
19140   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19141     if (!FunctionScopes.empty())
19142       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19143           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19144     return true;
19145   }
19146 
19147   // The initializer of a constexpr variable or of the first declaration of a
19148   // static data member is not syntactically a constant evaluated constant,
19149   // but nonetheless is always required to be a constant expression, so we
19150   // can skip diagnosing.
19151   // FIXME: Using the mangling context here is a hack.
19152   if (auto *VD = dyn_cast_or_null<VarDecl>(
19153           ExprEvalContexts.back().ManglingContextDecl)) {
19154     if (VD->isConstexpr() ||
19155         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19156       return false;
19157     // FIXME: For any other kind of variable, we should build a CFG for its
19158     // initializer and check whether the context in question is reachable.
19159   }
19160 
19161   Diag(Loc, PD);
19162   return true;
19163 }
19164 
19165 /// Emit a diagnostic that describes an effect on the run-time behavior
19166 /// of the program being compiled.
19167 ///
19168 /// This routine emits the given diagnostic when the code currently being
19169 /// type-checked is "potentially evaluated", meaning that there is a
19170 /// possibility that the code will actually be executable. Code in sizeof()
19171 /// expressions, code used only during overload resolution, etc., are not
19172 /// potentially evaluated. This routine will suppress such diagnostics or,
19173 /// in the absolutely nutty case of potentially potentially evaluated
19174 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19175 /// later.
19176 ///
19177 /// This routine should be used for all diagnostics that describe the run-time
19178 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19179 /// Failure to do so will likely result in spurious diagnostics or failures
19180 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19181 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19182                                const PartialDiagnostic &PD) {
19183 
19184   if (ExprEvalContexts.back().isDiscardedStatementContext())
19185     return false;
19186 
19187   switch (ExprEvalContexts.back().Context) {
19188   case ExpressionEvaluationContext::Unevaluated:
19189   case ExpressionEvaluationContext::UnevaluatedList:
19190   case ExpressionEvaluationContext::UnevaluatedAbstract:
19191   case ExpressionEvaluationContext::DiscardedStatement:
19192     // The argument will never be evaluated, so don't complain.
19193     break;
19194 
19195   case ExpressionEvaluationContext::ConstantEvaluated:
19196   case ExpressionEvaluationContext::ImmediateFunctionContext:
19197     // Relevant diagnostics should be produced by constant evaluation.
19198     break;
19199 
19200   case ExpressionEvaluationContext::PotentiallyEvaluated:
19201   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19202     return DiagIfReachable(Loc, Stmts, PD);
19203   }
19204 
19205   return false;
19206 }
19207 
19208 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19209                                const PartialDiagnostic &PD) {
19210   return DiagRuntimeBehavior(
19211       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19212 }
19213 
19214 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19215                                CallExpr *CE, FunctionDecl *FD) {
19216   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19217     return false;
19218 
19219   // If we're inside a decltype's expression, don't check for a valid return
19220   // type or construct temporaries until we know whether this is the last call.
19221   if (ExprEvalContexts.back().ExprContext ==
19222       ExpressionEvaluationContextRecord::EK_Decltype) {
19223     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19224     return false;
19225   }
19226 
19227   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19228     FunctionDecl *FD;
19229     CallExpr *CE;
19230 
19231   public:
19232     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19233       : FD(FD), CE(CE) { }
19234 
19235     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19236       if (!FD) {
19237         S.Diag(Loc, diag::err_call_incomplete_return)
19238           << T << CE->getSourceRange();
19239         return;
19240       }
19241 
19242       S.Diag(Loc, diag::err_call_function_incomplete_return)
19243           << CE->getSourceRange() << FD << T;
19244       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19245           << FD->getDeclName();
19246     }
19247   } Diagnoser(FD, CE);
19248 
19249   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19250     return true;
19251 
19252   return false;
19253 }
19254 
19255 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19256 // will prevent this condition from triggering, which is what we want.
19257 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19258   SourceLocation Loc;
19259 
19260   unsigned diagnostic = diag::warn_condition_is_assignment;
19261   bool IsOrAssign = false;
19262 
19263   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19264     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19265       return;
19266 
19267     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19268 
19269     // Greylist some idioms by putting them into a warning subcategory.
19270     if (ObjCMessageExpr *ME
19271           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19272       Selector Sel = ME->getSelector();
19273 
19274       // self = [<foo> init...]
19275       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19276         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19277 
19278       // <foo> = [<bar> nextObject]
19279       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19280         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19281     }
19282 
19283     Loc = Op->getOperatorLoc();
19284   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19285     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19286       return;
19287 
19288     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19289     Loc = Op->getOperatorLoc();
19290   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19291     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19292   else {
19293     // Not an assignment.
19294     return;
19295   }
19296 
19297   Diag(Loc, diagnostic) << E->getSourceRange();
19298 
19299   SourceLocation Open = E->getBeginLoc();
19300   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19301   Diag(Loc, diag::note_condition_assign_silence)
19302         << FixItHint::CreateInsertion(Open, "(")
19303         << FixItHint::CreateInsertion(Close, ")");
19304 
19305   if (IsOrAssign)
19306     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19307       << FixItHint::CreateReplacement(Loc, "!=");
19308   else
19309     Diag(Loc, diag::note_condition_assign_to_comparison)
19310       << FixItHint::CreateReplacement(Loc, "==");
19311 }
19312 
19313 /// Redundant parentheses over an equality comparison can indicate
19314 /// that the user intended an assignment used as condition.
19315 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19316   // Don't warn if the parens came from a macro.
19317   SourceLocation parenLoc = ParenE->getBeginLoc();
19318   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19319     return;
19320   // Don't warn for dependent expressions.
19321   if (ParenE->isTypeDependent())
19322     return;
19323 
19324   Expr *E = ParenE->IgnoreParens();
19325 
19326   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19327     if (opE->getOpcode() == BO_EQ &&
19328         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19329                                                            == Expr::MLV_Valid) {
19330       SourceLocation Loc = opE->getOperatorLoc();
19331 
19332       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19333       SourceRange ParenERange = ParenE->getSourceRange();
19334       Diag(Loc, diag::note_equality_comparison_silence)
19335         << FixItHint::CreateRemoval(ParenERange.getBegin())
19336         << FixItHint::CreateRemoval(ParenERange.getEnd());
19337       Diag(Loc, diag::note_equality_comparison_to_assign)
19338         << FixItHint::CreateReplacement(Loc, "=");
19339     }
19340 }
19341 
19342 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19343                                        bool IsConstexpr) {
19344   DiagnoseAssignmentAsCondition(E);
19345   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19346     DiagnoseEqualityWithExtraParens(parenE);
19347 
19348   ExprResult result = CheckPlaceholderExpr(E);
19349   if (result.isInvalid()) return ExprError();
19350   E = result.get();
19351 
19352   if (!E->isTypeDependent()) {
19353     if (getLangOpts().CPlusPlus)
19354       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19355 
19356     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19357     if (ERes.isInvalid())
19358       return ExprError();
19359     E = ERes.get();
19360 
19361     QualType T = E->getType();
19362     if (!T->isScalarType()) { // C99 6.8.4.1p1
19363       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19364         << T << E->getSourceRange();
19365       return ExprError();
19366     }
19367     CheckBoolLikeConversion(E, Loc);
19368   }
19369 
19370   return E;
19371 }
19372 
19373 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19374                                            Expr *SubExpr, ConditionKind CK,
19375                                            bool MissingOK) {
19376   // MissingOK indicates whether having no condition expression is valid
19377   // (for loop) or invalid (e.g. while loop).
19378   if (!SubExpr)
19379     return MissingOK ? ConditionResult() : ConditionError();
19380 
19381   ExprResult Cond;
19382   switch (CK) {
19383   case ConditionKind::Boolean:
19384     Cond = CheckBooleanCondition(Loc, SubExpr);
19385     break;
19386 
19387   case ConditionKind::ConstexprIf:
19388     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19389     break;
19390 
19391   case ConditionKind::Switch:
19392     Cond = CheckSwitchCondition(Loc, SubExpr);
19393     break;
19394   }
19395   if (Cond.isInvalid()) {
19396     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19397                               {SubExpr}, PreferredConditionType(CK));
19398     if (!Cond.get())
19399       return ConditionError();
19400   }
19401   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19402   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19403   if (!FullExpr.get())
19404     return ConditionError();
19405 
19406   return ConditionResult(*this, nullptr, FullExpr,
19407                          CK == ConditionKind::ConstexprIf);
19408 }
19409 
19410 namespace {
19411   /// A visitor for rebuilding a call to an __unknown_any expression
19412   /// to have an appropriate type.
19413   struct RebuildUnknownAnyFunction
19414     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19415 
19416     Sema &S;
19417 
19418     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19419 
19420     ExprResult VisitStmt(Stmt *S) {
19421       llvm_unreachable("unexpected statement!");
19422     }
19423 
19424     ExprResult VisitExpr(Expr *E) {
19425       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19426         << E->getSourceRange();
19427       return ExprError();
19428     }
19429 
19430     /// Rebuild an expression which simply semantically wraps another
19431     /// expression which it shares the type and value kind of.
19432     template <class T> ExprResult rebuildSugarExpr(T *E) {
19433       ExprResult SubResult = Visit(E->getSubExpr());
19434       if (SubResult.isInvalid()) return ExprError();
19435 
19436       Expr *SubExpr = SubResult.get();
19437       E->setSubExpr(SubExpr);
19438       E->setType(SubExpr->getType());
19439       E->setValueKind(SubExpr->getValueKind());
19440       assert(E->getObjectKind() == OK_Ordinary);
19441       return E;
19442     }
19443 
19444     ExprResult VisitParenExpr(ParenExpr *E) {
19445       return rebuildSugarExpr(E);
19446     }
19447 
19448     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19449       return rebuildSugarExpr(E);
19450     }
19451 
19452     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19453       ExprResult SubResult = Visit(E->getSubExpr());
19454       if (SubResult.isInvalid()) return ExprError();
19455 
19456       Expr *SubExpr = SubResult.get();
19457       E->setSubExpr(SubExpr);
19458       E->setType(S.Context.getPointerType(SubExpr->getType()));
19459       assert(E->isPRValue());
19460       assert(E->getObjectKind() == OK_Ordinary);
19461       return E;
19462     }
19463 
19464     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19465       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19466 
19467       E->setType(VD->getType());
19468 
19469       assert(E->isPRValue());
19470       if (S.getLangOpts().CPlusPlus &&
19471           !(isa<CXXMethodDecl>(VD) &&
19472             cast<CXXMethodDecl>(VD)->isInstance()))
19473         E->setValueKind(VK_LValue);
19474 
19475       return E;
19476     }
19477 
19478     ExprResult VisitMemberExpr(MemberExpr *E) {
19479       return resolveDecl(E, E->getMemberDecl());
19480     }
19481 
19482     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19483       return resolveDecl(E, E->getDecl());
19484     }
19485   };
19486 }
19487 
19488 /// Given a function expression of unknown-any type, try to rebuild it
19489 /// to have a function type.
19490 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19491   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19492   if (Result.isInvalid()) return ExprError();
19493   return S.DefaultFunctionArrayConversion(Result.get());
19494 }
19495 
19496 namespace {
19497   /// A visitor for rebuilding an expression of type __unknown_anytype
19498   /// into one which resolves the type directly on the referring
19499   /// expression.  Strict preservation of the original source
19500   /// structure is not a goal.
19501   struct RebuildUnknownAnyExpr
19502     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19503 
19504     Sema &S;
19505 
19506     /// The current destination type.
19507     QualType DestType;
19508 
19509     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19510       : S(S), DestType(CastType) {}
19511 
19512     ExprResult VisitStmt(Stmt *S) {
19513       llvm_unreachable("unexpected statement!");
19514     }
19515 
19516     ExprResult VisitExpr(Expr *E) {
19517       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19518         << E->getSourceRange();
19519       return ExprError();
19520     }
19521 
19522     ExprResult VisitCallExpr(CallExpr *E);
19523     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19524 
19525     /// Rebuild an expression which simply semantically wraps another
19526     /// expression which it shares the type and value kind of.
19527     template <class T> ExprResult rebuildSugarExpr(T *E) {
19528       ExprResult SubResult = Visit(E->getSubExpr());
19529       if (SubResult.isInvalid()) return ExprError();
19530       Expr *SubExpr = SubResult.get();
19531       E->setSubExpr(SubExpr);
19532       E->setType(SubExpr->getType());
19533       E->setValueKind(SubExpr->getValueKind());
19534       assert(E->getObjectKind() == OK_Ordinary);
19535       return E;
19536     }
19537 
19538     ExprResult VisitParenExpr(ParenExpr *E) {
19539       return rebuildSugarExpr(E);
19540     }
19541 
19542     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19543       return rebuildSugarExpr(E);
19544     }
19545 
19546     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19547       const PointerType *Ptr = DestType->getAs<PointerType>();
19548       if (!Ptr) {
19549         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19550           << E->getSourceRange();
19551         return ExprError();
19552       }
19553 
19554       if (isa<CallExpr>(E->getSubExpr())) {
19555         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19556           << E->getSourceRange();
19557         return ExprError();
19558       }
19559 
19560       assert(E->isPRValue());
19561       assert(E->getObjectKind() == OK_Ordinary);
19562       E->setType(DestType);
19563 
19564       // Build the sub-expression as if it were an object of the pointee type.
19565       DestType = Ptr->getPointeeType();
19566       ExprResult SubResult = Visit(E->getSubExpr());
19567       if (SubResult.isInvalid()) return ExprError();
19568       E->setSubExpr(SubResult.get());
19569       return E;
19570     }
19571 
19572     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19573 
19574     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19575 
19576     ExprResult VisitMemberExpr(MemberExpr *E) {
19577       return resolveDecl(E, E->getMemberDecl());
19578     }
19579 
19580     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19581       return resolveDecl(E, E->getDecl());
19582     }
19583   };
19584 }
19585 
19586 /// Rebuilds a call expression which yielded __unknown_anytype.
19587 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19588   Expr *CalleeExpr = E->getCallee();
19589 
19590   enum FnKind {
19591     FK_MemberFunction,
19592     FK_FunctionPointer,
19593     FK_BlockPointer
19594   };
19595 
19596   FnKind Kind;
19597   QualType CalleeType = CalleeExpr->getType();
19598   if (CalleeType == S.Context.BoundMemberTy) {
19599     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19600     Kind = FK_MemberFunction;
19601     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19602   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19603     CalleeType = Ptr->getPointeeType();
19604     Kind = FK_FunctionPointer;
19605   } else {
19606     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19607     Kind = FK_BlockPointer;
19608   }
19609   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19610 
19611   // Verify that this is a legal result type of a function.
19612   if (DestType->isArrayType() || DestType->isFunctionType()) {
19613     unsigned diagID = diag::err_func_returning_array_function;
19614     if (Kind == FK_BlockPointer)
19615       diagID = diag::err_block_returning_array_function;
19616 
19617     S.Diag(E->getExprLoc(), diagID)
19618       << DestType->isFunctionType() << DestType;
19619     return ExprError();
19620   }
19621 
19622   // Otherwise, go ahead and set DestType as the call's result.
19623   E->setType(DestType.getNonLValueExprType(S.Context));
19624   E->setValueKind(Expr::getValueKindForType(DestType));
19625   assert(E->getObjectKind() == OK_Ordinary);
19626 
19627   // Rebuild the function type, replacing the result type with DestType.
19628   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19629   if (Proto) {
19630     // __unknown_anytype(...) is a special case used by the debugger when
19631     // it has no idea what a function's signature is.
19632     //
19633     // We want to build this call essentially under the K&R
19634     // unprototyped rules, but making a FunctionNoProtoType in C++
19635     // would foul up all sorts of assumptions.  However, we cannot
19636     // simply pass all arguments as variadic arguments, nor can we
19637     // portably just call the function under a non-variadic type; see
19638     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19639     // However, it turns out that in practice it is generally safe to
19640     // call a function declared as "A foo(B,C,D);" under the prototype
19641     // "A foo(B,C,D,...);".  The only known exception is with the
19642     // Windows ABI, where any variadic function is implicitly cdecl
19643     // regardless of its normal CC.  Therefore we change the parameter
19644     // types to match the types of the arguments.
19645     //
19646     // This is a hack, but it is far superior to moving the
19647     // corresponding target-specific code from IR-gen to Sema/AST.
19648 
19649     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19650     SmallVector<QualType, 8> ArgTypes;
19651     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19652       ArgTypes.reserve(E->getNumArgs());
19653       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19654         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
19655       }
19656       ParamTypes = ArgTypes;
19657     }
19658     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19659                                          Proto->getExtProtoInfo());
19660   } else {
19661     DestType = S.Context.getFunctionNoProtoType(DestType,
19662                                                 FnType->getExtInfo());
19663   }
19664 
19665   // Rebuild the appropriate pointer-to-function type.
19666   switch (Kind) {
19667   case FK_MemberFunction:
19668     // Nothing to do.
19669     break;
19670 
19671   case FK_FunctionPointer:
19672     DestType = S.Context.getPointerType(DestType);
19673     break;
19674 
19675   case FK_BlockPointer:
19676     DestType = S.Context.getBlockPointerType(DestType);
19677     break;
19678   }
19679 
19680   // Finally, we can recurse.
19681   ExprResult CalleeResult = Visit(CalleeExpr);
19682   if (!CalleeResult.isUsable()) return ExprError();
19683   E->setCallee(CalleeResult.get());
19684 
19685   // Bind a temporary if necessary.
19686   return S.MaybeBindToTemporary(E);
19687 }
19688 
19689 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19690   // Verify that this is a legal result type of a call.
19691   if (DestType->isArrayType() || DestType->isFunctionType()) {
19692     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19693       << DestType->isFunctionType() << DestType;
19694     return ExprError();
19695   }
19696 
19697   // Rewrite the method result type if available.
19698   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19699     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19700     Method->setReturnType(DestType);
19701   }
19702 
19703   // Change the type of the message.
19704   E->setType(DestType.getNonReferenceType());
19705   E->setValueKind(Expr::getValueKindForType(DestType));
19706 
19707   return S.MaybeBindToTemporary(E);
19708 }
19709 
19710 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19711   // The only case we should ever see here is a function-to-pointer decay.
19712   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19713     assert(E->isPRValue());
19714     assert(E->getObjectKind() == OK_Ordinary);
19715 
19716     E->setType(DestType);
19717 
19718     // Rebuild the sub-expression as the pointee (function) type.
19719     DestType = DestType->castAs<PointerType>()->getPointeeType();
19720 
19721     ExprResult Result = Visit(E->getSubExpr());
19722     if (!Result.isUsable()) return ExprError();
19723 
19724     E->setSubExpr(Result.get());
19725     return E;
19726   } else if (E->getCastKind() == CK_LValueToRValue) {
19727     assert(E->isPRValue());
19728     assert(E->getObjectKind() == OK_Ordinary);
19729 
19730     assert(isa<BlockPointerType>(E->getType()));
19731 
19732     E->setType(DestType);
19733 
19734     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19735     DestType = S.Context.getLValueReferenceType(DestType);
19736 
19737     ExprResult Result = Visit(E->getSubExpr());
19738     if (!Result.isUsable()) return ExprError();
19739 
19740     E->setSubExpr(Result.get());
19741     return E;
19742   } else {
19743     llvm_unreachable("Unhandled cast type!");
19744   }
19745 }
19746 
19747 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19748   ExprValueKind ValueKind = VK_LValue;
19749   QualType Type = DestType;
19750 
19751   // We know how to make this work for certain kinds of decls:
19752 
19753   //  - functions
19754   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19755     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19756       DestType = Ptr->getPointeeType();
19757       ExprResult Result = resolveDecl(E, VD);
19758       if (Result.isInvalid()) return ExprError();
19759       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
19760                                  VK_PRValue);
19761     }
19762 
19763     if (!Type->isFunctionType()) {
19764       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19765         << VD << E->getSourceRange();
19766       return ExprError();
19767     }
19768     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19769       // We must match the FunctionDecl's type to the hack introduced in
19770       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19771       // type. See the lengthy commentary in that routine.
19772       QualType FDT = FD->getType();
19773       const FunctionType *FnType = FDT->castAs<FunctionType>();
19774       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19775       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19776       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19777         SourceLocation Loc = FD->getLocation();
19778         FunctionDecl *NewFD = FunctionDecl::Create(
19779             S.Context, FD->getDeclContext(), Loc, Loc,
19780             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19781             SC_None, S.getCurFPFeatures().isFPConstrained(),
19782             false /*isInlineSpecified*/, FD->hasPrototype(),
19783             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19784 
19785         if (FD->getQualifier())
19786           NewFD->setQualifierInfo(FD->getQualifierLoc());
19787 
19788         SmallVector<ParmVarDecl*, 16> Params;
19789         for (const auto &AI : FT->param_types()) {
19790           ParmVarDecl *Param =
19791             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19792           Param->setScopeInfo(0, Params.size());
19793           Params.push_back(Param);
19794         }
19795         NewFD->setParams(Params);
19796         DRE->setDecl(NewFD);
19797         VD = DRE->getDecl();
19798       }
19799     }
19800 
19801     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19802       if (MD->isInstance()) {
19803         ValueKind = VK_PRValue;
19804         Type = S.Context.BoundMemberTy;
19805       }
19806 
19807     // Function references aren't l-values in C.
19808     if (!S.getLangOpts().CPlusPlus)
19809       ValueKind = VK_PRValue;
19810 
19811   //  - variables
19812   } else if (isa<VarDecl>(VD)) {
19813     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19814       Type = RefTy->getPointeeType();
19815     } else if (Type->isFunctionType()) {
19816       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19817         << VD << E->getSourceRange();
19818       return ExprError();
19819     }
19820 
19821   //  - nothing else
19822   } else {
19823     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19824       << VD << E->getSourceRange();
19825     return ExprError();
19826   }
19827 
19828   // Modifying the declaration like this is friendly to IR-gen but
19829   // also really dangerous.
19830   VD->setType(DestType);
19831   E->setType(Type);
19832   E->setValueKind(ValueKind);
19833   return E;
19834 }
19835 
19836 /// Check a cast of an unknown-any type.  We intentionally only
19837 /// trigger this for C-style casts.
19838 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19839                                      Expr *CastExpr, CastKind &CastKind,
19840                                      ExprValueKind &VK, CXXCastPath &Path) {
19841   // The type we're casting to must be either void or complete.
19842   if (!CastType->isVoidType() &&
19843       RequireCompleteType(TypeRange.getBegin(), CastType,
19844                           diag::err_typecheck_cast_to_incomplete))
19845     return ExprError();
19846 
19847   // Rewrite the casted expression from scratch.
19848   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19849   if (!result.isUsable()) return ExprError();
19850 
19851   CastExpr = result.get();
19852   VK = CastExpr->getValueKind();
19853   CastKind = CK_NoOp;
19854 
19855   return CastExpr;
19856 }
19857 
19858 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19859   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19860 }
19861 
19862 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19863                                     Expr *arg, QualType &paramType) {
19864   // If the syntactic form of the argument is not an explicit cast of
19865   // any sort, just do default argument promotion.
19866   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19867   if (!castArg) {
19868     ExprResult result = DefaultArgumentPromotion(arg);
19869     if (result.isInvalid()) return ExprError();
19870     paramType = result.get()->getType();
19871     return result;
19872   }
19873 
19874   // Otherwise, use the type that was written in the explicit cast.
19875   assert(!arg->hasPlaceholderType());
19876   paramType = castArg->getTypeAsWritten();
19877 
19878   // Copy-initialize a parameter of that type.
19879   InitializedEntity entity =
19880     InitializedEntity::InitializeParameter(Context, paramType,
19881                                            /*consumed*/ false);
19882   return PerformCopyInitialization(entity, callLoc, arg);
19883 }
19884 
19885 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19886   Expr *orig = E;
19887   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19888   while (true) {
19889     E = E->IgnoreParenImpCasts();
19890     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19891       E = call->getCallee();
19892       diagID = diag::err_uncasted_call_of_unknown_any;
19893     } else {
19894       break;
19895     }
19896   }
19897 
19898   SourceLocation loc;
19899   NamedDecl *d;
19900   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19901     loc = ref->getLocation();
19902     d = ref->getDecl();
19903   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19904     loc = mem->getMemberLoc();
19905     d = mem->getMemberDecl();
19906   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19907     diagID = diag::err_uncasted_call_of_unknown_any;
19908     loc = msg->getSelectorStartLoc();
19909     d = msg->getMethodDecl();
19910     if (!d) {
19911       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19912         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19913         << orig->getSourceRange();
19914       return ExprError();
19915     }
19916   } else {
19917     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19918       << E->getSourceRange();
19919     return ExprError();
19920   }
19921 
19922   S.Diag(loc, diagID) << d << orig->getSourceRange();
19923 
19924   // Never recoverable.
19925   return ExprError();
19926 }
19927 
19928 /// Check for operands with placeholder types and complain if found.
19929 /// Returns ExprError() if there was an error and no recovery was possible.
19930 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19931   if (!Context.isDependenceAllowed()) {
19932     // C cannot handle TypoExpr nodes on either side of a binop because it
19933     // doesn't handle dependent types properly, so make sure any TypoExprs have
19934     // been dealt with before checking the operands.
19935     ExprResult Result = CorrectDelayedTyposInExpr(E);
19936     if (!Result.isUsable()) return ExprError();
19937     E = Result.get();
19938   }
19939 
19940   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19941   if (!placeholderType) return E;
19942 
19943   switch (placeholderType->getKind()) {
19944 
19945   // Overloaded expressions.
19946   case BuiltinType::Overload: {
19947     // Try to resolve a single function template specialization.
19948     // This is obligatory.
19949     ExprResult Result = E;
19950     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19951       return Result;
19952 
19953     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19954     // leaves Result unchanged on failure.
19955     Result = E;
19956     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19957       return Result;
19958 
19959     // If that failed, try to recover with a call.
19960     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19961                          /*complain*/ true);
19962     return Result;
19963   }
19964 
19965   // Bound member functions.
19966   case BuiltinType::BoundMember: {
19967     ExprResult result = E;
19968     const Expr *BME = E->IgnoreParens();
19969     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19970     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19971     if (isa<CXXPseudoDestructorExpr>(BME)) {
19972       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19973     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19974       if (ME->getMemberNameInfo().getName().getNameKind() ==
19975           DeclarationName::CXXDestructorName)
19976         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19977     }
19978     tryToRecoverWithCall(result, PD,
19979                          /*complain*/ true);
19980     return result;
19981   }
19982 
19983   // ARC unbridged casts.
19984   case BuiltinType::ARCUnbridgedCast: {
19985     Expr *realCast = stripARCUnbridgedCast(E);
19986     diagnoseARCUnbridgedCast(realCast);
19987     return realCast;
19988   }
19989 
19990   // Expressions of unknown type.
19991   case BuiltinType::UnknownAny:
19992     return diagnoseUnknownAnyExpr(*this, E);
19993 
19994   // Pseudo-objects.
19995   case BuiltinType::PseudoObject:
19996     return checkPseudoObjectRValue(E);
19997 
19998   case BuiltinType::BuiltinFn: {
19999     // Accept __noop without parens by implicitly converting it to a call expr.
20000     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20001     if (DRE) {
20002       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20003       if (FD->getBuiltinID() == Builtin::BI__noop) {
20004         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20005                               CK_BuiltinFnToFnPtr)
20006                 .get();
20007         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20008                                 VK_PRValue, SourceLocation(),
20009                                 FPOptionsOverride());
20010       }
20011     }
20012 
20013     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20014     return ExprError();
20015   }
20016 
20017   case BuiltinType::IncompleteMatrixIdx:
20018     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20019              ->getRowIdx()
20020              ->getBeginLoc(),
20021          diag::err_matrix_incomplete_index);
20022     return ExprError();
20023 
20024   // Expressions of unknown type.
20025   case BuiltinType::OMPArraySection:
20026     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20027     return ExprError();
20028 
20029   // Expressions of unknown type.
20030   case BuiltinType::OMPArrayShaping:
20031     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20032 
20033   case BuiltinType::OMPIterator:
20034     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20035 
20036   // Everything else should be impossible.
20037 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20038   case BuiltinType::Id:
20039 #include "clang/Basic/OpenCLImageTypes.def"
20040 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20041   case BuiltinType::Id:
20042 #include "clang/Basic/OpenCLExtensionTypes.def"
20043 #define SVE_TYPE(Name, Id, SingletonId) \
20044   case BuiltinType::Id:
20045 #include "clang/Basic/AArch64SVEACLETypes.def"
20046 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20047   case BuiltinType::Id:
20048 #include "clang/Basic/PPCTypes.def"
20049 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20050 #include "clang/Basic/RISCVVTypes.def"
20051 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20052 #define PLACEHOLDER_TYPE(Id, SingletonId)
20053 #include "clang/AST/BuiltinTypes.def"
20054     break;
20055   }
20056 
20057   llvm_unreachable("invalid placeholder type!");
20058 }
20059 
20060 bool Sema::CheckCaseExpression(Expr *E) {
20061   if (E->isTypeDependent())
20062     return true;
20063   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20064     return E->getType()->isIntegralOrEnumerationType();
20065   return false;
20066 }
20067 
20068 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20069 ExprResult
20070 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20071   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20072          "Unknown Objective-C Boolean value!");
20073   QualType BoolT = Context.ObjCBuiltinBoolTy;
20074   if (!Context.getBOOLDecl()) {
20075     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20076                         Sema::LookupOrdinaryName);
20077     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20078       NamedDecl *ND = Result.getFoundDecl();
20079       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20080         Context.setBOOLDecl(TD);
20081     }
20082   }
20083   if (Context.getBOOLDecl())
20084     BoolT = Context.getBOOLType();
20085   return new (Context)
20086       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20087 }
20088 
20089 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20090     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20091     SourceLocation RParen) {
20092   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20093     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20094       return Spec.getPlatform() == Platform;
20095     });
20096     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20097     // for "maccatalyst" if "maccatalyst" is not specified.
20098     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20099       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20100         return Spec.getPlatform() == "ios";
20101       });
20102     }
20103     if (Spec == AvailSpecs.end())
20104       return None;
20105     return Spec->getVersion();
20106   };
20107 
20108   VersionTuple Version;
20109   if (auto MaybeVersion =
20110           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20111     Version = *MaybeVersion;
20112 
20113   // The use of `@available` in the enclosing context should be analyzed to
20114   // warn when it's used inappropriately (i.e. not if(@available)).
20115   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20116     Context->HasPotentialAvailabilityViolations = true;
20117 
20118   return new (Context)
20119       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20120 }
20121 
20122 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20123                                     ArrayRef<Expr *> SubExprs, QualType T) {
20124   if (!Context.getLangOpts().RecoveryAST)
20125     return ExprError();
20126 
20127   if (isSFINAEContext())
20128     return ExprError();
20129 
20130   if (T.isNull() || T->isUndeducedType() ||
20131       !Context.getLangOpts().RecoveryASTType)
20132     // We don't know the concrete type, fallback to dependent type.
20133     T = Context.DependentTy;
20134 
20135   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20136 }
20137