1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 using namespace clang;
53 using namespace sema;
54 using llvm::RoundingMode;
55 
56 /// Determine whether the use of this declaration is valid, without
57 /// emitting diagnostics.
58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
59   // See if this is an auto-typed variable whose initializer we are parsing.
60   if (ParsingInitForAutoVars.count(D))
61     return false;
62 
63   // See if this is a deleted function.
64   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
65     if (FD->isDeleted())
66       return false;
67 
68     // If the function has a deduced return type, and we can't deduce it,
69     // then we can't use it either.
70     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
71         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
72       return false;
73 
74     // See if this is an aligned allocation/deallocation function that is
75     // unavailable.
76     if (TreatUnavailableAsInvalid &&
77         isUnavailableAlignedAllocationFunction(*FD))
78       return false;
79   }
80 
81   // See if this function is unavailable.
82   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
83       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
84     return false;
85 
86   return true;
87 }
88 
89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
90   // Warn if this is used but marked unused.
91   if (const auto *A = D->getAttr<UnusedAttr>()) {
92     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
93     // should diagnose them.
94     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
95         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
96       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
97       if (DC && !DC->hasAttr<UnusedAttr>())
98         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
99     }
100   }
101 }
102 
103 /// Emit a note explaining that this function is deleted.
104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
105   assert(Decl && Decl->isDeleted());
106 
107   if (Decl->isDefaulted()) {
108     // If the method was explicitly defaulted, point at that declaration.
109     if (!Decl->isImplicit())
110       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
111 
112     // Try to diagnose why this special member function was implicitly
113     // deleted. This might fail, if that reason no longer applies.
114     DiagnoseDeletedDefaultedFunction(Decl);
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
253     // See if this is a deleted function.
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // [expr.prim.id]p4
267     //   A program that refers explicitly or implicitly to a function with a
268     //   trailing requires-clause whose constraint-expression is not satisfied,
269     //   other than to declare it, is ill-formed. [...]
270     //
271     // See if this is a function with constraints that need to be satisfied.
272     // Check this before deducing the return type, as it might instantiate the
273     // definition.
274     if (FD->getTrailingRequiresClause()) {
275       ConstraintSatisfaction Satisfaction;
276       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
277         // A diagnostic will have already been generated (non-constant
278         // constraint expression, for example)
279         return true;
280       if (!Satisfaction.IsSatisfied) {
281         Diag(Loc,
282              diag::err_reference_to_function_with_unsatisfied_constraints)
283             << D;
284         DiagnoseUnsatisfiedConstraint(Satisfaction);
285         return true;
286       }
287     }
288 
289     // If the function has a deduced return type, and we can't deduce it,
290     // then we can't use it either.
291     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
292         DeduceReturnType(FD, Loc))
293       return true;
294 
295     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
296       return true;
297 
298     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
299       return true;
300   }
301 
302   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
303     // Lambdas are only default-constructible or assignable in C++2a onwards.
304     if (MD->getParent()->isLambda() &&
305         ((isa<CXXConstructorDecl>(MD) &&
306           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
307          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
308       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
309         << !isa<CXXConstructorDecl>(MD);
310     }
311   }
312 
313   auto getReferencedObjCProp = [](const NamedDecl *D) ->
314                                       const ObjCPropertyDecl * {
315     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
316       return MD->findPropertyDecl();
317     return nullptr;
318   };
319   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
320     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
321       return true;
322   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
323       return true;
324   }
325 
326   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
327   // Only the variables omp_in and omp_out are allowed in the combiner.
328   // Only the variables omp_priv and omp_orig are allowed in the
329   // initializer-clause.
330   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
331   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
332       isa<VarDecl>(D)) {
333     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
334         << getCurFunction()->HasOMPDeclareReductionCombiner;
335     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
336     return true;
337   }
338 
339   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
340   //  List-items in map clauses on this construct may only refer to the declared
341   //  variable var and entities that could be referenced by a procedure defined
342   //  at the same location
343   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
344       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << getOpenMPDeclareMapperVarName();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   // CUDA/HIP: Diagnose invalid references of host global variables in device
359   // functions. Reference of device global variables in host functions is
360   // allowed through shadow variables therefore it is not diagnosed.
361   if (LangOpts.CUDAIsDevice) {
362     auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext);
363     auto Target = IdentifyCUDATarget(FD);
364     if (FD && Target != CFT_Host) {
365       const auto *VD = dyn_cast<VarDecl>(D);
366       if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() &&
367           !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() &&
368           !VD->getType()->isCUDADeviceBuiltinSurfaceType() &&
369           !VD->getType()->isCUDADeviceBuiltinTextureType() &&
370           !VD->isConstexpr() && !VD->getType().isConstQualified())
371         targetDiag(*Locs.begin(), diag::err_ref_bad_target)
372             << /*host*/ 2 << /*variable*/ 1 << VD << Target;
373     }
374   }
375 
376   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
377     if (auto *VD = dyn_cast<ValueDecl>(D))
378       checkDeviceDecl(VD, Loc);
379 
380     if (!Context.getTargetInfo().isTLSSupported())
381       if (const auto *VD = dyn_cast<VarDecl>(D))
382         if (VD->getTLSKind() != VarDecl::TLS_None)
383           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
384   }
385 
386   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
387       !isUnevaluatedContext()) {
388     // C++ [expr.prim.req.nested] p3
389     //   A local parameter shall only appear as an unevaluated operand
390     //   (Clause 8) within the constraint-expression.
391     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
392         << D;
393     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
394     return true;
395   }
396 
397   return false;
398 }
399 
400 /// DiagnoseSentinelCalls - This routine checks whether a call or
401 /// message-send is to a declaration with the sentinel attribute, and
402 /// if so, it checks that the requirements of the sentinel are
403 /// satisfied.
404 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
405                                  ArrayRef<Expr *> Args) {
406   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
407   if (!attr)
408     return;
409 
410   // The number of formal parameters of the declaration.
411   unsigned numFormalParams;
412 
413   // The kind of declaration.  This is also an index into a %select in
414   // the diagnostic.
415   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
416 
417   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
418     numFormalParams = MD->param_size();
419     calleeType = CT_Method;
420   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
421     numFormalParams = FD->param_size();
422     calleeType = CT_Function;
423   } else if (isa<VarDecl>(D)) {
424     QualType type = cast<ValueDecl>(D)->getType();
425     const FunctionType *fn = nullptr;
426     if (const PointerType *ptr = type->getAs<PointerType>()) {
427       fn = ptr->getPointeeType()->getAs<FunctionType>();
428       if (!fn) return;
429       calleeType = CT_Function;
430     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
431       fn = ptr->getPointeeType()->castAs<FunctionType>();
432       calleeType = CT_Block;
433     } else {
434       return;
435     }
436 
437     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
438       numFormalParams = proto->getNumParams();
439     } else {
440       numFormalParams = 0;
441     }
442   } else {
443     return;
444   }
445 
446   // "nullPos" is the number of formal parameters at the end which
447   // effectively count as part of the variadic arguments.  This is
448   // useful if you would prefer to not have *any* formal parameters,
449   // but the language forces you to have at least one.
450   unsigned nullPos = attr->getNullPos();
451   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
452   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
453 
454   // The number of arguments which should follow the sentinel.
455   unsigned numArgsAfterSentinel = attr->getSentinel();
456 
457   // If there aren't enough arguments for all the formal parameters,
458   // the sentinel, and the args after the sentinel, complain.
459   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
460     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
461     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
462     return;
463   }
464 
465   // Otherwise, find the sentinel expression.
466   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
467   if (!sentinelExpr) return;
468   if (sentinelExpr->isValueDependent()) return;
469   if (Context.isSentinelNullExpr(sentinelExpr)) return;
470 
471   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
472   // or 'NULL' if those are actually defined in the context.  Only use
473   // 'nil' for ObjC methods, where it's much more likely that the
474   // variadic arguments form a list of object pointers.
475   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
476   std::string NullValue;
477   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
478     NullValue = "nil";
479   else if (getLangOpts().CPlusPlus11)
480     NullValue = "nullptr";
481   else if (PP.isMacroDefined("NULL"))
482     NullValue = "NULL";
483   else
484     NullValue = "(void*) 0";
485 
486   if (MissingNilLoc.isInvalid())
487     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
488   else
489     Diag(MissingNilLoc, diag::warn_missing_sentinel)
490       << int(calleeType)
491       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
492   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
493 }
494 
495 SourceRange Sema::getExprRange(Expr *E) const {
496   return E ? E->getSourceRange() : SourceRange();
497 }
498 
499 //===----------------------------------------------------------------------===//
500 //  Standard Promotions and Conversions
501 //===----------------------------------------------------------------------===//
502 
503 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
504 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
505   // Handle any placeholder expressions which made it here.
506   if (E->getType()->isPlaceholderType()) {
507     ExprResult result = CheckPlaceholderExpr(E);
508     if (result.isInvalid()) return ExprError();
509     E = result.get();
510   }
511 
512   QualType Ty = E->getType();
513   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
514 
515   if (Ty->isFunctionType()) {
516     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
517       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
518         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
519           return ExprError();
520 
521     E = ImpCastExprToType(E, Context.getPointerType(Ty),
522                           CK_FunctionToPointerDecay).get();
523   } else if (Ty->isArrayType()) {
524     // In C90 mode, arrays only promote to pointers if the array expression is
525     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
526     // type 'array of type' is converted to an expression that has type 'pointer
527     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
528     // that has type 'array of type' ...".  The relevant change is "an lvalue"
529     // (C90) to "an expression" (C99).
530     //
531     // C++ 4.2p1:
532     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
533     // T" can be converted to an rvalue of type "pointer to T".
534     //
535     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
536       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
537                             CK_ArrayToPointerDecay).get();
538   }
539   return E;
540 }
541 
542 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
543   // Check to see if we are dereferencing a null pointer.  If so,
544   // and if not volatile-qualified, this is undefined behavior that the
545   // optimizer will delete, so warn about it.  People sometimes try to use this
546   // to get a deterministic trap and are surprised by clang's behavior.  This
547   // only handles the pattern "*null", which is a very syntactic check.
548   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
549   if (UO && UO->getOpcode() == UO_Deref &&
550       UO->getSubExpr()->getType()->isPointerType()) {
551     const LangAS AS =
552         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
553     if ((!isTargetAddressSpace(AS) ||
554          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
555         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
556             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
557         !UO->getType().isVolatileQualified()) {
558       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
559                             S.PDiag(diag::warn_indirection_through_null)
560                                 << UO->getSubExpr()->getSourceRange());
561       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
562                             S.PDiag(diag::note_indirection_through_null));
563     }
564   }
565 }
566 
567 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
568                                     SourceLocation AssignLoc,
569                                     const Expr* RHS) {
570   const ObjCIvarDecl *IV = OIRE->getDecl();
571   if (!IV)
572     return;
573 
574   DeclarationName MemberName = IV->getDeclName();
575   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
576   if (!Member || !Member->isStr("isa"))
577     return;
578 
579   const Expr *Base = OIRE->getBase();
580   QualType BaseType = Base->getType();
581   if (OIRE->isArrow())
582     BaseType = BaseType->getPointeeType();
583   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
584     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
585       ObjCInterfaceDecl *ClassDeclared = nullptr;
586       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
587       if (!ClassDeclared->getSuperClass()
588           && (*ClassDeclared->ivar_begin()) == IV) {
589         if (RHS) {
590           NamedDecl *ObjectSetClass =
591             S.LookupSingleName(S.TUScope,
592                                &S.Context.Idents.get("object_setClass"),
593                                SourceLocation(), S.LookupOrdinaryName);
594           if (ObjectSetClass) {
595             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
596             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
597                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
598                                               "object_setClass(")
599                 << FixItHint::CreateReplacement(
600                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
601                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
602           }
603           else
604             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
605         } else {
606           NamedDecl *ObjectGetClass =
607             S.LookupSingleName(S.TUScope,
608                                &S.Context.Idents.get("object_getClass"),
609                                SourceLocation(), S.LookupOrdinaryName);
610           if (ObjectGetClass)
611             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
612                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
613                                               "object_getClass(")
614                 << FixItHint::CreateReplacement(
615                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
616           else
617             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
618         }
619         S.Diag(IV->getLocation(), diag::note_ivar_decl);
620       }
621     }
622 }
623 
624 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
625   // Handle any placeholder expressions which made it here.
626   if (E->getType()->isPlaceholderType()) {
627     ExprResult result = CheckPlaceholderExpr(E);
628     if (result.isInvalid()) return ExprError();
629     E = result.get();
630   }
631 
632   // C++ [conv.lval]p1:
633   //   A glvalue of a non-function, non-array type T can be
634   //   converted to a prvalue.
635   if (!E->isGLValue()) return E;
636 
637   QualType T = E->getType();
638   assert(!T.isNull() && "r-value conversion on typeless expression?");
639 
640   // lvalue-to-rvalue conversion cannot be applied to function or array types.
641   if (T->isFunctionType() || T->isArrayType())
642     return E;
643 
644   // We don't want to throw lvalue-to-rvalue casts on top of
645   // expressions of certain types in C++.
646   if (getLangOpts().CPlusPlus &&
647       (E->getType() == Context.OverloadTy ||
648        T->isDependentType() ||
649        T->isRecordType()))
650     return E;
651 
652   // The C standard is actually really unclear on this point, and
653   // DR106 tells us what the result should be but not why.  It's
654   // generally best to say that void types just doesn't undergo
655   // lvalue-to-rvalue at all.  Note that expressions of unqualified
656   // 'void' type are never l-values, but qualified void can be.
657   if (T->isVoidType())
658     return E;
659 
660   // OpenCL usually rejects direct accesses to values of 'half' type.
661   if (getLangOpts().OpenCL &&
662       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
663       T->isHalfType()) {
664     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
665       << 0 << T;
666     return ExprError();
667   }
668 
669   CheckForNullPointerDereference(*this, E);
670   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
671     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
672                                      &Context.Idents.get("object_getClass"),
673                                      SourceLocation(), LookupOrdinaryName);
674     if (ObjectGetClass)
675       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
676           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
677           << FixItHint::CreateReplacement(
678                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
679     else
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
681   }
682   else if (const ObjCIvarRefExpr *OIRE =
683             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
684     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
685 
686   // C++ [conv.lval]p1:
687   //   [...] If T is a non-class type, the type of the prvalue is the
688   //   cv-unqualified version of T. Otherwise, the type of the
689   //   rvalue is T.
690   //
691   // C99 6.3.2.1p2:
692   //   If the lvalue has qualified type, the value has the unqualified
693   //   version of the type of the lvalue; otherwise, the value has the
694   //   type of the lvalue.
695   if (T.hasQualifiers())
696     T = T.getUnqualifiedType();
697 
698   // Under the MS ABI, lock down the inheritance model now.
699   if (T->isMemberPointerType() &&
700       Context.getTargetInfo().getCXXABI().isMicrosoft())
701     (void)isCompleteType(E->getExprLoc(), T);
702 
703   ExprResult Res = CheckLValueToRValueConversionOperand(E);
704   if (Res.isInvalid())
705     return Res;
706   E = Res.get();
707 
708   // Loading a __weak object implicitly retains the value, so we need a cleanup to
709   // balance that.
710   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711     Cleanup.setExprNeedsCleanups(true);
712 
713   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
714     Cleanup.setExprNeedsCleanups(true);
715 
716   // C++ [conv.lval]p3:
717   //   If T is cv std::nullptr_t, the result is a null pointer constant.
718   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
719   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
720                                  CurFPFeatureOverrides());
721 
722   // C11 6.3.2.1p2:
723   //   ... if the lvalue has atomic type, the value has the non-atomic version
724   //   of the type of the lvalue ...
725   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
726     T = Atomic->getValueType().getUnqualifiedType();
727     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
728                                    nullptr, VK_RValue, FPOptionsOverride());
729   }
730 
731   return Res;
732 }
733 
734 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
735   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
736   if (Res.isInvalid())
737     return ExprError();
738   Res = DefaultLvalueConversion(Res.get());
739   if (Res.isInvalid())
740     return ExprError();
741   return Res;
742 }
743 
744 /// CallExprUnaryConversions - a special case of an unary conversion
745 /// performed on a function designator of a call expression.
746 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
747   QualType Ty = E->getType();
748   ExprResult Res = E;
749   // Only do implicit cast for a function type, but not for a pointer
750   // to function type.
751   if (Ty->isFunctionType()) {
752     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
753                             CK_FunctionToPointerDecay);
754     if (Res.isInvalid())
755       return ExprError();
756   }
757   Res = DefaultLvalueConversion(Res.get());
758   if (Res.isInvalid())
759     return ExprError();
760   return Res.get();
761 }
762 
763 /// UsualUnaryConversions - Performs various conversions that are common to most
764 /// operators (C99 6.3). The conversions of array and function types are
765 /// sometimes suppressed. For example, the array->pointer conversion doesn't
766 /// apply if the array is an argument to the sizeof or address (&) operators.
767 /// In these instances, this routine should *not* be called.
768 ExprResult Sema::UsualUnaryConversions(Expr *E) {
769   // First, convert to an r-value.
770   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
771   if (Res.isInvalid())
772     return ExprError();
773   E = Res.get();
774 
775   QualType Ty = E->getType();
776   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
777 
778   // Half FP have to be promoted to float unless it is natively supported
779   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
780     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
781 
782   // Try to perform integral promotions if the object has a theoretically
783   // promotable type.
784   if (Ty->isIntegralOrUnscopedEnumerationType()) {
785     // C99 6.3.1.1p2:
786     //
787     //   The following may be used in an expression wherever an int or
788     //   unsigned int may be used:
789     //     - an object or expression with an integer type whose integer
790     //       conversion rank is less than or equal to the rank of int
791     //       and unsigned int.
792     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
793     //
794     //   If an int can represent all values of the original type, the
795     //   value is converted to an int; otherwise, it is converted to an
796     //   unsigned int. These are called the integer promotions. All
797     //   other types are unchanged by the integer promotions.
798 
799     QualType PTy = Context.isPromotableBitField(E);
800     if (!PTy.isNull()) {
801       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
802       return E;
803     }
804     if (Ty->isPromotableIntegerType()) {
805       QualType PT = Context.getPromotedIntegerType(Ty);
806       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
807       return E;
808     }
809   }
810   return E;
811 }
812 
813 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
814 /// do not have a prototype. Arguments that have type float or __fp16
815 /// are promoted to double. All other argument types are converted by
816 /// UsualUnaryConversions().
817 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
818   QualType Ty = E->getType();
819   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
820 
821   ExprResult Res = UsualUnaryConversions(E);
822   if (Res.isInvalid())
823     return ExprError();
824   E = Res.get();
825 
826   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
827   // promote to double.
828   // Note that default argument promotion applies only to float (and
829   // half/fp16); it does not apply to _Float16.
830   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
831   if (BTy && (BTy->getKind() == BuiltinType::Half ||
832               BTy->getKind() == BuiltinType::Float)) {
833     if (getLangOpts().OpenCL &&
834         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
835       if (BTy->getKind() == BuiltinType::Half) {
836         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
837       }
838     } else {
839       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
840     }
841   }
842 
843   // C++ performs lvalue-to-rvalue conversion as a default argument
844   // promotion, even on class types, but note:
845   //   C++11 [conv.lval]p2:
846   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
847   //     operand or a subexpression thereof the value contained in the
848   //     referenced object is not accessed. Otherwise, if the glvalue
849   //     has a class type, the conversion copy-initializes a temporary
850   //     of type T from the glvalue and the result of the conversion
851   //     is a prvalue for the temporary.
852   // FIXME: add some way to gate this entire thing for correctness in
853   // potentially potentially evaluated contexts.
854   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
855     ExprResult Temp = PerformCopyInitialization(
856                        InitializedEntity::InitializeTemporary(E->getType()),
857                                                 E->getExprLoc(), E);
858     if (Temp.isInvalid())
859       return ExprError();
860     E = Temp.get();
861   }
862 
863   return E;
864 }
865 
866 /// Determine the degree of POD-ness for an expression.
867 /// Incomplete types are considered POD, since this check can be performed
868 /// when we're in an unevaluated context.
869 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
870   if (Ty->isIncompleteType()) {
871     // C++11 [expr.call]p7:
872     //   After these conversions, if the argument does not have arithmetic,
873     //   enumeration, pointer, pointer to member, or class type, the program
874     //   is ill-formed.
875     //
876     // Since we've already performed array-to-pointer and function-to-pointer
877     // decay, the only such type in C++ is cv void. This also handles
878     // initializer lists as variadic arguments.
879     if (Ty->isVoidType())
880       return VAK_Invalid;
881 
882     if (Ty->isObjCObjectType())
883       return VAK_Invalid;
884     return VAK_Valid;
885   }
886 
887   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
888     return VAK_Invalid;
889 
890   if (Ty.isCXX98PODType(Context))
891     return VAK_Valid;
892 
893   // C++11 [expr.call]p7:
894   //   Passing a potentially-evaluated argument of class type (Clause 9)
895   //   having a non-trivial copy constructor, a non-trivial move constructor,
896   //   or a non-trivial destructor, with no corresponding parameter,
897   //   is conditionally-supported with implementation-defined semantics.
898   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
899     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
900       if (!Record->hasNonTrivialCopyConstructor() &&
901           !Record->hasNonTrivialMoveConstructor() &&
902           !Record->hasNonTrivialDestructor())
903         return VAK_ValidInCXX11;
904 
905   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
906     return VAK_Valid;
907 
908   if (Ty->isObjCObjectType())
909     return VAK_Invalid;
910 
911   if (getLangOpts().MSVCCompat)
912     return VAK_MSVCUndefined;
913 
914   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
915   // permitted to reject them. We should consider doing so.
916   return VAK_Undefined;
917 }
918 
919 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
920   // Don't allow one to pass an Objective-C interface to a vararg.
921   const QualType &Ty = E->getType();
922   VarArgKind VAK = isValidVarArgType(Ty);
923 
924   // Complain about passing non-POD types through varargs.
925   switch (VAK) {
926   case VAK_ValidInCXX11:
927     DiagRuntimeBehavior(
928         E->getBeginLoc(), nullptr,
929         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
930     LLVM_FALLTHROUGH;
931   case VAK_Valid:
932     if (Ty->isRecordType()) {
933       // This is unlikely to be what the user intended. If the class has a
934       // 'c_str' member function, the user probably meant to call that.
935       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
936                           PDiag(diag::warn_pass_class_arg_to_vararg)
937                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
938     }
939     break;
940 
941   case VAK_Undefined:
942   case VAK_MSVCUndefined:
943     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
944                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
945                             << getLangOpts().CPlusPlus11 << Ty << CT);
946     break;
947 
948   case VAK_Invalid:
949     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
950       Diag(E->getBeginLoc(),
951            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
952           << Ty << CT;
953     else if (Ty->isObjCObjectType())
954       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
955                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
956                               << Ty << CT);
957     else
958       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
959           << isa<InitListExpr>(E) << Ty << CT;
960     break;
961   }
962 }
963 
964 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
965 /// will create a trap if the resulting type is not a POD type.
966 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
967                                                   FunctionDecl *FDecl) {
968   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
969     // Strip the unbridged-cast placeholder expression off, if applicable.
970     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
971         (CT == VariadicMethod ||
972          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
973       E = stripARCUnbridgedCast(E);
974 
975     // Otherwise, do normal placeholder checking.
976     } else {
977       ExprResult ExprRes = CheckPlaceholderExpr(E);
978       if (ExprRes.isInvalid())
979         return ExprError();
980       E = ExprRes.get();
981     }
982   }
983 
984   ExprResult ExprRes = DefaultArgumentPromotion(E);
985   if (ExprRes.isInvalid())
986     return ExprError();
987 
988   // Copy blocks to the heap.
989   if (ExprRes.get()->getType()->isBlockPointerType())
990     maybeExtendBlockObject(ExprRes);
991 
992   E = ExprRes.get();
993 
994   // Diagnostics regarding non-POD argument types are
995   // emitted along with format string checking in Sema::CheckFunctionCall().
996   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
997     // Turn this into a trap.
998     CXXScopeSpec SS;
999     SourceLocation TemplateKWLoc;
1000     UnqualifiedId Name;
1001     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1002                        E->getBeginLoc());
1003     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1004                                           /*HasTrailingLParen=*/true,
1005                                           /*IsAddressOfOperand=*/false);
1006     if (TrapFn.isInvalid())
1007       return ExprError();
1008 
1009     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1010                                     None, E->getEndLoc());
1011     if (Call.isInvalid())
1012       return ExprError();
1013 
1014     ExprResult Comma =
1015         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1016     if (Comma.isInvalid())
1017       return ExprError();
1018     return Comma.get();
1019   }
1020 
1021   if (!getLangOpts().CPlusPlus &&
1022       RequireCompleteType(E->getExprLoc(), E->getType(),
1023                           diag::err_call_incomplete_argument))
1024     return ExprError();
1025 
1026   return E;
1027 }
1028 
1029 /// Converts an integer to complex float type.  Helper function of
1030 /// UsualArithmeticConversions()
1031 ///
1032 /// \return false if the integer expression is an integer type and is
1033 /// successfully converted to the complex type.
1034 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1035                                                   ExprResult &ComplexExpr,
1036                                                   QualType IntTy,
1037                                                   QualType ComplexTy,
1038                                                   bool SkipCast) {
1039   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1040   if (SkipCast) return false;
1041   if (IntTy->isIntegerType()) {
1042     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1043     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1044     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1045                                   CK_FloatingRealToComplex);
1046   } else {
1047     assert(IntTy->isComplexIntegerType());
1048     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1049                                   CK_IntegralComplexToFloatingComplex);
1050   }
1051   return false;
1052 }
1053 
1054 /// Handle arithmetic conversion with complex types.  Helper function of
1055 /// UsualArithmeticConversions()
1056 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1057                                              ExprResult &RHS, QualType LHSType,
1058                                              QualType RHSType,
1059                                              bool IsCompAssign) {
1060   // if we have an integer operand, the result is the complex type.
1061   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1062                                              /*skipCast*/false))
1063     return LHSType;
1064   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1065                                              /*skipCast*/IsCompAssign))
1066     return RHSType;
1067 
1068   // This handles complex/complex, complex/float, or float/complex.
1069   // When both operands are complex, the shorter operand is converted to the
1070   // type of the longer, and that is the type of the result. This corresponds
1071   // to what is done when combining two real floating-point operands.
1072   // The fun begins when size promotion occur across type domains.
1073   // From H&S 6.3.4: When one operand is complex and the other is a real
1074   // floating-point type, the less precise type is converted, within it's
1075   // real or complex domain, to the precision of the other type. For example,
1076   // when combining a "long double" with a "double _Complex", the
1077   // "double _Complex" is promoted to "long double _Complex".
1078 
1079   // Compute the rank of the two types, regardless of whether they are complex.
1080   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1081 
1082   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1083   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1084   QualType LHSElementType =
1085       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1086   QualType RHSElementType =
1087       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1088 
1089   QualType ResultType = S.Context.getComplexType(LHSElementType);
1090   if (Order < 0) {
1091     // Promote the precision of the LHS if not an assignment.
1092     ResultType = S.Context.getComplexType(RHSElementType);
1093     if (!IsCompAssign) {
1094       if (LHSComplexType)
1095         LHS =
1096             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1097       else
1098         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1099     }
1100   } else if (Order > 0) {
1101     // Promote the precision of the RHS.
1102     if (RHSComplexType)
1103       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1104     else
1105       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1106   }
1107   return ResultType;
1108 }
1109 
1110 /// Handle arithmetic conversion from integer to float.  Helper function
1111 /// of UsualArithmeticConversions()
1112 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1113                                            ExprResult &IntExpr,
1114                                            QualType FloatTy, QualType IntTy,
1115                                            bool ConvertFloat, bool ConvertInt) {
1116   if (IntTy->isIntegerType()) {
1117     if (ConvertInt)
1118       // Convert intExpr to the lhs floating point type.
1119       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1120                                     CK_IntegralToFloating);
1121     return FloatTy;
1122   }
1123 
1124   // Convert both sides to the appropriate complex float.
1125   assert(IntTy->isComplexIntegerType());
1126   QualType result = S.Context.getComplexType(FloatTy);
1127 
1128   // _Complex int -> _Complex float
1129   if (ConvertInt)
1130     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1131                                   CK_IntegralComplexToFloatingComplex);
1132 
1133   // float -> _Complex float
1134   if (ConvertFloat)
1135     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1136                                     CK_FloatingRealToComplex);
1137 
1138   return result;
1139 }
1140 
1141 /// Handle arithmethic conversion with floating point types.  Helper
1142 /// function of UsualArithmeticConversions()
1143 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1144                                       ExprResult &RHS, QualType LHSType,
1145                                       QualType RHSType, bool IsCompAssign) {
1146   bool LHSFloat = LHSType->isRealFloatingType();
1147   bool RHSFloat = RHSType->isRealFloatingType();
1148 
1149   // N1169 4.1.4: If one of the operands has a floating type and the other
1150   //              operand has a fixed-point type, the fixed-point operand
1151   //              is converted to the floating type [...]
1152   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1153     if (LHSFloat)
1154       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1155     else if (!IsCompAssign)
1156       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1157     return LHSFloat ? LHSType : RHSType;
1158   }
1159 
1160   // If we have two real floating types, convert the smaller operand
1161   // to the bigger result.
1162   if (LHSFloat && RHSFloat) {
1163     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1164     if (order > 0) {
1165       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1166       return LHSType;
1167     }
1168 
1169     assert(order < 0 && "illegal float comparison");
1170     if (!IsCompAssign)
1171       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1172     return RHSType;
1173   }
1174 
1175   if (LHSFloat) {
1176     // Half FP has to be promoted to float unless it is natively supported
1177     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1178       LHSType = S.Context.FloatTy;
1179 
1180     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1181                                       /*ConvertFloat=*/!IsCompAssign,
1182                                       /*ConvertInt=*/ true);
1183   }
1184   assert(RHSFloat);
1185   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1186                                     /*ConvertFloat=*/ true,
1187                                     /*ConvertInt=*/!IsCompAssign);
1188 }
1189 
1190 /// Diagnose attempts to convert between __float128 and long double if
1191 /// there is no support for such conversion. Helper function of
1192 /// UsualArithmeticConversions().
1193 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1194                                       QualType RHSType) {
1195   /*  No issue converting if at least one of the types is not a floating point
1196       type or the two types have the same rank.
1197   */
1198   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1199       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1200     return false;
1201 
1202   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1203          "The remaining types must be floating point types.");
1204 
1205   auto *LHSComplex = LHSType->getAs<ComplexType>();
1206   auto *RHSComplex = RHSType->getAs<ComplexType>();
1207 
1208   QualType LHSElemType = LHSComplex ?
1209     LHSComplex->getElementType() : LHSType;
1210   QualType RHSElemType = RHSComplex ?
1211     RHSComplex->getElementType() : RHSType;
1212 
1213   // No issue if the two types have the same representation
1214   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1215       &S.Context.getFloatTypeSemantics(RHSElemType))
1216     return false;
1217 
1218   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1219                                 RHSElemType == S.Context.LongDoubleTy);
1220   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1221                             RHSElemType == S.Context.Float128Ty);
1222 
1223   // We've handled the situation where __float128 and long double have the same
1224   // representation. We allow all conversions for all possible long double types
1225   // except PPC's double double.
1226   return Float128AndLongDouble &&
1227     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1228      &llvm::APFloat::PPCDoubleDouble());
1229 }
1230 
1231 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1232 
1233 namespace {
1234 /// These helper callbacks are placed in an anonymous namespace to
1235 /// permit their use as function template parameters.
1236 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1237   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1238 }
1239 
1240 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1241   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1242                              CK_IntegralComplexCast);
1243 }
1244 }
1245 
1246 /// Handle integer arithmetic conversions.  Helper function of
1247 /// UsualArithmeticConversions()
1248 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1249 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1250                                         ExprResult &RHS, QualType LHSType,
1251                                         QualType RHSType, bool IsCompAssign) {
1252   // The rules for this case are in C99 6.3.1.8
1253   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1254   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1255   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1256   if (LHSSigned == RHSSigned) {
1257     // Same signedness; use the higher-ranked type
1258     if (order >= 0) {
1259       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1260       return LHSType;
1261     } else if (!IsCompAssign)
1262       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1263     return RHSType;
1264   } else if (order != (LHSSigned ? 1 : -1)) {
1265     // The unsigned type has greater than or equal rank to the
1266     // signed type, so use the unsigned type
1267     if (RHSSigned) {
1268       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1269       return LHSType;
1270     } else if (!IsCompAssign)
1271       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1272     return RHSType;
1273   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1274     // The two types are different widths; if we are here, that
1275     // means the signed type is larger than the unsigned type, so
1276     // use the signed type.
1277     if (LHSSigned) {
1278       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1279       return LHSType;
1280     } else if (!IsCompAssign)
1281       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1282     return RHSType;
1283   } else {
1284     // The signed type is higher-ranked than the unsigned type,
1285     // but isn't actually any bigger (like unsigned int and long
1286     // on most 32-bit systems).  Use the unsigned type corresponding
1287     // to the signed type.
1288     QualType result =
1289       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1290     RHS = (*doRHSCast)(S, RHS.get(), result);
1291     if (!IsCompAssign)
1292       LHS = (*doLHSCast)(S, LHS.get(), result);
1293     return result;
1294   }
1295 }
1296 
1297 /// Handle conversions with GCC complex int extension.  Helper function
1298 /// of UsualArithmeticConversions()
1299 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1300                                            ExprResult &RHS, QualType LHSType,
1301                                            QualType RHSType,
1302                                            bool IsCompAssign) {
1303   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1304   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1305 
1306   if (LHSComplexInt && RHSComplexInt) {
1307     QualType LHSEltType = LHSComplexInt->getElementType();
1308     QualType RHSEltType = RHSComplexInt->getElementType();
1309     QualType ScalarType =
1310       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1311         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1312 
1313     return S.Context.getComplexType(ScalarType);
1314   }
1315 
1316   if (LHSComplexInt) {
1317     QualType LHSEltType = LHSComplexInt->getElementType();
1318     QualType ScalarType =
1319       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1320         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1321     QualType ComplexType = S.Context.getComplexType(ScalarType);
1322     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1323                               CK_IntegralRealToComplex);
1324 
1325     return ComplexType;
1326   }
1327 
1328   assert(RHSComplexInt);
1329 
1330   QualType RHSEltType = RHSComplexInt->getElementType();
1331   QualType ScalarType =
1332     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1333       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1334   QualType ComplexType = S.Context.getComplexType(ScalarType);
1335 
1336   if (!IsCompAssign)
1337     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1338                               CK_IntegralRealToComplex);
1339   return ComplexType;
1340 }
1341 
1342 /// Return the rank of a given fixed point or integer type. The value itself
1343 /// doesn't matter, but the values must be increasing with proper increasing
1344 /// rank as described in N1169 4.1.1.
1345 static unsigned GetFixedPointRank(QualType Ty) {
1346   const auto *BTy = Ty->getAs<BuiltinType>();
1347   assert(BTy && "Expected a builtin type.");
1348 
1349   switch (BTy->getKind()) {
1350   case BuiltinType::ShortFract:
1351   case BuiltinType::UShortFract:
1352   case BuiltinType::SatShortFract:
1353   case BuiltinType::SatUShortFract:
1354     return 1;
1355   case BuiltinType::Fract:
1356   case BuiltinType::UFract:
1357   case BuiltinType::SatFract:
1358   case BuiltinType::SatUFract:
1359     return 2;
1360   case BuiltinType::LongFract:
1361   case BuiltinType::ULongFract:
1362   case BuiltinType::SatLongFract:
1363   case BuiltinType::SatULongFract:
1364     return 3;
1365   case BuiltinType::ShortAccum:
1366   case BuiltinType::UShortAccum:
1367   case BuiltinType::SatShortAccum:
1368   case BuiltinType::SatUShortAccum:
1369     return 4;
1370   case BuiltinType::Accum:
1371   case BuiltinType::UAccum:
1372   case BuiltinType::SatAccum:
1373   case BuiltinType::SatUAccum:
1374     return 5;
1375   case BuiltinType::LongAccum:
1376   case BuiltinType::ULongAccum:
1377   case BuiltinType::SatLongAccum:
1378   case BuiltinType::SatULongAccum:
1379     return 6;
1380   default:
1381     if (BTy->isInteger())
1382       return 0;
1383     llvm_unreachable("Unexpected fixed point or integer type");
1384   }
1385 }
1386 
1387 /// handleFixedPointConversion - Fixed point operations between fixed
1388 /// point types and integers or other fixed point types do not fall under
1389 /// usual arithmetic conversion since these conversions could result in loss
1390 /// of precsision (N1169 4.1.4). These operations should be calculated with
1391 /// the full precision of their result type (N1169 4.1.6.2.1).
1392 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1393                                            QualType RHSTy) {
1394   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1395          "Expected at least one of the operands to be a fixed point type");
1396   assert((LHSTy->isFixedPointOrIntegerType() ||
1397           RHSTy->isFixedPointOrIntegerType()) &&
1398          "Special fixed point arithmetic operation conversions are only "
1399          "applied to ints or other fixed point types");
1400 
1401   // If one operand has signed fixed-point type and the other operand has
1402   // unsigned fixed-point type, then the unsigned fixed-point operand is
1403   // converted to its corresponding signed fixed-point type and the resulting
1404   // type is the type of the converted operand.
1405   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1406     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1407   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1408     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1409 
1410   // The result type is the type with the highest rank, whereby a fixed-point
1411   // conversion rank is always greater than an integer conversion rank; if the
1412   // type of either of the operands is a saturating fixedpoint type, the result
1413   // type shall be the saturating fixed-point type corresponding to the type
1414   // with the highest rank; the resulting value is converted (taking into
1415   // account rounding and overflow) to the precision of the resulting type.
1416   // Same ranks between signed and unsigned types are resolved earlier, so both
1417   // types are either signed or both unsigned at this point.
1418   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1419   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1420 
1421   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1422 
1423   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1424     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1425 
1426   return ResultTy;
1427 }
1428 
1429 /// Check that the usual arithmetic conversions can be performed on this pair of
1430 /// expressions that might be of enumeration type.
1431 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1432                                            SourceLocation Loc,
1433                                            Sema::ArithConvKind ACK) {
1434   // C++2a [expr.arith.conv]p1:
1435   //   If one operand is of enumeration type and the other operand is of a
1436   //   different enumeration type or a floating-point type, this behavior is
1437   //   deprecated ([depr.arith.conv.enum]).
1438   //
1439   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1440   // Eventually we will presumably reject these cases (in C++23 onwards?).
1441   QualType L = LHS->getType(), R = RHS->getType();
1442   bool LEnum = L->isUnscopedEnumerationType(),
1443        REnum = R->isUnscopedEnumerationType();
1444   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1445   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1446       (REnum && L->isFloatingType())) {
1447     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1448                     ? diag::warn_arith_conv_enum_float_cxx20
1449                     : diag::warn_arith_conv_enum_float)
1450         << LHS->getSourceRange() << RHS->getSourceRange()
1451         << (int)ACK << LEnum << L << R;
1452   } else if (!IsCompAssign && LEnum && REnum &&
1453              !S.Context.hasSameUnqualifiedType(L, R)) {
1454     unsigned DiagID;
1455     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1456         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1457       // If either enumeration type is unnamed, it's less likely that the
1458       // user cares about this, but this situation is still deprecated in
1459       // C++2a. Use a different warning group.
1460       DiagID = S.getLangOpts().CPlusPlus20
1461                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1462                     : diag::warn_arith_conv_mixed_anon_enum_types;
1463     } else if (ACK == Sema::ACK_Conditional) {
1464       // Conditional expressions are separated out because they have
1465       // historically had a different warning flag.
1466       DiagID = S.getLangOpts().CPlusPlus20
1467                    ? diag::warn_conditional_mixed_enum_types_cxx20
1468                    : diag::warn_conditional_mixed_enum_types;
1469     } else if (ACK == Sema::ACK_Comparison) {
1470       // Comparison expressions are separated out because they have
1471       // historically had a different warning flag.
1472       DiagID = S.getLangOpts().CPlusPlus20
1473                    ? diag::warn_comparison_mixed_enum_types_cxx20
1474                    : diag::warn_comparison_mixed_enum_types;
1475     } else {
1476       DiagID = S.getLangOpts().CPlusPlus20
1477                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1478                    : diag::warn_arith_conv_mixed_enum_types;
1479     }
1480     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1481                         << (int)ACK << L << R;
1482   }
1483 }
1484 
1485 /// UsualArithmeticConversions - Performs various conversions that are common to
1486 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1487 /// routine returns the first non-arithmetic type found. The client is
1488 /// responsible for emitting appropriate error diagnostics.
1489 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1490                                           SourceLocation Loc,
1491                                           ArithConvKind ACK) {
1492   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1493 
1494   if (ACK != ACK_CompAssign) {
1495     LHS = UsualUnaryConversions(LHS.get());
1496     if (LHS.isInvalid())
1497       return QualType();
1498   }
1499 
1500   RHS = UsualUnaryConversions(RHS.get());
1501   if (RHS.isInvalid())
1502     return QualType();
1503 
1504   // For conversion purposes, we ignore any qualifiers.
1505   // For example, "const float" and "float" are equivalent.
1506   QualType LHSType =
1507     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1508   QualType RHSType =
1509     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1510 
1511   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1512   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1513     LHSType = AtomicLHS->getValueType();
1514 
1515   // If both types are identical, no conversion is needed.
1516   if (LHSType == RHSType)
1517     return LHSType;
1518 
1519   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1520   // The caller can deal with this (e.g. pointer + int).
1521   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1522     return QualType();
1523 
1524   // Apply unary and bitfield promotions to the LHS's type.
1525   QualType LHSUnpromotedType = LHSType;
1526   if (LHSType->isPromotableIntegerType())
1527     LHSType = Context.getPromotedIntegerType(LHSType);
1528   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1529   if (!LHSBitfieldPromoteTy.isNull())
1530     LHSType = LHSBitfieldPromoteTy;
1531   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1532     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1533 
1534   // If both types are identical, no conversion is needed.
1535   if (LHSType == RHSType)
1536     return LHSType;
1537 
1538   // ExtInt types aren't subject to conversions between them or normal integers,
1539   // so this fails.
1540   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1541     return QualType();
1542 
1543   // At this point, we have two different arithmetic types.
1544 
1545   // Diagnose attempts to convert between __float128 and long double where
1546   // such conversions currently can't be handled.
1547   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1548     return QualType();
1549 
1550   // Handle complex types first (C99 6.3.1.8p1).
1551   if (LHSType->isComplexType() || RHSType->isComplexType())
1552     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1553                                         ACK == ACK_CompAssign);
1554 
1555   // Now handle "real" floating types (i.e. float, double, long double).
1556   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1557     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1558                                  ACK == ACK_CompAssign);
1559 
1560   // Handle GCC complex int extension.
1561   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1562     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1563                                       ACK == ACK_CompAssign);
1564 
1565   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1566     return handleFixedPointConversion(*this, LHSType, RHSType);
1567 
1568   // Finally, we have two differing integer types.
1569   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1570            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1571 }
1572 
1573 //===----------------------------------------------------------------------===//
1574 //  Semantic Analysis for various Expression Types
1575 //===----------------------------------------------------------------------===//
1576 
1577 
1578 ExprResult
1579 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1580                                 SourceLocation DefaultLoc,
1581                                 SourceLocation RParenLoc,
1582                                 Expr *ControllingExpr,
1583                                 ArrayRef<ParsedType> ArgTypes,
1584                                 ArrayRef<Expr *> ArgExprs) {
1585   unsigned NumAssocs = ArgTypes.size();
1586   assert(NumAssocs == ArgExprs.size());
1587 
1588   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1589   for (unsigned i = 0; i < NumAssocs; ++i) {
1590     if (ArgTypes[i])
1591       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1592     else
1593       Types[i] = nullptr;
1594   }
1595 
1596   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1597                                              ControllingExpr,
1598                                              llvm::makeArrayRef(Types, NumAssocs),
1599                                              ArgExprs);
1600   delete [] Types;
1601   return ER;
1602 }
1603 
1604 ExprResult
1605 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1606                                  SourceLocation DefaultLoc,
1607                                  SourceLocation RParenLoc,
1608                                  Expr *ControllingExpr,
1609                                  ArrayRef<TypeSourceInfo *> Types,
1610                                  ArrayRef<Expr *> Exprs) {
1611   unsigned NumAssocs = Types.size();
1612   assert(NumAssocs == Exprs.size());
1613 
1614   // Decay and strip qualifiers for the controlling expression type, and handle
1615   // placeholder type replacement. See committee discussion from WG14 DR423.
1616   {
1617     EnterExpressionEvaluationContext Unevaluated(
1618         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1619     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1620     if (R.isInvalid())
1621       return ExprError();
1622     ControllingExpr = R.get();
1623   }
1624 
1625   // The controlling expression is an unevaluated operand, so side effects are
1626   // likely unintended.
1627   if (!inTemplateInstantiation() &&
1628       ControllingExpr->HasSideEffects(Context, false))
1629     Diag(ControllingExpr->getExprLoc(),
1630          diag::warn_side_effects_unevaluated_context);
1631 
1632   bool TypeErrorFound = false,
1633        IsResultDependent = ControllingExpr->isTypeDependent(),
1634        ContainsUnexpandedParameterPack
1635          = ControllingExpr->containsUnexpandedParameterPack();
1636 
1637   for (unsigned i = 0; i < NumAssocs; ++i) {
1638     if (Exprs[i]->containsUnexpandedParameterPack())
1639       ContainsUnexpandedParameterPack = true;
1640 
1641     if (Types[i]) {
1642       if (Types[i]->getType()->containsUnexpandedParameterPack())
1643         ContainsUnexpandedParameterPack = true;
1644 
1645       if (Types[i]->getType()->isDependentType()) {
1646         IsResultDependent = true;
1647       } else {
1648         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1649         // complete object type other than a variably modified type."
1650         unsigned D = 0;
1651         if (Types[i]->getType()->isIncompleteType())
1652           D = diag::err_assoc_type_incomplete;
1653         else if (!Types[i]->getType()->isObjectType())
1654           D = diag::err_assoc_type_nonobject;
1655         else if (Types[i]->getType()->isVariablyModifiedType())
1656           D = diag::err_assoc_type_variably_modified;
1657 
1658         if (D != 0) {
1659           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1660             << Types[i]->getTypeLoc().getSourceRange()
1661             << Types[i]->getType();
1662           TypeErrorFound = true;
1663         }
1664 
1665         // C11 6.5.1.1p2 "No two generic associations in the same generic
1666         // selection shall specify compatible types."
1667         for (unsigned j = i+1; j < NumAssocs; ++j)
1668           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1669               Context.typesAreCompatible(Types[i]->getType(),
1670                                          Types[j]->getType())) {
1671             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1672                  diag::err_assoc_compatible_types)
1673               << Types[j]->getTypeLoc().getSourceRange()
1674               << Types[j]->getType()
1675               << Types[i]->getType();
1676             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1677                  diag::note_compat_assoc)
1678               << Types[i]->getTypeLoc().getSourceRange()
1679               << Types[i]->getType();
1680             TypeErrorFound = true;
1681           }
1682       }
1683     }
1684   }
1685   if (TypeErrorFound)
1686     return ExprError();
1687 
1688   // If we determined that the generic selection is result-dependent, don't
1689   // try to compute the result expression.
1690   if (IsResultDependent)
1691     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1692                                         Exprs, DefaultLoc, RParenLoc,
1693                                         ContainsUnexpandedParameterPack);
1694 
1695   SmallVector<unsigned, 1> CompatIndices;
1696   unsigned DefaultIndex = -1U;
1697   for (unsigned i = 0; i < NumAssocs; ++i) {
1698     if (!Types[i])
1699       DefaultIndex = i;
1700     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1701                                         Types[i]->getType()))
1702       CompatIndices.push_back(i);
1703   }
1704 
1705   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1706   // type compatible with at most one of the types named in its generic
1707   // association list."
1708   if (CompatIndices.size() > 1) {
1709     // We strip parens here because the controlling expression is typically
1710     // parenthesized in macro definitions.
1711     ControllingExpr = ControllingExpr->IgnoreParens();
1712     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1713         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1714         << (unsigned)CompatIndices.size();
1715     for (unsigned I : CompatIndices) {
1716       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1717            diag::note_compat_assoc)
1718         << Types[I]->getTypeLoc().getSourceRange()
1719         << Types[I]->getType();
1720     }
1721     return ExprError();
1722   }
1723 
1724   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1725   // its controlling expression shall have type compatible with exactly one of
1726   // the types named in its generic association list."
1727   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1728     // We strip parens here because the controlling expression is typically
1729     // parenthesized in macro definitions.
1730     ControllingExpr = ControllingExpr->IgnoreParens();
1731     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1732         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1733     return ExprError();
1734   }
1735 
1736   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1737   // type name that is compatible with the type of the controlling expression,
1738   // then the result expression of the generic selection is the expression
1739   // in that generic association. Otherwise, the result expression of the
1740   // generic selection is the expression in the default generic association."
1741   unsigned ResultIndex =
1742     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1743 
1744   return GenericSelectionExpr::Create(
1745       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1746       ContainsUnexpandedParameterPack, ResultIndex);
1747 }
1748 
1749 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1750 /// location of the token and the offset of the ud-suffix within it.
1751 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1752                                      unsigned Offset) {
1753   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1754                                         S.getLangOpts());
1755 }
1756 
1757 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1758 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1759 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1760                                                  IdentifierInfo *UDSuffix,
1761                                                  SourceLocation UDSuffixLoc,
1762                                                  ArrayRef<Expr*> Args,
1763                                                  SourceLocation LitEndLoc) {
1764   assert(Args.size() <= 2 && "too many arguments for literal operator");
1765 
1766   QualType ArgTy[2];
1767   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1768     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1769     if (ArgTy[ArgIdx]->isArrayType())
1770       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1771   }
1772 
1773   DeclarationName OpName =
1774     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1775   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1776   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1777 
1778   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1779   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1780                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1781                               /*AllowStringTemplatePack*/ false,
1782                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1783     return ExprError();
1784 
1785   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1786 }
1787 
1788 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1789 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1790 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1791 /// multiple tokens.  However, the common case is that StringToks points to one
1792 /// string.
1793 ///
1794 ExprResult
1795 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1796   assert(!StringToks.empty() && "Must have at least one string!");
1797 
1798   StringLiteralParser Literal(StringToks, PP);
1799   if (Literal.hadError)
1800     return ExprError();
1801 
1802   SmallVector<SourceLocation, 4> StringTokLocs;
1803   for (const Token &Tok : StringToks)
1804     StringTokLocs.push_back(Tok.getLocation());
1805 
1806   QualType CharTy = Context.CharTy;
1807   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1808   if (Literal.isWide()) {
1809     CharTy = Context.getWideCharType();
1810     Kind = StringLiteral::Wide;
1811   } else if (Literal.isUTF8()) {
1812     if (getLangOpts().Char8)
1813       CharTy = Context.Char8Ty;
1814     Kind = StringLiteral::UTF8;
1815   } else if (Literal.isUTF16()) {
1816     CharTy = Context.Char16Ty;
1817     Kind = StringLiteral::UTF16;
1818   } else if (Literal.isUTF32()) {
1819     CharTy = Context.Char32Ty;
1820     Kind = StringLiteral::UTF32;
1821   } else if (Literal.isPascal()) {
1822     CharTy = Context.UnsignedCharTy;
1823   }
1824 
1825   // Warn on initializing an array of char from a u8 string literal; this
1826   // becomes ill-formed in C++2a.
1827   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1828       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1829     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1830 
1831     // Create removals for all 'u8' prefixes in the string literal(s). This
1832     // ensures C++2a compatibility (but may change the program behavior when
1833     // built by non-Clang compilers for which the execution character set is
1834     // not always UTF-8).
1835     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1836     SourceLocation RemovalDiagLoc;
1837     for (const Token &Tok : StringToks) {
1838       if (Tok.getKind() == tok::utf8_string_literal) {
1839         if (RemovalDiagLoc.isInvalid())
1840           RemovalDiagLoc = Tok.getLocation();
1841         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1842             Tok.getLocation(),
1843             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1844                                            getSourceManager(), getLangOpts())));
1845       }
1846     }
1847     Diag(RemovalDiagLoc, RemovalDiag);
1848   }
1849 
1850   QualType StrTy =
1851       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1852 
1853   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1854   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1855                                              Kind, Literal.Pascal, StrTy,
1856                                              &StringTokLocs[0],
1857                                              StringTokLocs.size());
1858   if (Literal.getUDSuffix().empty())
1859     return Lit;
1860 
1861   // We're building a user-defined literal.
1862   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1863   SourceLocation UDSuffixLoc =
1864     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1865                    Literal.getUDSuffixOffset());
1866 
1867   // Make sure we're allowed user-defined literals here.
1868   if (!UDLScope)
1869     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1870 
1871   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1872   //   operator "" X (str, len)
1873   QualType SizeType = Context.getSizeType();
1874 
1875   DeclarationName OpName =
1876     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1877   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1878   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1879 
1880   QualType ArgTy[] = {
1881     Context.getArrayDecayedType(StrTy), SizeType
1882   };
1883 
1884   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1885   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1886                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1887                                 /*AllowStringTemplatePack*/ true,
1888                                 /*DiagnoseMissing*/ true, Lit)) {
1889 
1890   case LOLR_Cooked: {
1891     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1892     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1893                                                     StringTokLocs[0]);
1894     Expr *Args[] = { Lit, LenArg };
1895 
1896     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1897   }
1898 
1899   case LOLR_Template: {
1900     TemplateArgumentListInfo ExplicitArgs;
1901     TemplateArgument Arg(Lit);
1902     TemplateArgumentLocInfo ArgInfo(Lit);
1903     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1904     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1905                                     &ExplicitArgs);
1906   }
1907 
1908   case LOLR_StringTemplatePack: {
1909     TemplateArgumentListInfo ExplicitArgs;
1910 
1911     unsigned CharBits = Context.getIntWidth(CharTy);
1912     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1913     llvm::APSInt Value(CharBits, CharIsUnsigned);
1914 
1915     TemplateArgument TypeArg(CharTy);
1916     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1917     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1918 
1919     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1920       Value = Lit->getCodeUnit(I);
1921       TemplateArgument Arg(Context, Value, CharTy);
1922       TemplateArgumentLocInfo ArgInfo;
1923       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1924     }
1925     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1926                                     &ExplicitArgs);
1927   }
1928   case LOLR_Raw:
1929   case LOLR_ErrorNoDiagnostic:
1930     llvm_unreachable("unexpected literal operator lookup result");
1931   case LOLR_Error:
1932     return ExprError();
1933   }
1934   llvm_unreachable("unexpected literal operator lookup result");
1935 }
1936 
1937 DeclRefExpr *
1938 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1939                        SourceLocation Loc,
1940                        const CXXScopeSpec *SS) {
1941   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1942   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1943 }
1944 
1945 DeclRefExpr *
1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1947                        const DeclarationNameInfo &NameInfo,
1948                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1949                        SourceLocation TemplateKWLoc,
1950                        const TemplateArgumentListInfo *TemplateArgs) {
1951   NestedNameSpecifierLoc NNS =
1952       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1953   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1954                           TemplateArgs);
1955 }
1956 
1957 // CUDA/HIP: Check whether a captured reference variable is referencing a
1958 // host variable in a device or host device lambda.
1959 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1960                                                             VarDecl *VD) {
1961   if (!S.getLangOpts().CUDA || !VD->hasInit())
1962     return false;
1963   assert(VD->getType()->isReferenceType());
1964 
1965   // Check whether the reference variable is referencing a host variable.
1966   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1967   if (!DRE)
1968     return false;
1969   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1970   if (!Referee || !Referee->hasGlobalStorage() ||
1971       Referee->hasAttr<CUDADeviceAttr>())
1972     return false;
1973 
1974   // Check whether the current function is a device or host device lambda.
1975   // Check whether the reference variable is a capture by getDeclContext()
1976   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1977   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1978   if (MD && MD->getParent()->isLambda() &&
1979       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1980       VD->getDeclContext() != MD)
1981     return true;
1982 
1983   return false;
1984 }
1985 
1986 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1987   // A declaration named in an unevaluated operand never constitutes an odr-use.
1988   if (isUnevaluatedContext())
1989     return NOUR_Unevaluated;
1990 
1991   // C++2a [basic.def.odr]p4:
1992   //   A variable x whose name appears as a potentially-evaluated expression e
1993   //   is odr-used by e unless [...] x is a reference that is usable in
1994   //   constant expressions.
1995   // CUDA/HIP:
1996   //   If a reference variable referencing a host variable is captured in a
1997   //   device or host device lambda, the value of the referee must be copied
1998   //   to the capture and the reference variable must be treated as odr-use
1999   //   since the value of the referee is not known at compile time and must
2000   //   be loaded from the captured.
2001   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2002     if (VD->getType()->isReferenceType() &&
2003         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2004         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2005         VD->isUsableInConstantExpressions(Context))
2006       return NOUR_Constant;
2007   }
2008 
2009   // All remaining non-variable cases constitute an odr-use. For variables, we
2010   // need to wait and see how the expression is used.
2011   return NOUR_None;
2012 }
2013 
2014 /// BuildDeclRefExpr - Build an expression that references a
2015 /// declaration that does not require a closure capture.
2016 DeclRefExpr *
2017 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2018                        const DeclarationNameInfo &NameInfo,
2019                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2020                        SourceLocation TemplateKWLoc,
2021                        const TemplateArgumentListInfo *TemplateArgs) {
2022   bool RefersToCapturedVariable =
2023       isa<VarDecl>(D) &&
2024       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2025 
2026   DeclRefExpr *E = DeclRefExpr::Create(
2027       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2028       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2029   MarkDeclRefReferenced(E);
2030 
2031   // C++ [except.spec]p17:
2032   //   An exception-specification is considered to be needed when:
2033   //   - in an expression, the function is the unique lookup result or
2034   //     the selected member of a set of overloaded functions.
2035   //
2036   // We delay doing this until after we've built the function reference and
2037   // marked it as used so that:
2038   //  a) if the function is defaulted, we get errors from defining it before /
2039   //     instead of errors from computing its exception specification, and
2040   //  b) if the function is a defaulted comparison, we can use the body we
2041   //     build when defining it as input to the exception specification
2042   //     computation rather than computing a new body.
2043   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2044     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2045       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2046         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2047     }
2048   }
2049 
2050   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2051       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2052       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2053     getCurFunction()->recordUseOfWeak(E);
2054 
2055   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2056   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2057     FD = IFD->getAnonField();
2058   if (FD) {
2059     UnusedPrivateFields.remove(FD);
2060     // Just in case we're building an illegal pointer-to-member.
2061     if (FD->isBitField())
2062       E->setObjectKind(OK_BitField);
2063   }
2064 
2065   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2066   // designates a bit-field.
2067   if (auto *BD = dyn_cast<BindingDecl>(D))
2068     if (auto *BE = BD->getBinding())
2069       E->setObjectKind(BE->getObjectKind());
2070 
2071   return E;
2072 }
2073 
2074 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2075 /// possibly a list of template arguments.
2076 ///
2077 /// If this produces template arguments, it is permitted to call
2078 /// DecomposeTemplateName.
2079 ///
2080 /// This actually loses a lot of source location information for
2081 /// non-standard name kinds; we should consider preserving that in
2082 /// some way.
2083 void
2084 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2085                              TemplateArgumentListInfo &Buffer,
2086                              DeclarationNameInfo &NameInfo,
2087                              const TemplateArgumentListInfo *&TemplateArgs) {
2088   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2089     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2090     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2091 
2092     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2093                                        Id.TemplateId->NumArgs);
2094     translateTemplateArguments(TemplateArgsPtr, Buffer);
2095 
2096     TemplateName TName = Id.TemplateId->Template.get();
2097     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2098     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2099     TemplateArgs = &Buffer;
2100   } else {
2101     NameInfo = GetNameFromUnqualifiedId(Id);
2102     TemplateArgs = nullptr;
2103   }
2104 }
2105 
2106 static void emitEmptyLookupTypoDiagnostic(
2107     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2108     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2109     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2110   DeclContext *Ctx =
2111       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2112   if (!TC) {
2113     // Emit a special diagnostic for failed member lookups.
2114     // FIXME: computing the declaration context might fail here (?)
2115     if (Ctx)
2116       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2117                                                  << SS.getRange();
2118     else
2119       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2120     return;
2121   }
2122 
2123   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2124   bool DroppedSpecifier =
2125       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2126   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2127                         ? diag::note_implicit_param_decl
2128                         : diag::note_previous_decl;
2129   if (!Ctx)
2130     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2131                          SemaRef.PDiag(NoteID));
2132   else
2133     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2134                                  << Typo << Ctx << DroppedSpecifier
2135                                  << SS.getRange(),
2136                          SemaRef.PDiag(NoteID));
2137 }
2138 
2139 /// Diagnose a lookup that found results in an enclosing class during error
2140 /// recovery. This usually indicates that the results were found in a dependent
2141 /// base class that could not be searched as part of a template definition.
2142 /// Always issues a diagnostic (though this may be only a warning in MS
2143 /// compatibility mode).
2144 ///
2145 /// Return \c true if the error is unrecoverable, or \c false if the caller
2146 /// should attempt to recover using these lookup results.
2147 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2148   // During a default argument instantiation the CurContext points
2149   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2150   // function parameter list, hence add an explicit check.
2151   bool isDefaultArgument =
2152       !CodeSynthesisContexts.empty() &&
2153       CodeSynthesisContexts.back().Kind ==
2154           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2155   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2156   bool isInstance = CurMethod && CurMethod->isInstance() &&
2157                     R.getNamingClass() == CurMethod->getParent() &&
2158                     !isDefaultArgument;
2159 
2160   // There are two ways we can find a class-scope declaration during template
2161   // instantiation that we did not find in the template definition: if it is a
2162   // member of a dependent base class, or if it is declared after the point of
2163   // use in the same class. Distinguish these by comparing the class in which
2164   // the member was found to the naming class of the lookup.
2165   unsigned DiagID = diag::err_found_in_dependent_base;
2166   unsigned NoteID = diag::note_member_declared_at;
2167   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2168     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2169                                       : diag::err_found_later_in_class;
2170   } else if (getLangOpts().MSVCCompat) {
2171     DiagID = diag::ext_found_in_dependent_base;
2172     NoteID = diag::note_dependent_member_use;
2173   }
2174 
2175   if (isInstance) {
2176     // Give a code modification hint to insert 'this->'.
2177     Diag(R.getNameLoc(), DiagID)
2178         << R.getLookupName()
2179         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2180     CheckCXXThisCapture(R.getNameLoc());
2181   } else {
2182     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2183     // they're not shadowed).
2184     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2185   }
2186 
2187   for (NamedDecl *D : R)
2188     Diag(D->getLocation(), NoteID);
2189 
2190   // Return true if we are inside a default argument instantiation
2191   // and the found name refers to an instance member function, otherwise
2192   // the caller will try to create an implicit member call and this is wrong
2193   // for default arguments.
2194   //
2195   // FIXME: Is this special case necessary? We could allow the caller to
2196   // diagnose this.
2197   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2198     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2199     return true;
2200   }
2201 
2202   // Tell the callee to try to recover.
2203   return false;
2204 }
2205 
2206 /// Diagnose an empty lookup.
2207 ///
2208 /// \return false if new lookup candidates were found
2209 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2210                                CorrectionCandidateCallback &CCC,
2211                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2212                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2213   DeclarationName Name = R.getLookupName();
2214 
2215   unsigned diagnostic = diag::err_undeclared_var_use;
2216   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2217   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2218       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2219       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2220     diagnostic = diag::err_undeclared_use;
2221     diagnostic_suggest = diag::err_undeclared_use_suggest;
2222   }
2223 
2224   // If the original lookup was an unqualified lookup, fake an
2225   // unqualified lookup.  This is useful when (for example) the
2226   // original lookup would not have found something because it was a
2227   // dependent name.
2228   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2229   while (DC) {
2230     if (isa<CXXRecordDecl>(DC)) {
2231       LookupQualifiedName(R, DC);
2232 
2233       if (!R.empty()) {
2234         // Don't give errors about ambiguities in this lookup.
2235         R.suppressDiagnostics();
2236 
2237         // If there's a best viable function among the results, only mention
2238         // that one in the notes.
2239         OverloadCandidateSet Candidates(R.getNameLoc(),
2240                                         OverloadCandidateSet::CSK_Normal);
2241         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2242         OverloadCandidateSet::iterator Best;
2243         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2244             OR_Success) {
2245           R.clear();
2246           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2247           R.resolveKind();
2248         }
2249 
2250         return DiagnoseDependentMemberLookup(R);
2251       }
2252 
2253       R.clear();
2254     }
2255 
2256     DC = DC->getLookupParent();
2257   }
2258 
2259   // We didn't find anything, so try to correct for a typo.
2260   TypoCorrection Corrected;
2261   if (S && Out) {
2262     SourceLocation TypoLoc = R.getNameLoc();
2263     assert(!ExplicitTemplateArgs &&
2264            "Diagnosing an empty lookup with explicit template args!");
2265     *Out = CorrectTypoDelayed(
2266         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2267         [=](const TypoCorrection &TC) {
2268           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2269                                         diagnostic, diagnostic_suggest);
2270         },
2271         nullptr, CTK_ErrorRecovery);
2272     if (*Out)
2273       return true;
2274   } else if (S &&
2275              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2276                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2277     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2278     bool DroppedSpecifier =
2279         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2280     R.setLookupName(Corrected.getCorrection());
2281 
2282     bool AcceptableWithRecovery = false;
2283     bool AcceptableWithoutRecovery = false;
2284     NamedDecl *ND = Corrected.getFoundDecl();
2285     if (ND) {
2286       if (Corrected.isOverloaded()) {
2287         OverloadCandidateSet OCS(R.getNameLoc(),
2288                                  OverloadCandidateSet::CSK_Normal);
2289         OverloadCandidateSet::iterator Best;
2290         for (NamedDecl *CD : Corrected) {
2291           if (FunctionTemplateDecl *FTD =
2292                    dyn_cast<FunctionTemplateDecl>(CD))
2293             AddTemplateOverloadCandidate(
2294                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2295                 Args, OCS);
2296           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2297             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2298               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2299                                    Args, OCS);
2300         }
2301         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2302         case OR_Success:
2303           ND = Best->FoundDecl;
2304           Corrected.setCorrectionDecl(ND);
2305           break;
2306         default:
2307           // FIXME: Arbitrarily pick the first declaration for the note.
2308           Corrected.setCorrectionDecl(ND);
2309           break;
2310         }
2311       }
2312       R.addDecl(ND);
2313       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2314         CXXRecordDecl *Record = nullptr;
2315         if (Corrected.getCorrectionSpecifier()) {
2316           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2317           Record = Ty->getAsCXXRecordDecl();
2318         }
2319         if (!Record)
2320           Record = cast<CXXRecordDecl>(
2321               ND->getDeclContext()->getRedeclContext());
2322         R.setNamingClass(Record);
2323       }
2324 
2325       auto *UnderlyingND = ND->getUnderlyingDecl();
2326       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2327                                isa<FunctionTemplateDecl>(UnderlyingND);
2328       // FIXME: If we ended up with a typo for a type name or
2329       // Objective-C class name, we're in trouble because the parser
2330       // is in the wrong place to recover. Suggest the typo
2331       // correction, but don't make it a fix-it since we're not going
2332       // to recover well anyway.
2333       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2334                                   getAsTypeTemplateDecl(UnderlyingND) ||
2335                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2336     } else {
2337       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2338       // because we aren't able to recover.
2339       AcceptableWithoutRecovery = true;
2340     }
2341 
2342     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2343       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2344                             ? diag::note_implicit_param_decl
2345                             : diag::note_previous_decl;
2346       if (SS.isEmpty())
2347         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2348                      PDiag(NoteID), AcceptableWithRecovery);
2349       else
2350         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2351                                   << Name << computeDeclContext(SS, false)
2352                                   << DroppedSpecifier << SS.getRange(),
2353                      PDiag(NoteID), AcceptableWithRecovery);
2354 
2355       // Tell the callee whether to try to recover.
2356       return !AcceptableWithRecovery;
2357     }
2358   }
2359   R.clear();
2360 
2361   // Emit a special diagnostic for failed member lookups.
2362   // FIXME: computing the declaration context might fail here (?)
2363   if (!SS.isEmpty()) {
2364     Diag(R.getNameLoc(), diag::err_no_member)
2365       << Name << computeDeclContext(SS, false)
2366       << SS.getRange();
2367     return true;
2368   }
2369 
2370   // Give up, we can't recover.
2371   Diag(R.getNameLoc(), diagnostic) << Name;
2372   return true;
2373 }
2374 
2375 /// In Microsoft mode, if we are inside a template class whose parent class has
2376 /// dependent base classes, and we can't resolve an unqualified identifier, then
2377 /// assume the identifier is a member of a dependent base class.  We can only
2378 /// recover successfully in static methods, instance methods, and other contexts
2379 /// where 'this' is available.  This doesn't precisely match MSVC's
2380 /// instantiation model, but it's close enough.
2381 static Expr *
2382 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2383                                DeclarationNameInfo &NameInfo,
2384                                SourceLocation TemplateKWLoc,
2385                                const TemplateArgumentListInfo *TemplateArgs) {
2386   // Only try to recover from lookup into dependent bases in static methods or
2387   // contexts where 'this' is available.
2388   QualType ThisType = S.getCurrentThisType();
2389   const CXXRecordDecl *RD = nullptr;
2390   if (!ThisType.isNull())
2391     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2392   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2393     RD = MD->getParent();
2394   if (!RD || !RD->hasAnyDependentBases())
2395     return nullptr;
2396 
2397   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2398   // is available, suggest inserting 'this->' as a fixit.
2399   SourceLocation Loc = NameInfo.getLoc();
2400   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2401   DB << NameInfo.getName() << RD;
2402 
2403   if (!ThisType.isNull()) {
2404     DB << FixItHint::CreateInsertion(Loc, "this->");
2405     return CXXDependentScopeMemberExpr::Create(
2406         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2407         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2408         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2409   }
2410 
2411   // Synthesize a fake NNS that points to the derived class.  This will
2412   // perform name lookup during template instantiation.
2413   CXXScopeSpec SS;
2414   auto *NNS =
2415       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2416   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2417   return DependentScopeDeclRefExpr::Create(
2418       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2419       TemplateArgs);
2420 }
2421 
2422 ExprResult
2423 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2424                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2425                         bool HasTrailingLParen, bool IsAddressOfOperand,
2426                         CorrectionCandidateCallback *CCC,
2427                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2428   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2429          "cannot be direct & operand and have a trailing lparen");
2430   if (SS.isInvalid())
2431     return ExprError();
2432 
2433   TemplateArgumentListInfo TemplateArgsBuffer;
2434 
2435   // Decompose the UnqualifiedId into the following data.
2436   DeclarationNameInfo NameInfo;
2437   const TemplateArgumentListInfo *TemplateArgs;
2438   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2439 
2440   DeclarationName Name = NameInfo.getName();
2441   IdentifierInfo *II = Name.getAsIdentifierInfo();
2442   SourceLocation NameLoc = NameInfo.getLoc();
2443 
2444   if (II && II->isEditorPlaceholder()) {
2445     // FIXME: When typed placeholders are supported we can create a typed
2446     // placeholder expression node.
2447     return ExprError();
2448   }
2449 
2450   // C++ [temp.dep.expr]p3:
2451   //   An id-expression is type-dependent if it contains:
2452   //     -- an identifier that was declared with a dependent type,
2453   //        (note: handled after lookup)
2454   //     -- a template-id that is dependent,
2455   //        (note: handled in BuildTemplateIdExpr)
2456   //     -- a conversion-function-id that specifies a dependent type,
2457   //     -- a nested-name-specifier that contains a class-name that
2458   //        names a dependent type.
2459   // Determine whether this is a member of an unknown specialization;
2460   // we need to handle these differently.
2461   bool DependentID = false;
2462   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2463       Name.getCXXNameType()->isDependentType()) {
2464     DependentID = true;
2465   } else if (SS.isSet()) {
2466     if (DeclContext *DC = computeDeclContext(SS, false)) {
2467       if (RequireCompleteDeclContext(SS, DC))
2468         return ExprError();
2469     } else {
2470       DependentID = true;
2471     }
2472   }
2473 
2474   if (DependentID)
2475     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2476                                       IsAddressOfOperand, TemplateArgs);
2477 
2478   // Perform the required lookup.
2479   LookupResult R(*this, NameInfo,
2480                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2481                      ? LookupObjCImplicitSelfParam
2482                      : LookupOrdinaryName);
2483   if (TemplateKWLoc.isValid() || TemplateArgs) {
2484     // Lookup the template name again to correctly establish the context in
2485     // which it was found. This is really unfortunate as we already did the
2486     // lookup to determine that it was a template name in the first place. If
2487     // this becomes a performance hit, we can work harder to preserve those
2488     // results until we get here but it's likely not worth it.
2489     bool MemberOfUnknownSpecialization;
2490     AssumedTemplateKind AssumedTemplate;
2491     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2492                            MemberOfUnknownSpecialization, TemplateKWLoc,
2493                            &AssumedTemplate))
2494       return ExprError();
2495 
2496     if (MemberOfUnknownSpecialization ||
2497         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2498       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2499                                         IsAddressOfOperand, TemplateArgs);
2500   } else {
2501     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2502     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2503 
2504     // If the result might be in a dependent base class, this is a dependent
2505     // id-expression.
2506     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2507       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2508                                         IsAddressOfOperand, TemplateArgs);
2509 
2510     // If this reference is in an Objective-C method, then we need to do
2511     // some special Objective-C lookup, too.
2512     if (IvarLookupFollowUp) {
2513       ExprResult E(LookupInObjCMethod(R, S, II, true));
2514       if (E.isInvalid())
2515         return ExprError();
2516 
2517       if (Expr *Ex = E.getAs<Expr>())
2518         return Ex;
2519     }
2520   }
2521 
2522   if (R.isAmbiguous())
2523     return ExprError();
2524 
2525   // This could be an implicitly declared function reference (legal in C90,
2526   // extension in C99, forbidden in C++).
2527   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2528     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2529     if (D) R.addDecl(D);
2530   }
2531 
2532   // Determine whether this name might be a candidate for
2533   // argument-dependent lookup.
2534   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2535 
2536   if (R.empty() && !ADL) {
2537     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2538       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2539                                                    TemplateKWLoc, TemplateArgs))
2540         return E;
2541     }
2542 
2543     // Don't diagnose an empty lookup for inline assembly.
2544     if (IsInlineAsmIdentifier)
2545       return ExprError();
2546 
2547     // If this name wasn't predeclared and if this is not a function
2548     // call, diagnose the problem.
2549     TypoExpr *TE = nullptr;
2550     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2551                                                        : nullptr);
2552     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2553     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2554            "Typo correction callback misconfigured");
2555     if (CCC) {
2556       // Make sure the callback knows what the typo being diagnosed is.
2557       CCC->setTypoName(II);
2558       if (SS.isValid())
2559         CCC->setTypoNNS(SS.getScopeRep());
2560     }
2561     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2562     // a template name, but we happen to have always already looked up the name
2563     // before we get here if it must be a template name.
2564     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2565                             None, &TE)) {
2566       if (TE && KeywordReplacement) {
2567         auto &State = getTypoExprState(TE);
2568         auto BestTC = State.Consumer->getNextCorrection();
2569         if (BestTC.isKeyword()) {
2570           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2571           if (State.DiagHandler)
2572             State.DiagHandler(BestTC);
2573           KeywordReplacement->startToken();
2574           KeywordReplacement->setKind(II->getTokenID());
2575           KeywordReplacement->setIdentifierInfo(II);
2576           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2577           // Clean up the state associated with the TypoExpr, since it has
2578           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2579           clearDelayedTypo(TE);
2580           // Signal that a correction to a keyword was performed by returning a
2581           // valid-but-null ExprResult.
2582           return (Expr*)nullptr;
2583         }
2584         State.Consumer->resetCorrectionStream();
2585       }
2586       return TE ? TE : ExprError();
2587     }
2588 
2589     assert(!R.empty() &&
2590            "DiagnoseEmptyLookup returned false but added no results");
2591 
2592     // If we found an Objective-C instance variable, let
2593     // LookupInObjCMethod build the appropriate expression to
2594     // reference the ivar.
2595     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2596       R.clear();
2597       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2598       // In a hopelessly buggy code, Objective-C instance variable
2599       // lookup fails and no expression will be built to reference it.
2600       if (!E.isInvalid() && !E.get())
2601         return ExprError();
2602       return E;
2603     }
2604   }
2605 
2606   // This is guaranteed from this point on.
2607   assert(!R.empty() || ADL);
2608 
2609   // Check whether this might be a C++ implicit instance member access.
2610   // C++ [class.mfct.non-static]p3:
2611   //   When an id-expression that is not part of a class member access
2612   //   syntax and not used to form a pointer to member is used in the
2613   //   body of a non-static member function of class X, if name lookup
2614   //   resolves the name in the id-expression to a non-static non-type
2615   //   member of some class C, the id-expression is transformed into a
2616   //   class member access expression using (*this) as the
2617   //   postfix-expression to the left of the . operator.
2618   //
2619   // But we don't actually need to do this for '&' operands if R
2620   // resolved to a function or overloaded function set, because the
2621   // expression is ill-formed if it actually works out to be a
2622   // non-static member function:
2623   //
2624   // C++ [expr.ref]p4:
2625   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2626   //   [t]he expression can be used only as the left-hand operand of a
2627   //   member function call.
2628   //
2629   // There are other safeguards against such uses, but it's important
2630   // to get this right here so that we don't end up making a
2631   // spuriously dependent expression if we're inside a dependent
2632   // instance method.
2633   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2634     bool MightBeImplicitMember;
2635     if (!IsAddressOfOperand)
2636       MightBeImplicitMember = true;
2637     else if (!SS.isEmpty())
2638       MightBeImplicitMember = false;
2639     else if (R.isOverloadedResult())
2640       MightBeImplicitMember = false;
2641     else if (R.isUnresolvableResult())
2642       MightBeImplicitMember = true;
2643     else
2644       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2645                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2646                               isa<MSPropertyDecl>(R.getFoundDecl());
2647 
2648     if (MightBeImplicitMember)
2649       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2650                                              R, TemplateArgs, S);
2651   }
2652 
2653   if (TemplateArgs || TemplateKWLoc.isValid()) {
2654 
2655     // In C++1y, if this is a variable template id, then check it
2656     // in BuildTemplateIdExpr().
2657     // The single lookup result must be a variable template declaration.
2658     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2659         Id.TemplateId->Kind == TNK_Var_template) {
2660       assert(R.getAsSingle<VarTemplateDecl>() &&
2661              "There should only be one declaration found.");
2662     }
2663 
2664     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2665   }
2666 
2667   return BuildDeclarationNameExpr(SS, R, ADL);
2668 }
2669 
2670 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2671 /// declaration name, generally during template instantiation.
2672 /// There's a large number of things which don't need to be done along
2673 /// this path.
2674 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2675     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2676     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2677   DeclContext *DC = computeDeclContext(SS, false);
2678   if (!DC)
2679     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2680                                      NameInfo, /*TemplateArgs=*/nullptr);
2681 
2682   if (RequireCompleteDeclContext(SS, DC))
2683     return ExprError();
2684 
2685   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2686   LookupQualifiedName(R, DC);
2687 
2688   if (R.isAmbiguous())
2689     return ExprError();
2690 
2691   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2692     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2693                                      NameInfo, /*TemplateArgs=*/nullptr);
2694 
2695   if (R.empty()) {
2696     // Don't diagnose problems with invalid record decl, the secondary no_member
2697     // diagnostic during template instantiation is likely bogus, e.g. if a class
2698     // is invalid because it's derived from an invalid base class, then missing
2699     // members were likely supposed to be inherited.
2700     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2701       if (CD->isInvalidDecl())
2702         return ExprError();
2703     Diag(NameInfo.getLoc(), diag::err_no_member)
2704       << NameInfo.getName() << DC << SS.getRange();
2705     return ExprError();
2706   }
2707 
2708   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2709     // Diagnose a missing typename if this resolved unambiguously to a type in
2710     // a dependent context.  If we can recover with a type, downgrade this to
2711     // a warning in Microsoft compatibility mode.
2712     unsigned DiagID = diag::err_typename_missing;
2713     if (RecoveryTSI && getLangOpts().MSVCCompat)
2714       DiagID = diag::ext_typename_missing;
2715     SourceLocation Loc = SS.getBeginLoc();
2716     auto D = Diag(Loc, DiagID);
2717     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2718       << SourceRange(Loc, NameInfo.getEndLoc());
2719 
2720     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2721     // context.
2722     if (!RecoveryTSI)
2723       return ExprError();
2724 
2725     // Only issue the fixit if we're prepared to recover.
2726     D << FixItHint::CreateInsertion(Loc, "typename ");
2727 
2728     // Recover by pretending this was an elaborated type.
2729     QualType Ty = Context.getTypeDeclType(TD);
2730     TypeLocBuilder TLB;
2731     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2732 
2733     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2734     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2735     QTL.setElaboratedKeywordLoc(SourceLocation());
2736     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2737 
2738     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2739 
2740     return ExprEmpty();
2741   }
2742 
2743   // Defend against this resolving to an implicit member access. We usually
2744   // won't get here if this might be a legitimate a class member (we end up in
2745   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2746   // a pointer-to-member or in an unevaluated context in C++11.
2747   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2748     return BuildPossibleImplicitMemberExpr(SS,
2749                                            /*TemplateKWLoc=*/SourceLocation(),
2750                                            R, /*TemplateArgs=*/nullptr, S);
2751 
2752   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2753 }
2754 
2755 /// The parser has read a name in, and Sema has detected that we're currently
2756 /// inside an ObjC method. Perform some additional checks and determine if we
2757 /// should form a reference to an ivar.
2758 ///
2759 /// Ideally, most of this would be done by lookup, but there's
2760 /// actually quite a lot of extra work involved.
2761 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2762                                         IdentifierInfo *II) {
2763   SourceLocation Loc = Lookup.getNameLoc();
2764   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2765 
2766   // Check for error condition which is already reported.
2767   if (!CurMethod)
2768     return DeclResult(true);
2769 
2770   // There are two cases to handle here.  1) scoped lookup could have failed,
2771   // in which case we should look for an ivar.  2) scoped lookup could have
2772   // found a decl, but that decl is outside the current instance method (i.e.
2773   // a global variable).  In these two cases, we do a lookup for an ivar with
2774   // this name, if the lookup sucedes, we replace it our current decl.
2775 
2776   // If we're in a class method, we don't normally want to look for
2777   // ivars.  But if we don't find anything else, and there's an
2778   // ivar, that's an error.
2779   bool IsClassMethod = CurMethod->isClassMethod();
2780 
2781   bool LookForIvars;
2782   if (Lookup.empty())
2783     LookForIvars = true;
2784   else if (IsClassMethod)
2785     LookForIvars = false;
2786   else
2787     LookForIvars = (Lookup.isSingleResult() &&
2788                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2789   ObjCInterfaceDecl *IFace = nullptr;
2790   if (LookForIvars) {
2791     IFace = CurMethod->getClassInterface();
2792     ObjCInterfaceDecl *ClassDeclared;
2793     ObjCIvarDecl *IV = nullptr;
2794     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2795       // Diagnose using an ivar in a class method.
2796       if (IsClassMethod) {
2797         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2798         return DeclResult(true);
2799       }
2800 
2801       // Diagnose the use of an ivar outside of the declaring class.
2802       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2803           !declaresSameEntity(ClassDeclared, IFace) &&
2804           !getLangOpts().DebuggerSupport)
2805         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2806 
2807       // Success.
2808       return IV;
2809     }
2810   } else if (CurMethod->isInstanceMethod()) {
2811     // We should warn if a local variable hides an ivar.
2812     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2813       ObjCInterfaceDecl *ClassDeclared;
2814       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2815         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2816             declaresSameEntity(IFace, ClassDeclared))
2817           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2818       }
2819     }
2820   } else if (Lookup.isSingleResult() &&
2821              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2822     // If accessing a stand-alone ivar in a class method, this is an error.
2823     if (const ObjCIvarDecl *IV =
2824             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2825       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2826       return DeclResult(true);
2827     }
2828   }
2829 
2830   // Didn't encounter an error, didn't find an ivar.
2831   return DeclResult(false);
2832 }
2833 
2834 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2835                                   ObjCIvarDecl *IV) {
2836   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2837   assert(CurMethod && CurMethod->isInstanceMethod() &&
2838          "should not reference ivar from this context");
2839 
2840   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2841   assert(IFace && "should not reference ivar from this context");
2842 
2843   // If we're referencing an invalid decl, just return this as a silent
2844   // error node.  The error diagnostic was already emitted on the decl.
2845   if (IV->isInvalidDecl())
2846     return ExprError();
2847 
2848   // Check if referencing a field with __attribute__((deprecated)).
2849   if (DiagnoseUseOfDecl(IV, Loc))
2850     return ExprError();
2851 
2852   // FIXME: This should use a new expr for a direct reference, don't
2853   // turn this into Self->ivar, just return a BareIVarExpr or something.
2854   IdentifierInfo &II = Context.Idents.get("self");
2855   UnqualifiedId SelfName;
2856   SelfName.setImplicitSelfParam(&II);
2857   CXXScopeSpec SelfScopeSpec;
2858   SourceLocation TemplateKWLoc;
2859   ExprResult SelfExpr =
2860       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2861                         /*HasTrailingLParen=*/false,
2862                         /*IsAddressOfOperand=*/false);
2863   if (SelfExpr.isInvalid())
2864     return ExprError();
2865 
2866   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2867   if (SelfExpr.isInvalid())
2868     return ExprError();
2869 
2870   MarkAnyDeclReferenced(Loc, IV, true);
2871 
2872   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2873   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2874       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2875     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2876 
2877   ObjCIvarRefExpr *Result = new (Context)
2878       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2879                       IV->getLocation(), SelfExpr.get(), true, true);
2880 
2881   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2882     if (!isUnevaluatedContext() &&
2883         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2884       getCurFunction()->recordUseOfWeak(Result);
2885   }
2886   if (getLangOpts().ObjCAutoRefCount)
2887     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2888       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2889 
2890   return Result;
2891 }
2892 
2893 /// The parser has read a name in, and Sema has detected that we're currently
2894 /// inside an ObjC method. Perform some additional checks and determine if we
2895 /// should form a reference to an ivar. If so, build an expression referencing
2896 /// that ivar.
2897 ExprResult
2898 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2899                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2900   // FIXME: Integrate this lookup step into LookupParsedName.
2901   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2902   if (Ivar.isInvalid())
2903     return ExprError();
2904   if (Ivar.isUsable())
2905     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2906                             cast<ObjCIvarDecl>(Ivar.get()));
2907 
2908   if (Lookup.empty() && II && AllowBuiltinCreation)
2909     LookupBuiltin(Lookup);
2910 
2911   // Sentinel value saying that we didn't do anything special.
2912   return ExprResult(false);
2913 }
2914 
2915 /// Cast a base object to a member's actual type.
2916 ///
2917 /// There are two relevant checks:
2918 ///
2919 /// C++ [class.access.base]p7:
2920 ///
2921 ///   If a class member access operator [...] is used to access a non-static
2922 ///   data member or non-static member function, the reference is ill-formed if
2923 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2924 ///   naming class of the right operand.
2925 ///
2926 /// C++ [expr.ref]p7:
2927 ///
2928 ///   If E2 is a non-static data member or a non-static member function, the
2929 ///   program is ill-formed if the class of which E2 is directly a member is an
2930 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2931 ///
2932 /// Note that the latter check does not consider access; the access of the
2933 /// "real" base class is checked as appropriate when checking the access of the
2934 /// member name.
2935 ExprResult
2936 Sema::PerformObjectMemberConversion(Expr *From,
2937                                     NestedNameSpecifier *Qualifier,
2938                                     NamedDecl *FoundDecl,
2939                                     NamedDecl *Member) {
2940   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2941   if (!RD)
2942     return From;
2943 
2944   QualType DestRecordType;
2945   QualType DestType;
2946   QualType FromRecordType;
2947   QualType FromType = From->getType();
2948   bool PointerConversions = false;
2949   if (isa<FieldDecl>(Member)) {
2950     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2951     auto FromPtrType = FromType->getAs<PointerType>();
2952     DestRecordType = Context.getAddrSpaceQualType(
2953         DestRecordType, FromPtrType
2954                             ? FromType->getPointeeType().getAddressSpace()
2955                             : FromType.getAddressSpace());
2956 
2957     if (FromPtrType) {
2958       DestType = Context.getPointerType(DestRecordType);
2959       FromRecordType = FromPtrType->getPointeeType();
2960       PointerConversions = true;
2961     } else {
2962       DestType = DestRecordType;
2963       FromRecordType = FromType;
2964     }
2965   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2966     if (Method->isStatic())
2967       return From;
2968 
2969     DestType = Method->getThisType();
2970     DestRecordType = DestType->getPointeeType();
2971 
2972     if (FromType->getAs<PointerType>()) {
2973       FromRecordType = FromType->getPointeeType();
2974       PointerConversions = true;
2975     } else {
2976       FromRecordType = FromType;
2977       DestType = DestRecordType;
2978     }
2979 
2980     LangAS FromAS = FromRecordType.getAddressSpace();
2981     LangAS DestAS = DestRecordType.getAddressSpace();
2982     if (FromAS != DestAS) {
2983       QualType FromRecordTypeWithoutAS =
2984           Context.removeAddrSpaceQualType(FromRecordType);
2985       QualType FromTypeWithDestAS =
2986           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2987       if (PointerConversions)
2988         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2989       From = ImpCastExprToType(From, FromTypeWithDestAS,
2990                                CK_AddressSpaceConversion, From->getValueKind())
2991                  .get();
2992     }
2993   } else {
2994     // No conversion necessary.
2995     return From;
2996   }
2997 
2998   if (DestType->isDependentType() || FromType->isDependentType())
2999     return From;
3000 
3001   // If the unqualified types are the same, no conversion is necessary.
3002   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3003     return From;
3004 
3005   SourceRange FromRange = From->getSourceRange();
3006   SourceLocation FromLoc = FromRange.getBegin();
3007 
3008   ExprValueKind VK = From->getValueKind();
3009 
3010   // C++ [class.member.lookup]p8:
3011   //   [...] Ambiguities can often be resolved by qualifying a name with its
3012   //   class name.
3013   //
3014   // If the member was a qualified name and the qualified referred to a
3015   // specific base subobject type, we'll cast to that intermediate type
3016   // first and then to the object in which the member is declared. That allows
3017   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3018   //
3019   //   class Base { public: int x; };
3020   //   class Derived1 : public Base { };
3021   //   class Derived2 : public Base { };
3022   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3023   //
3024   //   void VeryDerived::f() {
3025   //     x = 17; // error: ambiguous base subobjects
3026   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3027   //   }
3028   if (Qualifier && Qualifier->getAsType()) {
3029     QualType QType = QualType(Qualifier->getAsType(), 0);
3030     assert(QType->isRecordType() && "lookup done with non-record type");
3031 
3032     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3033 
3034     // In C++98, the qualifier type doesn't actually have to be a base
3035     // type of the object type, in which case we just ignore it.
3036     // Otherwise build the appropriate casts.
3037     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3038       CXXCastPath BasePath;
3039       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3040                                        FromLoc, FromRange, &BasePath))
3041         return ExprError();
3042 
3043       if (PointerConversions)
3044         QType = Context.getPointerType(QType);
3045       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3046                                VK, &BasePath).get();
3047 
3048       FromType = QType;
3049       FromRecordType = QRecordType;
3050 
3051       // If the qualifier type was the same as the destination type,
3052       // we're done.
3053       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3054         return From;
3055     }
3056   }
3057 
3058   CXXCastPath BasePath;
3059   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3060                                    FromLoc, FromRange, &BasePath,
3061                                    /*IgnoreAccess=*/true))
3062     return ExprError();
3063 
3064   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3065                            VK, &BasePath);
3066 }
3067 
3068 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3069                                       const LookupResult &R,
3070                                       bool HasTrailingLParen) {
3071   // Only when used directly as the postfix-expression of a call.
3072   if (!HasTrailingLParen)
3073     return false;
3074 
3075   // Never if a scope specifier was provided.
3076   if (SS.isSet())
3077     return false;
3078 
3079   // Only in C++ or ObjC++.
3080   if (!getLangOpts().CPlusPlus)
3081     return false;
3082 
3083   // Turn off ADL when we find certain kinds of declarations during
3084   // normal lookup:
3085   for (NamedDecl *D : R) {
3086     // C++0x [basic.lookup.argdep]p3:
3087     //     -- a declaration of a class member
3088     // Since using decls preserve this property, we check this on the
3089     // original decl.
3090     if (D->isCXXClassMember())
3091       return false;
3092 
3093     // C++0x [basic.lookup.argdep]p3:
3094     //     -- a block-scope function declaration that is not a
3095     //        using-declaration
3096     // NOTE: we also trigger this for function templates (in fact, we
3097     // don't check the decl type at all, since all other decl types
3098     // turn off ADL anyway).
3099     if (isa<UsingShadowDecl>(D))
3100       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3101     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3102       return false;
3103 
3104     // C++0x [basic.lookup.argdep]p3:
3105     //     -- a declaration that is neither a function or a function
3106     //        template
3107     // And also for builtin functions.
3108     if (isa<FunctionDecl>(D)) {
3109       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3110 
3111       // But also builtin functions.
3112       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3113         return false;
3114     } else if (!isa<FunctionTemplateDecl>(D))
3115       return false;
3116   }
3117 
3118   return true;
3119 }
3120 
3121 
3122 /// Diagnoses obvious problems with the use of the given declaration
3123 /// as an expression.  This is only actually called for lookups that
3124 /// were not overloaded, and it doesn't promise that the declaration
3125 /// will in fact be used.
3126 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3127   if (D->isInvalidDecl())
3128     return true;
3129 
3130   if (isa<TypedefNameDecl>(D)) {
3131     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3132     return true;
3133   }
3134 
3135   if (isa<ObjCInterfaceDecl>(D)) {
3136     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3137     return true;
3138   }
3139 
3140   if (isa<NamespaceDecl>(D)) {
3141     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3142     return true;
3143   }
3144 
3145   return false;
3146 }
3147 
3148 // Certain multiversion types should be treated as overloaded even when there is
3149 // only one result.
3150 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3151   assert(R.isSingleResult() && "Expected only a single result");
3152   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3153   return FD &&
3154          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3155 }
3156 
3157 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3158                                           LookupResult &R, bool NeedsADL,
3159                                           bool AcceptInvalidDecl) {
3160   // If this is a single, fully-resolved result and we don't need ADL,
3161   // just build an ordinary singleton decl ref.
3162   if (!NeedsADL && R.isSingleResult() &&
3163       !R.getAsSingle<FunctionTemplateDecl>() &&
3164       !ShouldLookupResultBeMultiVersionOverload(R))
3165     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3166                                     R.getRepresentativeDecl(), nullptr,
3167                                     AcceptInvalidDecl);
3168 
3169   // We only need to check the declaration if there's exactly one
3170   // result, because in the overloaded case the results can only be
3171   // functions and function templates.
3172   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3173       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3174     return ExprError();
3175 
3176   // Otherwise, just build an unresolved lookup expression.  Suppress
3177   // any lookup-related diagnostics; we'll hash these out later, when
3178   // we've picked a target.
3179   R.suppressDiagnostics();
3180 
3181   UnresolvedLookupExpr *ULE
3182     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3183                                    SS.getWithLocInContext(Context),
3184                                    R.getLookupNameInfo(),
3185                                    NeedsADL, R.isOverloadedResult(),
3186                                    R.begin(), R.end());
3187 
3188   return ULE;
3189 }
3190 
3191 static void
3192 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3193                                    ValueDecl *var, DeclContext *DC);
3194 
3195 /// Complete semantic analysis for a reference to the given declaration.
3196 ExprResult Sema::BuildDeclarationNameExpr(
3197     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3198     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3199     bool AcceptInvalidDecl) {
3200   assert(D && "Cannot refer to a NULL declaration");
3201   assert(!isa<FunctionTemplateDecl>(D) &&
3202          "Cannot refer unambiguously to a function template");
3203 
3204   SourceLocation Loc = NameInfo.getLoc();
3205   if (CheckDeclInExpr(*this, Loc, D))
3206     return ExprError();
3207 
3208   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3209     // Specifically diagnose references to class templates that are missing
3210     // a template argument list.
3211     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3212     return ExprError();
3213   }
3214 
3215   // Make sure that we're referring to a value.
3216   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3217   if (!VD) {
3218     Diag(Loc, diag::err_ref_non_value)
3219       << D << SS.getRange();
3220     Diag(D->getLocation(), diag::note_declared_at);
3221     return ExprError();
3222   }
3223 
3224   // Check whether this declaration can be used. Note that we suppress
3225   // this check when we're going to perform argument-dependent lookup
3226   // on this function name, because this might not be the function
3227   // that overload resolution actually selects.
3228   if (DiagnoseUseOfDecl(VD, Loc))
3229     return ExprError();
3230 
3231   // Only create DeclRefExpr's for valid Decl's.
3232   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3233     return ExprError();
3234 
3235   // Handle members of anonymous structs and unions.  If we got here,
3236   // and the reference is to a class member indirect field, then this
3237   // must be the subject of a pointer-to-member expression.
3238   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3239     if (!indirectField->isCXXClassMember())
3240       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3241                                                       indirectField);
3242 
3243   {
3244     QualType type = VD->getType();
3245     if (type.isNull())
3246       return ExprError();
3247     ExprValueKind valueKind = VK_RValue;
3248 
3249     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3250     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3251     // is expanded by some outer '...' in the context of the use.
3252     type = type.getNonPackExpansionType();
3253 
3254     switch (D->getKind()) {
3255     // Ignore all the non-ValueDecl kinds.
3256 #define ABSTRACT_DECL(kind)
3257 #define VALUE(type, base)
3258 #define DECL(type, base) \
3259     case Decl::type:
3260 #include "clang/AST/DeclNodes.inc"
3261       llvm_unreachable("invalid value decl kind");
3262 
3263     // These shouldn't make it here.
3264     case Decl::ObjCAtDefsField:
3265       llvm_unreachable("forming non-member reference to ivar?");
3266 
3267     // Enum constants are always r-values and never references.
3268     // Unresolved using declarations are dependent.
3269     case Decl::EnumConstant:
3270     case Decl::UnresolvedUsingValue:
3271     case Decl::OMPDeclareReduction:
3272     case Decl::OMPDeclareMapper:
3273       valueKind = VK_RValue;
3274       break;
3275 
3276     // Fields and indirect fields that got here must be for
3277     // pointer-to-member expressions; we just call them l-values for
3278     // internal consistency, because this subexpression doesn't really
3279     // exist in the high-level semantics.
3280     case Decl::Field:
3281     case Decl::IndirectField:
3282     case Decl::ObjCIvar:
3283       assert(getLangOpts().CPlusPlus &&
3284              "building reference to field in C?");
3285 
3286       // These can't have reference type in well-formed programs, but
3287       // for internal consistency we do this anyway.
3288       type = type.getNonReferenceType();
3289       valueKind = VK_LValue;
3290       break;
3291 
3292     // Non-type template parameters are either l-values or r-values
3293     // depending on the type.
3294     case Decl::NonTypeTemplateParm: {
3295       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3296         type = reftype->getPointeeType();
3297         valueKind = VK_LValue; // even if the parameter is an r-value reference
3298         break;
3299       }
3300 
3301       // [expr.prim.id.unqual]p2:
3302       //   If the entity is a template parameter object for a template
3303       //   parameter of type T, the type of the expression is const T.
3304       //   [...] The expression is an lvalue if the entity is a [...] template
3305       //   parameter object.
3306       if (type->isRecordType()) {
3307         type = type.getUnqualifiedType().withConst();
3308         valueKind = VK_LValue;
3309         break;
3310       }
3311 
3312       // For non-references, we need to strip qualifiers just in case
3313       // the template parameter was declared as 'const int' or whatever.
3314       valueKind = VK_RValue;
3315       type = type.getUnqualifiedType();
3316       break;
3317     }
3318 
3319     case Decl::Var:
3320     case Decl::VarTemplateSpecialization:
3321     case Decl::VarTemplatePartialSpecialization:
3322     case Decl::Decomposition:
3323     case Decl::OMPCapturedExpr:
3324       // In C, "extern void blah;" is valid and is an r-value.
3325       if (!getLangOpts().CPlusPlus &&
3326           !type.hasQualifiers() &&
3327           type->isVoidType()) {
3328         valueKind = VK_RValue;
3329         break;
3330       }
3331       LLVM_FALLTHROUGH;
3332 
3333     case Decl::ImplicitParam:
3334     case Decl::ParmVar: {
3335       // These are always l-values.
3336       valueKind = VK_LValue;
3337       type = type.getNonReferenceType();
3338 
3339       // FIXME: Does the addition of const really only apply in
3340       // potentially-evaluated contexts? Since the variable isn't actually
3341       // captured in an unevaluated context, it seems that the answer is no.
3342       if (!isUnevaluatedContext()) {
3343         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3344         if (!CapturedType.isNull())
3345           type = CapturedType;
3346       }
3347 
3348       break;
3349     }
3350 
3351     case Decl::Binding: {
3352       // These are always lvalues.
3353       valueKind = VK_LValue;
3354       type = type.getNonReferenceType();
3355       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3356       // decides how that's supposed to work.
3357       auto *BD = cast<BindingDecl>(VD);
3358       if (BD->getDeclContext() != CurContext) {
3359         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3360         if (DD && DD->hasLocalStorage())
3361           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3362       }
3363       break;
3364     }
3365 
3366     case Decl::Function: {
3367       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3368         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3369           type = Context.BuiltinFnTy;
3370           valueKind = VK_RValue;
3371           break;
3372         }
3373       }
3374 
3375       const FunctionType *fty = type->castAs<FunctionType>();
3376 
3377       // If we're referring to a function with an __unknown_anytype
3378       // result type, make the entire expression __unknown_anytype.
3379       if (fty->getReturnType() == Context.UnknownAnyTy) {
3380         type = Context.UnknownAnyTy;
3381         valueKind = VK_RValue;
3382         break;
3383       }
3384 
3385       // Functions are l-values in C++.
3386       if (getLangOpts().CPlusPlus) {
3387         valueKind = VK_LValue;
3388         break;
3389       }
3390 
3391       // C99 DR 316 says that, if a function type comes from a
3392       // function definition (without a prototype), that type is only
3393       // used for checking compatibility. Therefore, when referencing
3394       // the function, we pretend that we don't have the full function
3395       // type.
3396       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3397           isa<FunctionProtoType>(fty))
3398         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3399                                               fty->getExtInfo());
3400 
3401       // Functions are r-values in C.
3402       valueKind = VK_RValue;
3403       break;
3404     }
3405 
3406     case Decl::CXXDeductionGuide:
3407       llvm_unreachable("building reference to deduction guide");
3408 
3409     case Decl::MSProperty:
3410     case Decl::MSGuid:
3411     case Decl::TemplateParamObject:
3412       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3413       // capture in OpenMP, or duplicated between host and device?
3414       valueKind = VK_LValue;
3415       break;
3416 
3417     case Decl::CXXMethod:
3418       // If we're referring to a method with an __unknown_anytype
3419       // result type, make the entire expression __unknown_anytype.
3420       // This should only be possible with a type written directly.
3421       if (const FunctionProtoType *proto
3422             = dyn_cast<FunctionProtoType>(VD->getType()))
3423         if (proto->getReturnType() == Context.UnknownAnyTy) {
3424           type = Context.UnknownAnyTy;
3425           valueKind = VK_RValue;
3426           break;
3427         }
3428 
3429       // C++ methods are l-values if static, r-values if non-static.
3430       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3431         valueKind = VK_LValue;
3432         break;
3433       }
3434       LLVM_FALLTHROUGH;
3435 
3436     case Decl::CXXConversion:
3437     case Decl::CXXDestructor:
3438     case Decl::CXXConstructor:
3439       valueKind = VK_RValue;
3440       break;
3441     }
3442 
3443     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3444                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3445                             TemplateArgs);
3446   }
3447 }
3448 
3449 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3450                                     SmallString<32> &Target) {
3451   Target.resize(CharByteWidth * (Source.size() + 1));
3452   char *ResultPtr = &Target[0];
3453   const llvm::UTF8 *ErrorPtr;
3454   bool success =
3455       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3456   (void)success;
3457   assert(success);
3458   Target.resize(ResultPtr - &Target[0]);
3459 }
3460 
3461 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3462                                      PredefinedExpr::IdentKind IK) {
3463   // Pick the current block, lambda, captured statement or function.
3464   Decl *currentDecl = nullptr;
3465   if (const BlockScopeInfo *BSI = getCurBlock())
3466     currentDecl = BSI->TheDecl;
3467   else if (const LambdaScopeInfo *LSI = getCurLambda())
3468     currentDecl = LSI->CallOperator;
3469   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3470     currentDecl = CSI->TheCapturedDecl;
3471   else
3472     currentDecl = getCurFunctionOrMethodDecl();
3473 
3474   if (!currentDecl) {
3475     Diag(Loc, diag::ext_predef_outside_function);
3476     currentDecl = Context.getTranslationUnitDecl();
3477   }
3478 
3479   QualType ResTy;
3480   StringLiteral *SL = nullptr;
3481   if (cast<DeclContext>(currentDecl)->isDependentContext())
3482     ResTy = Context.DependentTy;
3483   else {
3484     // Pre-defined identifiers are of type char[x], where x is the length of
3485     // the string.
3486     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3487     unsigned Length = Str.length();
3488 
3489     llvm::APInt LengthI(32, Length + 1);
3490     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3491       ResTy =
3492           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3493       SmallString<32> RawChars;
3494       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3495                               Str, RawChars);
3496       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3497                                            ArrayType::Normal,
3498                                            /*IndexTypeQuals*/ 0);
3499       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3500                                  /*Pascal*/ false, ResTy, Loc);
3501     } else {
3502       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3503       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3504                                            ArrayType::Normal,
3505                                            /*IndexTypeQuals*/ 0);
3506       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3507                                  /*Pascal*/ false, ResTy, Loc);
3508     }
3509   }
3510 
3511   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3512 }
3513 
3514 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3515   PredefinedExpr::IdentKind IK;
3516 
3517   switch (Kind) {
3518   default: llvm_unreachable("Unknown simple primary expr!");
3519   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3520   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3521   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3522   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3523   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3524   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3525   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3526   }
3527 
3528   return BuildPredefinedExpr(Loc, IK);
3529 }
3530 
3531 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3532   SmallString<16> CharBuffer;
3533   bool Invalid = false;
3534   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3535   if (Invalid)
3536     return ExprError();
3537 
3538   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3539                             PP, Tok.getKind());
3540   if (Literal.hadError())
3541     return ExprError();
3542 
3543   QualType Ty;
3544   if (Literal.isWide())
3545     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3546   else if (Literal.isUTF8() && getLangOpts().Char8)
3547     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3548   else if (Literal.isUTF16())
3549     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3550   else if (Literal.isUTF32())
3551     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3552   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3553     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3554   else
3555     Ty = Context.CharTy;  // 'x' -> char in C++
3556 
3557   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3558   if (Literal.isWide())
3559     Kind = CharacterLiteral::Wide;
3560   else if (Literal.isUTF16())
3561     Kind = CharacterLiteral::UTF16;
3562   else if (Literal.isUTF32())
3563     Kind = CharacterLiteral::UTF32;
3564   else if (Literal.isUTF8())
3565     Kind = CharacterLiteral::UTF8;
3566 
3567   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3568                                              Tok.getLocation());
3569 
3570   if (Literal.getUDSuffix().empty())
3571     return Lit;
3572 
3573   // We're building a user-defined literal.
3574   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3575   SourceLocation UDSuffixLoc =
3576     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3577 
3578   // Make sure we're allowed user-defined literals here.
3579   if (!UDLScope)
3580     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3581 
3582   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3583   //   operator "" X (ch)
3584   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3585                                         Lit, Tok.getLocation());
3586 }
3587 
3588 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3589   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3590   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3591                                 Context.IntTy, Loc);
3592 }
3593 
3594 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3595                                   QualType Ty, SourceLocation Loc) {
3596   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3597 
3598   using llvm::APFloat;
3599   APFloat Val(Format);
3600 
3601   APFloat::opStatus result = Literal.GetFloatValue(Val);
3602 
3603   // Overflow is always an error, but underflow is only an error if
3604   // we underflowed to zero (APFloat reports denormals as underflow).
3605   if ((result & APFloat::opOverflow) ||
3606       ((result & APFloat::opUnderflow) && Val.isZero())) {
3607     unsigned diagnostic;
3608     SmallString<20> buffer;
3609     if (result & APFloat::opOverflow) {
3610       diagnostic = diag::warn_float_overflow;
3611       APFloat::getLargest(Format).toString(buffer);
3612     } else {
3613       diagnostic = diag::warn_float_underflow;
3614       APFloat::getSmallest(Format).toString(buffer);
3615     }
3616 
3617     S.Diag(Loc, diagnostic)
3618       << Ty
3619       << StringRef(buffer.data(), buffer.size());
3620   }
3621 
3622   bool isExact = (result == APFloat::opOK);
3623   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3624 }
3625 
3626 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3627   assert(E && "Invalid expression");
3628 
3629   if (E->isValueDependent())
3630     return false;
3631 
3632   QualType QT = E->getType();
3633   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3634     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3635     return true;
3636   }
3637 
3638   llvm::APSInt ValueAPS;
3639   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3640 
3641   if (R.isInvalid())
3642     return true;
3643 
3644   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3645   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3646     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3647         << ValueAPS.toString(10) << ValueIsPositive;
3648     return true;
3649   }
3650 
3651   return false;
3652 }
3653 
3654 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3655   // Fast path for a single digit (which is quite common).  A single digit
3656   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3657   if (Tok.getLength() == 1) {
3658     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3659     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3660   }
3661 
3662   SmallString<128> SpellingBuffer;
3663   // NumericLiteralParser wants to overread by one character.  Add padding to
3664   // the buffer in case the token is copied to the buffer.  If getSpelling()
3665   // returns a StringRef to the memory buffer, it should have a null char at
3666   // the EOF, so it is also safe.
3667   SpellingBuffer.resize(Tok.getLength() + 1);
3668 
3669   // Get the spelling of the token, which eliminates trigraphs, etc.
3670   bool Invalid = false;
3671   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3672   if (Invalid)
3673     return ExprError();
3674 
3675   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3676                                PP.getSourceManager(), PP.getLangOpts(),
3677                                PP.getTargetInfo(), PP.getDiagnostics());
3678   if (Literal.hadError)
3679     return ExprError();
3680 
3681   if (Literal.hasUDSuffix()) {
3682     // We're building a user-defined literal.
3683     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3684     SourceLocation UDSuffixLoc =
3685       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3686 
3687     // Make sure we're allowed user-defined literals here.
3688     if (!UDLScope)
3689       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3690 
3691     QualType CookedTy;
3692     if (Literal.isFloatingLiteral()) {
3693       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3694       // long double, the literal is treated as a call of the form
3695       //   operator "" X (f L)
3696       CookedTy = Context.LongDoubleTy;
3697     } else {
3698       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3699       // unsigned long long, the literal is treated as a call of the form
3700       //   operator "" X (n ULL)
3701       CookedTy = Context.UnsignedLongLongTy;
3702     }
3703 
3704     DeclarationName OpName =
3705       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3706     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3707     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3708 
3709     SourceLocation TokLoc = Tok.getLocation();
3710 
3711     // Perform literal operator lookup to determine if we're building a raw
3712     // literal or a cooked one.
3713     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3714     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3715                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3716                                   /*AllowStringTemplatePack*/ false,
3717                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3718     case LOLR_ErrorNoDiagnostic:
3719       // Lookup failure for imaginary constants isn't fatal, there's still the
3720       // GNU extension producing _Complex types.
3721       break;
3722     case LOLR_Error:
3723       return ExprError();
3724     case LOLR_Cooked: {
3725       Expr *Lit;
3726       if (Literal.isFloatingLiteral()) {
3727         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3728       } else {
3729         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3730         if (Literal.GetIntegerValue(ResultVal))
3731           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3732               << /* Unsigned */ 1;
3733         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3734                                      Tok.getLocation());
3735       }
3736       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3737     }
3738 
3739     case LOLR_Raw: {
3740       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3741       // literal is treated as a call of the form
3742       //   operator "" X ("n")
3743       unsigned Length = Literal.getUDSuffixOffset();
3744       QualType StrTy = Context.getConstantArrayType(
3745           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3746           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3747       Expr *Lit = StringLiteral::Create(
3748           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3749           /*Pascal*/false, StrTy, &TokLoc, 1);
3750       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3751     }
3752 
3753     case LOLR_Template: {
3754       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3755       // template), L is treated as a call fo the form
3756       //   operator "" X <'c1', 'c2', ... 'ck'>()
3757       // where n is the source character sequence c1 c2 ... ck.
3758       TemplateArgumentListInfo ExplicitArgs;
3759       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3760       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3761       llvm::APSInt Value(CharBits, CharIsUnsigned);
3762       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3763         Value = TokSpelling[I];
3764         TemplateArgument Arg(Context, Value, Context.CharTy);
3765         TemplateArgumentLocInfo ArgInfo;
3766         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3767       }
3768       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3769                                       &ExplicitArgs);
3770     }
3771     case LOLR_StringTemplatePack:
3772       llvm_unreachable("unexpected literal operator lookup result");
3773     }
3774   }
3775 
3776   Expr *Res;
3777 
3778   if (Literal.isFixedPointLiteral()) {
3779     QualType Ty;
3780 
3781     if (Literal.isAccum) {
3782       if (Literal.isHalf) {
3783         Ty = Context.ShortAccumTy;
3784       } else if (Literal.isLong) {
3785         Ty = Context.LongAccumTy;
3786       } else {
3787         Ty = Context.AccumTy;
3788       }
3789     } else if (Literal.isFract) {
3790       if (Literal.isHalf) {
3791         Ty = Context.ShortFractTy;
3792       } else if (Literal.isLong) {
3793         Ty = Context.LongFractTy;
3794       } else {
3795         Ty = Context.FractTy;
3796       }
3797     }
3798 
3799     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3800 
3801     bool isSigned = !Literal.isUnsigned;
3802     unsigned scale = Context.getFixedPointScale(Ty);
3803     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3804 
3805     llvm::APInt Val(bit_width, 0, isSigned);
3806     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3807     bool ValIsZero = Val.isNullValue() && !Overflowed;
3808 
3809     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3810     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3811       // Clause 6.4.4 - The value of a constant shall be in the range of
3812       // representable values for its type, with exception for constants of a
3813       // fract type with a value of exactly 1; such a constant shall denote
3814       // the maximal value for the type.
3815       --Val;
3816     else if (Val.ugt(MaxVal) || Overflowed)
3817       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3818 
3819     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3820                                               Tok.getLocation(), scale);
3821   } else if (Literal.isFloatingLiteral()) {
3822     QualType Ty;
3823     if (Literal.isHalf){
3824       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3825         Ty = Context.HalfTy;
3826       else {
3827         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3828         return ExprError();
3829       }
3830     } else if (Literal.isFloat)
3831       Ty = Context.FloatTy;
3832     else if (Literal.isLong)
3833       Ty = Context.LongDoubleTy;
3834     else if (Literal.isFloat16)
3835       Ty = Context.Float16Ty;
3836     else if (Literal.isFloat128)
3837       Ty = Context.Float128Ty;
3838     else
3839       Ty = Context.DoubleTy;
3840 
3841     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3842 
3843     if (Ty == Context.DoubleTy) {
3844       if (getLangOpts().SinglePrecisionConstants) {
3845         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3846           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3847         }
3848       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3849                                              "cl_khr_fp64", getLangOpts())) {
3850         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3851         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3852         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3853       }
3854     }
3855   } else if (!Literal.isIntegerLiteral()) {
3856     return ExprError();
3857   } else {
3858     QualType Ty;
3859 
3860     // 'long long' is a C99 or C++11 feature.
3861     if (!getLangOpts().C99 && Literal.isLongLong) {
3862       if (getLangOpts().CPlusPlus)
3863         Diag(Tok.getLocation(),
3864              getLangOpts().CPlusPlus11 ?
3865              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3866       else
3867         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3868     }
3869 
3870     // 'z/uz' literals are a C++2b feature.
3871     if (Literal.isSizeT)
3872       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3873                                   ? getLangOpts().CPlusPlus2b
3874                                         ? diag::warn_cxx20_compat_size_t_suffix
3875                                         : diag::ext_cxx2b_size_t_suffix
3876                                   : diag::err_cxx2b_size_t_suffix);
3877 
3878     // Get the value in the widest-possible width.
3879     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3880     llvm::APInt ResultVal(MaxWidth, 0);
3881 
3882     if (Literal.GetIntegerValue(ResultVal)) {
3883       // If this value didn't fit into uintmax_t, error and force to ull.
3884       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3885           << /* Unsigned */ 1;
3886       Ty = Context.UnsignedLongLongTy;
3887       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3888              "long long is not intmax_t?");
3889     } else {
3890       // If this value fits into a ULL, try to figure out what else it fits into
3891       // according to the rules of C99 6.4.4.1p5.
3892 
3893       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3894       // be an unsigned int.
3895       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3896 
3897       // Check from smallest to largest, picking the smallest type we can.
3898       unsigned Width = 0;
3899 
3900       // Microsoft specific integer suffixes are explicitly sized.
3901       if (Literal.MicrosoftInteger) {
3902         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3903           Width = 8;
3904           Ty = Context.CharTy;
3905         } else {
3906           Width = Literal.MicrosoftInteger;
3907           Ty = Context.getIntTypeForBitwidth(Width,
3908                                              /*Signed=*/!Literal.isUnsigned);
3909         }
3910       }
3911 
3912       // Check C++2b size_t literals.
3913       if (Literal.isSizeT) {
3914         assert(!Literal.MicrosoftInteger &&
3915                "size_t literals can't be Microsoft literals");
3916         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3917             Context.getTargetInfo().getSizeType());
3918 
3919         // Does it fit in size_t?
3920         if (ResultVal.isIntN(SizeTSize)) {
3921           // Does it fit in ssize_t?
3922           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3923             Ty = Context.getSignedSizeType();
3924           else if (AllowUnsigned)
3925             Ty = Context.getSizeType();
3926           Width = SizeTSize;
3927         }
3928       }
3929 
3930       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3931           !Literal.isSizeT) {
3932         // Are int/unsigned possibilities?
3933         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3934 
3935         // Does it fit in a unsigned int?
3936         if (ResultVal.isIntN(IntSize)) {
3937           // Does it fit in a signed int?
3938           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3939             Ty = Context.IntTy;
3940           else if (AllowUnsigned)
3941             Ty = Context.UnsignedIntTy;
3942           Width = IntSize;
3943         }
3944       }
3945 
3946       // Are long/unsigned long possibilities?
3947       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3948         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3949 
3950         // Does it fit in a unsigned long?
3951         if (ResultVal.isIntN(LongSize)) {
3952           // Does it fit in a signed long?
3953           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3954             Ty = Context.LongTy;
3955           else if (AllowUnsigned)
3956             Ty = Context.UnsignedLongTy;
3957           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3958           // is compatible.
3959           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3960             const unsigned LongLongSize =
3961                 Context.getTargetInfo().getLongLongWidth();
3962             Diag(Tok.getLocation(),
3963                  getLangOpts().CPlusPlus
3964                      ? Literal.isLong
3965                            ? diag::warn_old_implicitly_unsigned_long_cxx
3966                            : /*C++98 UB*/ diag::
3967                                  ext_old_implicitly_unsigned_long_cxx
3968                      : diag::warn_old_implicitly_unsigned_long)
3969                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3970                                             : /*will be ill-formed*/ 1);
3971             Ty = Context.UnsignedLongTy;
3972           }
3973           Width = LongSize;
3974         }
3975       }
3976 
3977       // Check long long if needed.
3978       if (Ty.isNull() && !Literal.isSizeT) {
3979         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3980 
3981         // Does it fit in a unsigned long long?
3982         if (ResultVal.isIntN(LongLongSize)) {
3983           // Does it fit in a signed long long?
3984           // To be compatible with MSVC, hex integer literals ending with the
3985           // LL or i64 suffix are always signed in Microsoft mode.
3986           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3987               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3988             Ty = Context.LongLongTy;
3989           else if (AllowUnsigned)
3990             Ty = Context.UnsignedLongLongTy;
3991           Width = LongLongSize;
3992         }
3993       }
3994 
3995       // If we still couldn't decide a type, we either have 'size_t' literal
3996       // that is out of range, or a decimal literal that does not fit in a
3997       // signed long long and has no U suffix.
3998       if (Ty.isNull()) {
3999         if (Literal.isSizeT)
4000           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4001               << Literal.isUnsigned;
4002         else
4003           Diag(Tok.getLocation(),
4004                diag::ext_integer_literal_too_large_for_signed);
4005         Ty = Context.UnsignedLongLongTy;
4006         Width = Context.getTargetInfo().getLongLongWidth();
4007       }
4008 
4009       if (ResultVal.getBitWidth() != Width)
4010         ResultVal = ResultVal.trunc(Width);
4011     }
4012     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4013   }
4014 
4015   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4016   if (Literal.isImaginary) {
4017     Res = new (Context) ImaginaryLiteral(Res,
4018                                         Context.getComplexType(Res->getType()));
4019 
4020     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4021   }
4022   return Res;
4023 }
4024 
4025 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4026   assert(E && "ActOnParenExpr() missing expr");
4027   return new (Context) ParenExpr(L, R, E);
4028 }
4029 
4030 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4031                                          SourceLocation Loc,
4032                                          SourceRange ArgRange) {
4033   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4034   // scalar or vector data type argument..."
4035   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4036   // type (C99 6.2.5p18) or void.
4037   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4038     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4039       << T << ArgRange;
4040     return true;
4041   }
4042 
4043   assert((T->isVoidType() || !T->isIncompleteType()) &&
4044          "Scalar types should always be complete");
4045   return false;
4046 }
4047 
4048 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4049                                            SourceLocation Loc,
4050                                            SourceRange ArgRange,
4051                                            UnaryExprOrTypeTrait TraitKind) {
4052   // Invalid types must be hard errors for SFINAE in C++.
4053   if (S.LangOpts.CPlusPlus)
4054     return true;
4055 
4056   // C99 6.5.3.4p1:
4057   if (T->isFunctionType() &&
4058       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4059        TraitKind == UETT_PreferredAlignOf)) {
4060     // sizeof(function)/alignof(function) is allowed as an extension.
4061     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4062         << getTraitSpelling(TraitKind) << ArgRange;
4063     return false;
4064   }
4065 
4066   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4067   // this is an error (OpenCL v1.1 s6.3.k)
4068   if (T->isVoidType()) {
4069     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4070                                         : diag::ext_sizeof_alignof_void_type;
4071     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4072     return false;
4073   }
4074 
4075   return true;
4076 }
4077 
4078 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4079                                              SourceLocation Loc,
4080                                              SourceRange ArgRange,
4081                                              UnaryExprOrTypeTrait TraitKind) {
4082   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4083   // runtime doesn't allow it.
4084   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4085     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4086       << T << (TraitKind == UETT_SizeOf)
4087       << ArgRange;
4088     return true;
4089   }
4090 
4091   return false;
4092 }
4093 
4094 /// Check whether E is a pointer from a decayed array type (the decayed
4095 /// pointer type is equal to T) and emit a warning if it is.
4096 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4097                                      Expr *E) {
4098   // Don't warn if the operation changed the type.
4099   if (T != E->getType())
4100     return;
4101 
4102   // Now look for array decays.
4103   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4104   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4105     return;
4106 
4107   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4108                                              << ICE->getType()
4109                                              << ICE->getSubExpr()->getType();
4110 }
4111 
4112 /// Check the constraints on expression operands to unary type expression
4113 /// and type traits.
4114 ///
4115 /// Completes any types necessary and validates the constraints on the operand
4116 /// expression. The logic mostly mirrors the type-based overload, but may modify
4117 /// the expression as it completes the type for that expression through template
4118 /// instantiation, etc.
4119 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4120                                             UnaryExprOrTypeTrait ExprKind) {
4121   QualType ExprTy = E->getType();
4122   assert(!ExprTy->isReferenceType());
4123 
4124   bool IsUnevaluatedOperand =
4125       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4126        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4127   if (IsUnevaluatedOperand) {
4128     ExprResult Result = CheckUnevaluatedOperand(E);
4129     if (Result.isInvalid())
4130       return true;
4131     E = Result.get();
4132   }
4133 
4134   // The operand for sizeof and alignof is in an unevaluated expression context,
4135   // so side effects could result in unintended consequences.
4136   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4137   // used to build SFINAE gadgets.
4138   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4139   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4140       !E->isInstantiationDependent() &&
4141       E->HasSideEffects(Context, false))
4142     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4143 
4144   if (ExprKind == UETT_VecStep)
4145     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4146                                         E->getSourceRange());
4147 
4148   // Explicitly list some types as extensions.
4149   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4150                                       E->getSourceRange(), ExprKind))
4151     return false;
4152 
4153   // 'alignof' applied to an expression only requires the base element type of
4154   // the expression to be complete. 'sizeof' requires the expression's type to
4155   // be complete (and will attempt to complete it if it's an array of unknown
4156   // bound).
4157   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4158     if (RequireCompleteSizedType(
4159             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4160             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4161             getTraitSpelling(ExprKind), E->getSourceRange()))
4162       return true;
4163   } else {
4164     if (RequireCompleteSizedExprType(
4165             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4166             getTraitSpelling(ExprKind), E->getSourceRange()))
4167       return true;
4168   }
4169 
4170   // Completing the expression's type may have changed it.
4171   ExprTy = E->getType();
4172   assert(!ExprTy->isReferenceType());
4173 
4174   if (ExprTy->isFunctionType()) {
4175     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4176         << getTraitSpelling(ExprKind) << E->getSourceRange();
4177     return true;
4178   }
4179 
4180   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4181                                        E->getSourceRange(), ExprKind))
4182     return true;
4183 
4184   if (ExprKind == UETT_SizeOf) {
4185     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4186       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4187         QualType OType = PVD->getOriginalType();
4188         QualType Type = PVD->getType();
4189         if (Type->isPointerType() && OType->isArrayType()) {
4190           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4191             << Type << OType;
4192           Diag(PVD->getLocation(), diag::note_declared_at);
4193         }
4194       }
4195     }
4196 
4197     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4198     // decays into a pointer and returns an unintended result. This is most
4199     // likely a typo for "sizeof(array) op x".
4200     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4201       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4202                                BO->getLHS());
4203       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4204                                BO->getRHS());
4205     }
4206   }
4207 
4208   return false;
4209 }
4210 
4211 /// Check the constraints on operands to unary expression and type
4212 /// traits.
4213 ///
4214 /// This will complete any types necessary, and validate the various constraints
4215 /// on those operands.
4216 ///
4217 /// The UsualUnaryConversions() function is *not* called by this routine.
4218 /// C99 6.3.2.1p[2-4] all state:
4219 ///   Except when it is the operand of the sizeof operator ...
4220 ///
4221 /// C++ [expr.sizeof]p4
4222 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4223 ///   standard conversions are not applied to the operand of sizeof.
4224 ///
4225 /// This policy is followed for all of the unary trait expressions.
4226 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4227                                             SourceLocation OpLoc,
4228                                             SourceRange ExprRange,
4229                                             UnaryExprOrTypeTrait ExprKind) {
4230   if (ExprType->isDependentType())
4231     return false;
4232 
4233   // C++ [expr.sizeof]p2:
4234   //     When applied to a reference or a reference type, the result
4235   //     is the size of the referenced type.
4236   // C++11 [expr.alignof]p3:
4237   //     When alignof is applied to a reference type, the result
4238   //     shall be the alignment of the referenced type.
4239   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4240     ExprType = Ref->getPointeeType();
4241 
4242   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4243   //   When alignof or _Alignof is applied to an array type, the result
4244   //   is the alignment of the element type.
4245   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4246       ExprKind == UETT_OpenMPRequiredSimdAlign)
4247     ExprType = Context.getBaseElementType(ExprType);
4248 
4249   if (ExprKind == UETT_VecStep)
4250     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4251 
4252   // Explicitly list some types as extensions.
4253   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4254                                       ExprKind))
4255     return false;
4256 
4257   if (RequireCompleteSizedType(
4258           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4259           getTraitSpelling(ExprKind), ExprRange))
4260     return true;
4261 
4262   if (ExprType->isFunctionType()) {
4263     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4264         << getTraitSpelling(ExprKind) << ExprRange;
4265     return true;
4266   }
4267 
4268   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4269                                        ExprKind))
4270     return true;
4271 
4272   return false;
4273 }
4274 
4275 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4276   // Cannot know anything else if the expression is dependent.
4277   if (E->isTypeDependent())
4278     return false;
4279 
4280   if (E->getObjectKind() == OK_BitField) {
4281     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4282        << 1 << E->getSourceRange();
4283     return true;
4284   }
4285 
4286   ValueDecl *D = nullptr;
4287   Expr *Inner = E->IgnoreParens();
4288   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4289     D = DRE->getDecl();
4290   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4291     D = ME->getMemberDecl();
4292   }
4293 
4294   // If it's a field, require the containing struct to have a
4295   // complete definition so that we can compute the layout.
4296   //
4297   // This can happen in C++11 onwards, either by naming the member
4298   // in a way that is not transformed into a member access expression
4299   // (in an unevaluated operand, for instance), or by naming the member
4300   // in a trailing-return-type.
4301   //
4302   // For the record, since __alignof__ on expressions is a GCC
4303   // extension, GCC seems to permit this but always gives the
4304   // nonsensical answer 0.
4305   //
4306   // We don't really need the layout here --- we could instead just
4307   // directly check for all the appropriate alignment-lowing
4308   // attributes --- but that would require duplicating a lot of
4309   // logic that just isn't worth duplicating for such a marginal
4310   // use-case.
4311   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4312     // Fast path this check, since we at least know the record has a
4313     // definition if we can find a member of it.
4314     if (!FD->getParent()->isCompleteDefinition()) {
4315       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4316         << E->getSourceRange();
4317       return true;
4318     }
4319 
4320     // Otherwise, if it's a field, and the field doesn't have
4321     // reference type, then it must have a complete type (or be a
4322     // flexible array member, which we explicitly want to
4323     // white-list anyway), which makes the following checks trivial.
4324     if (!FD->getType()->isReferenceType())
4325       return false;
4326   }
4327 
4328   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4329 }
4330 
4331 bool Sema::CheckVecStepExpr(Expr *E) {
4332   E = E->IgnoreParens();
4333 
4334   // Cannot know anything else if the expression is dependent.
4335   if (E->isTypeDependent())
4336     return false;
4337 
4338   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4339 }
4340 
4341 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4342                                         CapturingScopeInfo *CSI) {
4343   assert(T->isVariablyModifiedType());
4344   assert(CSI != nullptr);
4345 
4346   // We're going to walk down into the type and look for VLA expressions.
4347   do {
4348     const Type *Ty = T.getTypePtr();
4349     switch (Ty->getTypeClass()) {
4350 #define TYPE(Class, Base)
4351 #define ABSTRACT_TYPE(Class, Base)
4352 #define NON_CANONICAL_TYPE(Class, Base)
4353 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4354 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4355 #include "clang/AST/TypeNodes.inc"
4356       T = QualType();
4357       break;
4358     // These types are never variably-modified.
4359     case Type::Builtin:
4360     case Type::Complex:
4361     case Type::Vector:
4362     case Type::ExtVector:
4363     case Type::ConstantMatrix:
4364     case Type::Record:
4365     case Type::Enum:
4366     case Type::Elaborated:
4367     case Type::TemplateSpecialization:
4368     case Type::ObjCObject:
4369     case Type::ObjCInterface:
4370     case Type::ObjCObjectPointer:
4371     case Type::ObjCTypeParam:
4372     case Type::Pipe:
4373     case Type::ExtInt:
4374       llvm_unreachable("type class is never variably-modified!");
4375     case Type::Adjusted:
4376       T = cast<AdjustedType>(Ty)->getOriginalType();
4377       break;
4378     case Type::Decayed:
4379       T = cast<DecayedType>(Ty)->getPointeeType();
4380       break;
4381     case Type::Pointer:
4382       T = cast<PointerType>(Ty)->getPointeeType();
4383       break;
4384     case Type::BlockPointer:
4385       T = cast<BlockPointerType>(Ty)->getPointeeType();
4386       break;
4387     case Type::LValueReference:
4388     case Type::RValueReference:
4389       T = cast<ReferenceType>(Ty)->getPointeeType();
4390       break;
4391     case Type::MemberPointer:
4392       T = cast<MemberPointerType>(Ty)->getPointeeType();
4393       break;
4394     case Type::ConstantArray:
4395     case Type::IncompleteArray:
4396       // Losing element qualification here is fine.
4397       T = cast<ArrayType>(Ty)->getElementType();
4398       break;
4399     case Type::VariableArray: {
4400       // Losing element qualification here is fine.
4401       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4402 
4403       // Unknown size indication requires no size computation.
4404       // Otherwise, evaluate and record it.
4405       auto Size = VAT->getSizeExpr();
4406       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4407           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4408         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4409 
4410       T = VAT->getElementType();
4411       break;
4412     }
4413     case Type::FunctionProto:
4414     case Type::FunctionNoProto:
4415       T = cast<FunctionType>(Ty)->getReturnType();
4416       break;
4417     case Type::Paren:
4418     case Type::TypeOf:
4419     case Type::UnaryTransform:
4420     case Type::Attributed:
4421     case Type::SubstTemplateTypeParm:
4422     case Type::MacroQualified:
4423       // Keep walking after single level desugaring.
4424       T = T.getSingleStepDesugaredType(Context);
4425       break;
4426     case Type::Typedef:
4427       T = cast<TypedefType>(Ty)->desugar();
4428       break;
4429     case Type::Decltype:
4430       T = cast<DecltypeType>(Ty)->desugar();
4431       break;
4432     case Type::Auto:
4433     case Type::DeducedTemplateSpecialization:
4434       T = cast<DeducedType>(Ty)->getDeducedType();
4435       break;
4436     case Type::TypeOfExpr:
4437       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4438       break;
4439     case Type::Atomic:
4440       T = cast<AtomicType>(Ty)->getValueType();
4441       break;
4442     }
4443   } while (!T.isNull() && T->isVariablyModifiedType());
4444 }
4445 
4446 /// Build a sizeof or alignof expression given a type operand.
4447 ExprResult
4448 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4449                                      SourceLocation OpLoc,
4450                                      UnaryExprOrTypeTrait ExprKind,
4451                                      SourceRange R) {
4452   if (!TInfo)
4453     return ExprError();
4454 
4455   QualType T = TInfo->getType();
4456 
4457   if (!T->isDependentType() &&
4458       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4459     return ExprError();
4460 
4461   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4462     if (auto *TT = T->getAs<TypedefType>()) {
4463       for (auto I = FunctionScopes.rbegin(),
4464                 E = std::prev(FunctionScopes.rend());
4465            I != E; ++I) {
4466         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4467         if (CSI == nullptr)
4468           break;
4469         DeclContext *DC = nullptr;
4470         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4471           DC = LSI->CallOperator;
4472         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4473           DC = CRSI->TheCapturedDecl;
4474         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4475           DC = BSI->TheDecl;
4476         if (DC) {
4477           if (DC->containsDecl(TT->getDecl()))
4478             break;
4479           captureVariablyModifiedType(Context, T, CSI);
4480         }
4481       }
4482     }
4483   }
4484 
4485   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4486   return new (Context) UnaryExprOrTypeTraitExpr(
4487       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4488 }
4489 
4490 /// Build a sizeof or alignof expression given an expression
4491 /// operand.
4492 ExprResult
4493 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4494                                      UnaryExprOrTypeTrait ExprKind) {
4495   ExprResult PE = CheckPlaceholderExpr(E);
4496   if (PE.isInvalid())
4497     return ExprError();
4498 
4499   E = PE.get();
4500 
4501   // Verify that the operand is valid.
4502   bool isInvalid = false;
4503   if (E->isTypeDependent()) {
4504     // Delay type-checking for type-dependent expressions.
4505   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4506     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4507   } else if (ExprKind == UETT_VecStep) {
4508     isInvalid = CheckVecStepExpr(E);
4509   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4510       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4511       isInvalid = true;
4512   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4513     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4514     isInvalid = true;
4515   } else {
4516     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4517   }
4518 
4519   if (isInvalid)
4520     return ExprError();
4521 
4522   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4523     PE = TransformToPotentiallyEvaluated(E);
4524     if (PE.isInvalid()) return ExprError();
4525     E = PE.get();
4526   }
4527 
4528   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4529   return new (Context) UnaryExprOrTypeTraitExpr(
4530       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4531 }
4532 
4533 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4534 /// expr and the same for @c alignof and @c __alignof
4535 /// Note that the ArgRange is invalid if isType is false.
4536 ExprResult
4537 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4538                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4539                                     void *TyOrEx, SourceRange ArgRange) {
4540   // If error parsing type, ignore.
4541   if (!TyOrEx) return ExprError();
4542 
4543   if (IsType) {
4544     TypeSourceInfo *TInfo;
4545     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4546     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4547   }
4548 
4549   Expr *ArgEx = (Expr *)TyOrEx;
4550   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4551   return Result;
4552 }
4553 
4554 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4555                                      bool IsReal) {
4556   if (V.get()->isTypeDependent())
4557     return S.Context.DependentTy;
4558 
4559   // _Real and _Imag are only l-values for normal l-values.
4560   if (V.get()->getObjectKind() != OK_Ordinary) {
4561     V = S.DefaultLvalueConversion(V.get());
4562     if (V.isInvalid())
4563       return QualType();
4564   }
4565 
4566   // These operators return the element type of a complex type.
4567   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4568     return CT->getElementType();
4569 
4570   // Otherwise they pass through real integer and floating point types here.
4571   if (V.get()->getType()->isArithmeticType())
4572     return V.get()->getType();
4573 
4574   // Test for placeholders.
4575   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4576   if (PR.isInvalid()) return QualType();
4577   if (PR.get() != V.get()) {
4578     V = PR;
4579     return CheckRealImagOperand(S, V, Loc, IsReal);
4580   }
4581 
4582   // Reject anything else.
4583   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4584     << (IsReal ? "__real" : "__imag");
4585   return QualType();
4586 }
4587 
4588 
4589 
4590 ExprResult
4591 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4592                           tok::TokenKind Kind, Expr *Input) {
4593   UnaryOperatorKind Opc;
4594   switch (Kind) {
4595   default: llvm_unreachable("Unknown unary op!");
4596   case tok::plusplus:   Opc = UO_PostInc; break;
4597   case tok::minusminus: Opc = UO_PostDec; break;
4598   }
4599 
4600   // Since this might is a postfix expression, get rid of ParenListExprs.
4601   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4602   if (Result.isInvalid()) return ExprError();
4603   Input = Result.get();
4604 
4605   return BuildUnaryOp(S, OpLoc, Opc, Input);
4606 }
4607 
4608 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4609 ///
4610 /// \return true on error
4611 static bool checkArithmeticOnObjCPointer(Sema &S,
4612                                          SourceLocation opLoc,
4613                                          Expr *op) {
4614   assert(op->getType()->isObjCObjectPointerType());
4615   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4616       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4617     return false;
4618 
4619   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4620     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4621     << op->getSourceRange();
4622   return true;
4623 }
4624 
4625 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4626   auto *BaseNoParens = Base->IgnoreParens();
4627   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4628     return MSProp->getPropertyDecl()->getType()->isArrayType();
4629   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4630 }
4631 
4632 ExprResult
4633 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4634                               Expr *idx, SourceLocation rbLoc) {
4635   if (base && !base->getType().isNull() &&
4636       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4637     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4638                                     SourceLocation(), /*Length*/ nullptr,
4639                                     /*Stride=*/nullptr, rbLoc);
4640 
4641   // Since this might be a postfix expression, get rid of ParenListExprs.
4642   if (isa<ParenListExpr>(base)) {
4643     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4644     if (result.isInvalid()) return ExprError();
4645     base = result.get();
4646   }
4647 
4648   // Check if base and idx form a MatrixSubscriptExpr.
4649   //
4650   // Helper to check for comma expressions, which are not allowed as indices for
4651   // matrix subscript expressions.
4652   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4653     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4654       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4655           << SourceRange(base->getBeginLoc(), rbLoc);
4656       return true;
4657     }
4658     return false;
4659   };
4660   // The matrix subscript operator ([][])is considered a single operator.
4661   // Separating the index expressions by parenthesis is not allowed.
4662   if (base->getType()->isSpecificPlaceholderType(
4663           BuiltinType::IncompleteMatrixIdx) &&
4664       !isa<MatrixSubscriptExpr>(base)) {
4665     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4666         << SourceRange(base->getBeginLoc(), rbLoc);
4667     return ExprError();
4668   }
4669   // If the base is a MatrixSubscriptExpr, try to create a new
4670   // MatrixSubscriptExpr.
4671   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4672   if (matSubscriptE) {
4673     if (CheckAndReportCommaError(idx))
4674       return ExprError();
4675 
4676     assert(matSubscriptE->isIncomplete() &&
4677            "base has to be an incomplete matrix subscript");
4678     return CreateBuiltinMatrixSubscriptExpr(
4679         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4680   }
4681 
4682   // Handle any non-overload placeholder types in the base and index
4683   // expressions.  We can't handle overloads here because the other
4684   // operand might be an overloadable type, in which case the overload
4685   // resolution for the operator overload should get the first crack
4686   // at the overload.
4687   bool IsMSPropertySubscript = false;
4688   if (base->getType()->isNonOverloadPlaceholderType()) {
4689     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4690     if (!IsMSPropertySubscript) {
4691       ExprResult result = CheckPlaceholderExpr(base);
4692       if (result.isInvalid())
4693         return ExprError();
4694       base = result.get();
4695     }
4696   }
4697 
4698   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4699   if (base->getType()->isMatrixType()) {
4700     if (CheckAndReportCommaError(idx))
4701       return ExprError();
4702 
4703     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4704   }
4705 
4706   // A comma-expression as the index is deprecated in C++2a onwards.
4707   if (getLangOpts().CPlusPlus20 &&
4708       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4709        (isa<CXXOperatorCallExpr>(idx) &&
4710         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4711     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4712         << SourceRange(base->getBeginLoc(), rbLoc);
4713   }
4714 
4715   if (idx->getType()->isNonOverloadPlaceholderType()) {
4716     ExprResult result = CheckPlaceholderExpr(idx);
4717     if (result.isInvalid()) return ExprError();
4718     idx = result.get();
4719   }
4720 
4721   // Build an unanalyzed expression if either operand is type-dependent.
4722   if (getLangOpts().CPlusPlus &&
4723       (base->isTypeDependent() || idx->isTypeDependent())) {
4724     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4725                                             VK_LValue, OK_Ordinary, rbLoc);
4726   }
4727 
4728   // MSDN, property (C++)
4729   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4730   // This attribute can also be used in the declaration of an empty array in a
4731   // class or structure definition. For example:
4732   // __declspec(property(get=GetX, put=PutX)) int x[];
4733   // The above statement indicates that x[] can be used with one or more array
4734   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4735   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4736   if (IsMSPropertySubscript) {
4737     // Build MS property subscript expression if base is MS property reference
4738     // or MS property subscript.
4739     return new (Context) MSPropertySubscriptExpr(
4740         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4741   }
4742 
4743   // Use C++ overloaded-operator rules if either operand has record
4744   // type.  The spec says to do this if either type is *overloadable*,
4745   // but enum types can't declare subscript operators or conversion
4746   // operators, so there's nothing interesting for overload resolution
4747   // to do if there aren't any record types involved.
4748   //
4749   // ObjC pointers have their own subscripting logic that is not tied
4750   // to overload resolution and so should not take this path.
4751   if (getLangOpts().CPlusPlus &&
4752       (base->getType()->isRecordType() ||
4753        (!base->getType()->isObjCObjectPointerType() &&
4754         idx->getType()->isRecordType()))) {
4755     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4756   }
4757 
4758   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4759 
4760   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4761     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4762 
4763   return Res;
4764 }
4765 
4766 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4767   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4768   InitializationKind Kind =
4769       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4770   InitializationSequence InitSeq(*this, Entity, Kind, E);
4771   return InitSeq.Perform(*this, Entity, Kind, E);
4772 }
4773 
4774 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4775                                                   Expr *ColumnIdx,
4776                                                   SourceLocation RBLoc) {
4777   ExprResult BaseR = CheckPlaceholderExpr(Base);
4778   if (BaseR.isInvalid())
4779     return BaseR;
4780   Base = BaseR.get();
4781 
4782   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4783   if (RowR.isInvalid())
4784     return RowR;
4785   RowIdx = RowR.get();
4786 
4787   if (!ColumnIdx)
4788     return new (Context) MatrixSubscriptExpr(
4789         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4790 
4791   // Build an unanalyzed expression if any of the operands is type-dependent.
4792   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4793       ColumnIdx->isTypeDependent())
4794     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4795                                              Context.DependentTy, RBLoc);
4796 
4797   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4798   if (ColumnR.isInvalid())
4799     return ColumnR;
4800   ColumnIdx = ColumnR.get();
4801 
4802   // Check that IndexExpr is an integer expression. If it is a constant
4803   // expression, check that it is less than Dim (= the number of elements in the
4804   // corresponding dimension).
4805   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4806                           bool IsColumnIdx) -> Expr * {
4807     if (!IndexExpr->getType()->isIntegerType() &&
4808         !IndexExpr->isTypeDependent()) {
4809       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4810           << IsColumnIdx;
4811       return nullptr;
4812     }
4813 
4814     if (Optional<llvm::APSInt> Idx =
4815             IndexExpr->getIntegerConstantExpr(Context)) {
4816       if ((*Idx < 0 || *Idx >= Dim)) {
4817         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4818             << IsColumnIdx << Dim;
4819         return nullptr;
4820       }
4821     }
4822 
4823     ExprResult ConvExpr =
4824         tryConvertExprToType(IndexExpr, Context.getSizeType());
4825     assert(!ConvExpr.isInvalid() &&
4826            "should be able to convert any integer type to size type");
4827     return ConvExpr.get();
4828   };
4829 
4830   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4831   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4832   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4833   if (!RowIdx || !ColumnIdx)
4834     return ExprError();
4835 
4836   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4837                                            MTy->getElementType(), RBLoc);
4838 }
4839 
4840 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4841   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4842   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4843 
4844   // For expressions like `&(*s).b`, the base is recorded and what should be
4845   // checked.
4846   const MemberExpr *Member = nullptr;
4847   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4848     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4849 
4850   LastRecord.PossibleDerefs.erase(StrippedExpr);
4851 }
4852 
4853 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4854   if (isUnevaluatedContext())
4855     return;
4856 
4857   QualType ResultTy = E->getType();
4858   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4859 
4860   // Bail if the element is an array since it is not memory access.
4861   if (isa<ArrayType>(ResultTy))
4862     return;
4863 
4864   if (ResultTy->hasAttr(attr::NoDeref)) {
4865     LastRecord.PossibleDerefs.insert(E);
4866     return;
4867   }
4868 
4869   // Check if the base type is a pointer to a member access of a struct
4870   // marked with noderef.
4871   const Expr *Base = E->getBase();
4872   QualType BaseTy = Base->getType();
4873   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4874     // Not a pointer access
4875     return;
4876 
4877   const MemberExpr *Member = nullptr;
4878   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4879          Member->isArrow())
4880     Base = Member->getBase();
4881 
4882   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4883     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4884       LastRecord.PossibleDerefs.insert(E);
4885   }
4886 }
4887 
4888 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4889                                           Expr *LowerBound,
4890                                           SourceLocation ColonLocFirst,
4891                                           SourceLocation ColonLocSecond,
4892                                           Expr *Length, Expr *Stride,
4893                                           SourceLocation RBLoc) {
4894   if (Base->getType()->isPlaceholderType() &&
4895       !Base->getType()->isSpecificPlaceholderType(
4896           BuiltinType::OMPArraySection)) {
4897     ExprResult Result = CheckPlaceholderExpr(Base);
4898     if (Result.isInvalid())
4899       return ExprError();
4900     Base = Result.get();
4901   }
4902   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4903     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4904     if (Result.isInvalid())
4905       return ExprError();
4906     Result = DefaultLvalueConversion(Result.get());
4907     if (Result.isInvalid())
4908       return ExprError();
4909     LowerBound = Result.get();
4910   }
4911   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4912     ExprResult Result = CheckPlaceholderExpr(Length);
4913     if (Result.isInvalid())
4914       return ExprError();
4915     Result = DefaultLvalueConversion(Result.get());
4916     if (Result.isInvalid())
4917       return ExprError();
4918     Length = Result.get();
4919   }
4920   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4921     ExprResult Result = CheckPlaceholderExpr(Stride);
4922     if (Result.isInvalid())
4923       return ExprError();
4924     Result = DefaultLvalueConversion(Result.get());
4925     if (Result.isInvalid())
4926       return ExprError();
4927     Stride = Result.get();
4928   }
4929 
4930   // Build an unanalyzed expression if either operand is type-dependent.
4931   if (Base->isTypeDependent() ||
4932       (LowerBound &&
4933        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4934       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4935       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4936     return new (Context) OMPArraySectionExpr(
4937         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4938         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4939   }
4940 
4941   // Perform default conversions.
4942   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4943   QualType ResultTy;
4944   if (OriginalTy->isAnyPointerType()) {
4945     ResultTy = OriginalTy->getPointeeType();
4946   } else if (OriginalTy->isArrayType()) {
4947     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4948   } else {
4949     return ExprError(
4950         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4951         << Base->getSourceRange());
4952   }
4953   // C99 6.5.2.1p1
4954   if (LowerBound) {
4955     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4956                                                       LowerBound);
4957     if (Res.isInvalid())
4958       return ExprError(Diag(LowerBound->getExprLoc(),
4959                             diag::err_omp_typecheck_section_not_integer)
4960                        << 0 << LowerBound->getSourceRange());
4961     LowerBound = Res.get();
4962 
4963     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4964         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4965       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4966           << 0 << LowerBound->getSourceRange();
4967   }
4968   if (Length) {
4969     auto Res =
4970         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4971     if (Res.isInvalid())
4972       return ExprError(Diag(Length->getExprLoc(),
4973                             diag::err_omp_typecheck_section_not_integer)
4974                        << 1 << Length->getSourceRange());
4975     Length = Res.get();
4976 
4977     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4978         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4979       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4980           << 1 << Length->getSourceRange();
4981   }
4982   if (Stride) {
4983     ExprResult Res =
4984         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4985     if (Res.isInvalid())
4986       return ExprError(Diag(Stride->getExprLoc(),
4987                             diag::err_omp_typecheck_section_not_integer)
4988                        << 1 << Stride->getSourceRange());
4989     Stride = Res.get();
4990 
4991     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4992         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4993       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4994           << 1 << Stride->getSourceRange();
4995   }
4996 
4997   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4998   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4999   // type. Note that functions are not objects, and that (in C99 parlance)
5000   // incomplete types are not object types.
5001   if (ResultTy->isFunctionType()) {
5002     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5003         << ResultTy << Base->getSourceRange();
5004     return ExprError();
5005   }
5006 
5007   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5008                           diag::err_omp_section_incomplete_type, Base))
5009     return ExprError();
5010 
5011   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5012     Expr::EvalResult Result;
5013     if (LowerBound->EvaluateAsInt(Result, Context)) {
5014       // OpenMP 5.0, [2.1.5 Array Sections]
5015       // The array section must be a subset of the original array.
5016       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5017       if (LowerBoundValue.isNegative()) {
5018         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5019             << LowerBound->getSourceRange();
5020         return ExprError();
5021       }
5022     }
5023   }
5024 
5025   if (Length) {
5026     Expr::EvalResult Result;
5027     if (Length->EvaluateAsInt(Result, Context)) {
5028       // OpenMP 5.0, [2.1.5 Array Sections]
5029       // The length must evaluate to non-negative integers.
5030       llvm::APSInt LengthValue = Result.Val.getInt();
5031       if (LengthValue.isNegative()) {
5032         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5033             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
5034             << Length->getSourceRange();
5035         return ExprError();
5036       }
5037     }
5038   } else if (ColonLocFirst.isValid() &&
5039              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5040                                       !OriginalTy->isVariableArrayType()))) {
5041     // OpenMP 5.0, [2.1.5 Array Sections]
5042     // When the size of the array dimension is not known, the length must be
5043     // specified explicitly.
5044     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5045         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5046     return ExprError();
5047   }
5048 
5049   if (Stride) {
5050     Expr::EvalResult Result;
5051     if (Stride->EvaluateAsInt(Result, Context)) {
5052       // OpenMP 5.0, [2.1.5 Array Sections]
5053       // The stride must evaluate to a positive integer.
5054       llvm::APSInt StrideValue = Result.Val.getInt();
5055       if (!StrideValue.isStrictlyPositive()) {
5056         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5057             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5058             << Stride->getSourceRange();
5059         return ExprError();
5060       }
5061     }
5062   }
5063 
5064   if (!Base->getType()->isSpecificPlaceholderType(
5065           BuiltinType::OMPArraySection)) {
5066     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5067     if (Result.isInvalid())
5068       return ExprError();
5069     Base = Result.get();
5070   }
5071   return new (Context) OMPArraySectionExpr(
5072       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5073       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5074 }
5075 
5076 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5077                                           SourceLocation RParenLoc,
5078                                           ArrayRef<Expr *> Dims,
5079                                           ArrayRef<SourceRange> Brackets) {
5080   if (Base->getType()->isPlaceholderType()) {
5081     ExprResult Result = CheckPlaceholderExpr(Base);
5082     if (Result.isInvalid())
5083       return ExprError();
5084     Result = DefaultLvalueConversion(Result.get());
5085     if (Result.isInvalid())
5086       return ExprError();
5087     Base = Result.get();
5088   }
5089   QualType BaseTy = Base->getType();
5090   // Delay analysis of the types/expressions if instantiation/specialization is
5091   // required.
5092   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5093     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5094                                        LParenLoc, RParenLoc, Dims, Brackets);
5095   if (!BaseTy->isPointerType() ||
5096       (!Base->isTypeDependent() &&
5097        BaseTy->getPointeeType()->isIncompleteType()))
5098     return ExprError(Diag(Base->getExprLoc(),
5099                           diag::err_omp_non_pointer_type_array_shaping_base)
5100                      << Base->getSourceRange());
5101 
5102   SmallVector<Expr *, 4> NewDims;
5103   bool ErrorFound = false;
5104   for (Expr *Dim : Dims) {
5105     if (Dim->getType()->isPlaceholderType()) {
5106       ExprResult Result = CheckPlaceholderExpr(Dim);
5107       if (Result.isInvalid()) {
5108         ErrorFound = true;
5109         continue;
5110       }
5111       Result = DefaultLvalueConversion(Result.get());
5112       if (Result.isInvalid()) {
5113         ErrorFound = true;
5114         continue;
5115       }
5116       Dim = Result.get();
5117     }
5118     if (!Dim->isTypeDependent()) {
5119       ExprResult Result =
5120           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5121       if (Result.isInvalid()) {
5122         ErrorFound = true;
5123         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5124             << Dim->getSourceRange();
5125         continue;
5126       }
5127       Dim = Result.get();
5128       Expr::EvalResult EvResult;
5129       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5130         // OpenMP 5.0, [2.1.4 Array Shaping]
5131         // Each si is an integral type expression that must evaluate to a
5132         // positive integer.
5133         llvm::APSInt Value = EvResult.Val.getInt();
5134         if (!Value.isStrictlyPositive()) {
5135           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5136               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5137               << Dim->getSourceRange();
5138           ErrorFound = true;
5139           continue;
5140         }
5141       }
5142     }
5143     NewDims.push_back(Dim);
5144   }
5145   if (ErrorFound)
5146     return ExprError();
5147   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5148                                      LParenLoc, RParenLoc, NewDims, Brackets);
5149 }
5150 
5151 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5152                                       SourceLocation LLoc, SourceLocation RLoc,
5153                                       ArrayRef<OMPIteratorData> Data) {
5154   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5155   bool IsCorrect = true;
5156   for (const OMPIteratorData &D : Data) {
5157     TypeSourceInfo *TInfo = nullptr;
5158     SourceLocation StartLoc;
5159     QualType DeclTy;
5160     if (!D.Type.getAsOpaquePtr()) {
5161       // OpenMP 5.0, 2.1.6 Iterators
5162       // In an iterator-specifier, if the iterator-type is not specified then
5163       // the type of that iterator is of int type.
5164       DeclTy = Context.IntTy;
5165       StartLoc = D.DeclIdentLoc;
5166     } else {
5167       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5168       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5169     }
5170 
5171     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5172                              DeclTy->containsUnexpandedParameterPack() ||
5173                              DeclTy->isInstantiationDependentType();
5174     if (!IsDeclTyDependent) {
5175       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5176         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5177         // The iterator-type must be an integral or pointer type.
5178         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5179             << DeclTy;
5180         IsCorrect = false;
5181         continue;
5182       }
5183       if (DeclTy.isConstant(Context)) {
5184         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5185         // The iterator-type must not be const qualified.
5186         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5187             << DeclTy;
5188         IsCorrect = false;
5189         continue;
5190       }
5191     }
5192 
5193     // Iterator declaration.
5194     assert(D.DeclIdent && "Identifier expected.");
5195     // Always try to create iterator declarator to avoid extra error messages
5196     // about unknown declarations use.
5197     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5198                                D.DeclIdent, DeclTy, TInfo, SC_None);
5199     VD->setImplicit();
5200     if (S) {
5201       // Check for conflicting previous declaration.
5202       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5203       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5204                             ForVisibleRedeclaration);
5205       Previous.suppressDiagnostics();
5206       LookupName(Previous, S);
5207 
5208       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5209                            /*AllowInlineNamespace=*/false);
5210       if (!Previous.empty()) {
5211         NamedDecl *Old = Previous.getRepresentativeDecl();
5212         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5213         Diag(Old->getLocation(), diag::note_previous_definition);
5214       } else {
5215         PushOnScopeChains(VD, S);
5216       }
5217     } else {
5218       CurContext->addDecl(VD);
5219     }
5220     Expr *Begin = D.Range.Begin;
5221     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5222       ExprResult BeginRes =
5223           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5224       Begin = BeginRes.get();
5225     }
5226     Expr *End = D.Range.End;
5227     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5228       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5229       End = EndRes.get();
5230     }
5231     Expr *Step = D.Range.Step;
5232     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5233       if (!Step->getType()->isIntegralType(Context)) {
5234         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5235             << Step << Step->getSourceRange();
5236         IsCorrect = false;
5237         continue;
5238       }
5239       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5240       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5241       // If the step expression of a range-specification equals zero, the
5242       // behavior is unspecified.
5243       if (Result && Result->isNullValue()) {
5244         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5245             << Step << Step->getSourceRange();
5246         IsCorrect = false;
5247         continue;
5248       }
5249     }
5250     if (!Begin || !End || !IsCorrect) {
5251       IsCorrect = false;
5252       continue;
5253     }
5254     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5255     IDElem.IteratorDecl = VD;
5256     IDElem.AssignmentLoc = D.AssignLoc;
5257     IDElem.Range.Begin = Begin;
5258     IDElem.Range.End = End;
5259     IDElem.Range.Step = Step;
5260     IDElem.ColonLoc = D.ColonLoc;
5261     IDElem.SecondColonLoc = D.SecColonLoc;
5262   }
5263   if (!IsCorrect) {
5264     // Invalidate all created iterator declarations if error is found.
5265     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5266       if (Decl *ID = D.IteratorDecl)
5267         ID->setInvalidDecl();
5268     }
5269     return ExprError();
5270   }
5271   SmallVector<OMPIteratorHelperData, 4> Helpers;
5272   if (!CurContext->isDependentContext()) {
5273     // Build number of ityeration for each iteration range.
5274     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5275     // ((Begini-Stepi-1-Endi) / -Stepi);
5276     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5277       // (Endi - Begini)
5278       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5279                                           D.Range.Begin);
5280       if(!Res.isUsable()) {
5281         IsCorrect = false;
5282         continue;
5283       }
5284       ExprResult St, St1;
5285       if (D.Range.Step) {
5286         St = D.Range.Step;
5287         // (Endi - Begini) + Stepi
5288         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5289         if (!Res.isUsable()) {
5290           IsCorrect = false;
5291           continue;
5292         }
5293         // (Endi - Begini) + Stepi - 1
5294         Res =
5295             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5296                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5297         if (!Res.isUsable()) {
5298           IsCorrect = false;
5299           continue;
5300         }
5301         // ((Endi - Begini) + Stepi - 1) / Stepi
5302         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5303         if (!Res.isUsable()) {
5304           IsCorrect = false;
5305           continue;
5306         }
5307         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5308         // (Begini - Endi)
5309         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5310                                              D.Range.Begin, D.Range.End);
5311         if (!Res1.isUsable()) {
5312           IsCorrect = false;
5313           continue;
5314         }
5315         // (Begini - Endi) - Stepi
5316         Res1 =
5317             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5318         if (!Res1.isUsable()) {
5319           IsCorrect = false;
5320           continue;
5321         }
5322         // (Begini - Endi) - Stepi - 1
5323         Res1 =
5324             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5325                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5326         if (!Res1.isUsable()) {
5327           IsCorrect = false;
5328           continue;
5329         }
5330         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5331         Res1 =
5332             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5333         if (!Res1.isUsable()) {
5334           IsCorrect = false;
5335           continue;
5336         }
5337         // Stepi > 0.
5338         ExprResult CmpRes =
5339             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5340                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5341         if (!CmpRes.isUsable()) {
5342           IsCorrect = false;
5343           continue;
5344         }
5345         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5346                                  Res.get(), Res1.get());
5347         if (!Res.isUsable()) {
5348           IsCorrect = false;
5349           continue;
5350         }
5351       }
5352       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5353       if (!Res.isUsable()) {
5354         IsCorrect = false;
5355         continue;
5356       }
5357 
5358       // Build counter update.
5359       // Build counter.
5360       auto *CounterVD =
5361           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5362                           D.IteratorDecl->getBeginLoc(), nullptr,
5363                           Res.get()->getType(), nullptr, SC_None);
5364       CounterVD->setImplicit();
5365       ExprResult RefRes =
5366           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5367                            D.IteratorDecl->getBeginLoc());
5368       // Build counter update.
5369       // I = Begini + counter * Stepi;
5370       ExprResult UpdateRes;
5371       if (D.Range.Step) {
5372         UpdateRes = CreateBuiltinBinOp(
5373             D.AssignmentLoc, BO_Mul,
5374             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5375       } else {
5376         UpdateRes = DefaultLvalueConversion(RefRes.get());
5377       }
5378       if (!UpdateRes.isUsable()) {
5379         IsCorrect = false;
5380         continue;
5381       }
5382       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5383                                      UpdateRes.get());
5384       if (!UpdateRes.isUsable()) {
5385         IsCorrect = false;
5386         continue;
5387       }
5388       ExprResult VDRes =
5389           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5390                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5391                            D.IteratorDecl->getBeginLoc());
5392       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5393                                      UpdateRes.get());
5394       if (!UpdateRes.isUsable()) {
5395         IsCorrect = false;
5396         continue;
5397       }
5398       UpdateRes =
5399           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5400       if (!UpdateRes.isUsable()) {
5401         IsCorrect = false;
5402         continue;
5403       }
5404       ExprResult CounterUpdateRes =
5405           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5406       if (!CounterUpdateRes.isUsable()) {
5407         IsCorrect = false;
5408         continue;
5409       }
5410       CounterUpdateRes =
5411           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5412       if (!CounterUpdateRes.isUsable()) {
5413         IsCorrect = false;
5414         continue;
5415       }
5416       OMPIteratorHelperData &HD = Helpers.emplace_back();
5417       HD.CounterVD = CounterVD;
5418       HD.Upper = Res.get();
5419       HD.Update = UpdateRes.get();
5420       HD.CounterUpdate = CounterUpdateRes.get();
5421     }
5422   } else {
5423     Helpers.assign(ID.size(), {});
5424   }
5425   if (!IsCorrect) {
5426     // Invalidate all created iterator declarations if error is found.
5427     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5428       if (Decl *ID = D.IteratorDecl)
5429         ID->setInvalidDecl();
5430     }
5431     return ExprError();
5432   }
5433   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5434                                  LLoc, RLoc, ID, Helpers);
5435 }
5436 
5437 ExprResult
5438 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5439                                       Expr *Idx, SourceLocation RLoc) {
5440   Expr *LHSExp = Base;
5441   Expr *RHSExp = Idx;
5442 
5443   ExprValueKind VK = VK_LValue;
5444   ExprObjectKind OK = OK_Ordinary;
5445 
5446   // Per C++ core issue 1213, the result is an xvalue if either operand is
5447   // a non-lvalue array, and an lvalue otherwise.
5448   if (getLangOpts().CPlusPlus11) {
5449     for (auto *Op : {LHSExp, RHSExp}) {
5450       Op = Op->IgnoreImplicit();
5451       if (Op->getType()->isArrayType() && !Op->isLValue())
5452         VK = VK_XValue;
5453     }
5454   }
5455 
5456   // Perform default conversions.
5457   if (!LHSExp->getType()->getAs<VectorType>()) {
5458     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5459     if (Result.isInvalid())
5460       return ExprError();
5461     LHSExp = Result.get();
5462   }
5463   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5464   if (Result.isInvalid())
5465     return ExprError();
5466   RHSExp = Result.get();
5467 
5468   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5469 
5470   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5471   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5472   // in the subscript position. As a result, we need to derive the array base
5473   // and index from the expression types.
5474   Expr *BaseExpr, *IndexExpr;
5475   QualType ResultType;
5476   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5477     BaseExpr = LHSExp;
5478     IndexExpr = RHSExp;
5479     ResultType = Context.DependentTy;
5480   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5481     BaseExpr = LHSExp;
5482     IndexExpr = RHSExp;
5483     ResultType = PTy->getPointeeType();
5484   } else if (const ObjCObjectPointerType *PTy =
5485                LHSTy->getAs<ObjCObjectPointerType>()) {
5486     BaseExpr = LHSExp;
5487     IndexExpr = RHSExp;
5488 
5489     // Use custom logic if this should be the pseudo-object subscript
5490     // expression.
5491     if (!LangOpts.isSubscriptPointerArithmetic())
5492       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5493                                           nullptr);
5494 
5495     ResultType = PTy->getPointeeType();
5496   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5497      // Handle the uncommon case of "123[Ptr]".
5498     BaseExpr = RHSExp;
5499     IndexExpr = LHSExp;
5500     ResultType = PTy->getPointeeType();
5501   } else if (const ObjCObjectPointerType *PTy =
5502                RHSTy->getAs<ObjCObjectPointerType>()) {
5503      // Handle the uncommon case of "123[Ptr]".
5504     BaseExpr = RHSExp;
5505     IndexExpr = LHSExp;
5506     ResultType = PTy->getPointeeType();
5507     if (!LangOpts.isSubscriptPointerArithmetic()) {
5508       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5509         << ResultType << BaseExpr->getSourceRange();
5510       return ExprError();
5511     }
5512   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5513     BaseExpr = LHSExp;    // vectors: V[123]
5514     IndexExpr = RHSExp;
5515     // We apply C++ DR1213 to vector subscripting too.
5516     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5517       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5518       if (Materialized.isInvalid())
5519         return ExprError();
5520       LHSExp = Materialized.get();
5521     }
5522     VK = LHSExp->getValueKind();
5523     if (VK != VK_RValue)
5524       OK = OK_VectorComponent;
5525 
5526     ResultType = VTy->getElementType();
5527     QualType BaseType = BaseExpr->getType();
5528     Qualifiers BaseQuals = BaseType.getQualifiers();
5529     Qualifiers MemberQuals = ResultType.getQualifiers();
5530     Qualifiers Combined = BaseQuals + MemberQuals;
5531     if (Combined != MemberQuals)
5532       ResultType = Context.getQualifiedType(ResultType, Combined);
5533   } else if (LHSTy->isArrayType()) {
5534     // If we see an array that wasn't promoted by
5535     // DefaultFunctionArrayLvalueConversion, it must be an array that
5536     // wasn't promoted because of the C90 rule that doesn't
5537     // allow promoting non-lvalue arrays.  Warn, then
5538     // force the promotion here.
5539     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5540         << LHSExp->getSourceRange();
5541     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5542                                CK_ArrayToPointerDecay).get();
5543     LHSTy = LHSExp->getType();
5544 
5545     BaseExpr = LHSExp;
5546     IndexExpr = RHSExp;
5547     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5548   } else if (RHSTy->isArrayType()) {
5549     // Same as previous, except for 123[f().a] case
5550     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5551         << RHSExp->getSourceRange();
5552     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5553                                CK_ArrayToPointerDecay).get();
5554     RHSTy = RHSExp->getType();
5555 
5556     BaseExpr = RHSExp;
5557     IndexExpr = LHSExp;
5558     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5559   } else {
5560     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5561        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5562   }
5563   // C99 6.5.2.1p1
5564   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5565     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5566                      << IndexExpr->getSourceRange());
5567 
5568   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5569        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5570          && !IndexExpr->isTypeDependent())
5571     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5572 
5573   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5574   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5575   // type. Note that Functions are not objects, and that (in C99 parlance)
5576   // incomplete types are not object types.
5577   if (ResultType->isFunctionType()) {
5578     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5579         << ResultType << BaseExpr->getSourceRange();
5580     return ExprError();
5581   }
5582 
5583   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5584     // GNU extension: subscripting on pointer to void
5585     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5586       << BaseExpr->getSourceRange();
5587 
5588     // C forbids expressions of unqualified void type from being l-values.
5589     // See IsCForbiddenLValueType.
5590     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5591   } else if (!ResultType->isDependentType() &&
5592              RequireCompleteSizedType(
5593                  LLoc, ResultType,
5594                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5595     return ExprError();
5596 
5597   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5598          !ResultType.isCForbiddenLValueType());
5599 
5600   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5601       FunctionScopes.size() > 1) {
5602     if (auto *TT =
5603             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5604       for (auto I = FunctionScopes.rbegin(),
5605                 E = std::prev(FunctionScopes.rend());
5606            I != E; ++I) {
5607         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5608         if (CSI == nullptr)
5609           break;
5610         DeclContext *DC = nullptr;
5611         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5612           DC = LSI->CallOperator;
5613         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5614           DC = CRSI->TheCapturedDecl;
5615         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5616           DC = BSI->TheDecl;
5617         if (DC) {
5618           if (DC->containsDecl(TT->getDecl()))
5619             break;
5620           captureVariablyModifiedType(
5621               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5622         }
5623       }
5624     }
5625   }
5626 
5627   return new (Context)
5628       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5629 }
5630 
5631 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5632                                   ParmVarDecl *Param) {
5633   if (Param->hasUnparsedDefaultArg()) {
5634     // If we've already cleared out the location for the default argument,
5635     // that means we're parsing it right now.
5636     if (!UnparsedDefaultArgLocs.count(Param)) {
5637       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5638       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5639       Param->setInvalidDecl();
5640       return true;
5641     }
5642 
5643     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5644         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5645     Diag(UnparsedDefaultArgLocs[Param],
5646          diag::note_default_argument_declared_here);
5647     return true;
5648   }
5649 
5650   if (Param->hasUninstantiatedDefaultArg() &&
5651       InstantiateDefaultArgument(CallLoc, FD, Param))
5652     return true;
5653 
5654   assert(Param->hasInit() && "default argument but no initializer?");
5655 
5656   // If the default expression creates temporaries, we need to
5657   // push them to the current stack of expression temporaries so they'll
5658   // be properly destroyed.
5659   // FIXME: We should really be rebuilding the default argument with new
5660   // bound temporaries; see the comment in PR5810.
5661   // We don't need to do that with block decls, though, because
5662   // blocks in default argument expression can never capture anything.
5663   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5664     // Set the "needs cleanups" bit regardless of whether there are
5665     // any explicit objects.
5666     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5667 
5668     // Append all the objects to the cleanup list.  Right now, this
5669     // should always be a no-op, because blocks in default argument
5670     // expressions should never be able to capture anything.
5671     assert(!Init->getNumObjects() &&
5672            "default argument expression has capturing blocks?");
5673   }
5674 
5675   // We already type-checked the argument, so we know it works.
5676   // Just mark all of the declarations in this potentially-evaluated expression
5677   // as being "referenced".
5678   EnterExpressionEvaluationContext EvalContext(
5679       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5680   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5681                                    /*SkipLocalVariables=*/true);
5682   return false;
5683 }
5684 
5685 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5686                                         FunctionDecl *FD, ParmVarDecl *Param) {
5687   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5688   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5689     return ExprError();
5690   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5691 }
5692 
5693 Sema::VariadicCallType
5694 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5695                           Expr *Fn) {
5696   if (Proto && Proto->isVariadic()) {
5697     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5698       return VariadicConstructor;
5699     else if (Fn && Fn->getType()->isBlockPointerType())
5700       return VariadicBlock;
5701     else if (FDecl) {
5702       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5703         if (Method->isInstance())
5704           return VariadicMethod;
5705     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5706       return VariadicMethod;
5707     return VariadicFunction;
5708   }
5709   return VariadicDoesNotApply;
5710 }
5711 
5712 namespace {
5713 class FunctionCallCCC final : public FunctionCallFilterCCC {
5714 public:
5715   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5716                   unsigned NumArgs, MemberExpr *ME)
5717       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5718         FunctionName(FuncName) {}
5719 
5720   bool ValidateCandidate(const TypoCorrection &candidate) override {
5721     if (!candidate.getCorrectionSpecifier() ||
5722         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5723       return false;
5724     }
5725 
5726     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5727   }
5728 
5729   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5730     return std::make_unique<FunctionCallCCC>(*this);
5731   }
5732 
5733 private:
5734   const IdentifierInfo *const FunctionName;
5735 };
5736 }
5737 
5738 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5739                                                FunctionDecl *FDecl,
5740                                                ArrayRef<Expr *> Args) {
5741   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5742   DeclarationName FuncName = FDecl->getDeclName();
5743   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5744 
5745   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5746   if (TypoCorrection Corrected = S.CorrectTypo(
5747           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5748           S.getScopeForContext(S.CurContext), nullptr, CCC,
5749           Sema::CTK_ErrorRecovery)) {
5750     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5751       if (Corrected.isOverloaded()) {
5752         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5753         OverloadCandidateSet::iterator Best;
5754         for (NamedDecl *CD : Corrected) {
5755           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5756             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5757                                    OCS);
5758         }
5759         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5760         case OR_Success:
5761           ND = Best->FoundDecl;
5762           Corrected.setCorrectionDecl(ND);
5763           break;
5764         default:
5765           break;
5766         }
5767       }
5768       ND = ND->getUnderlyingDecl();
5769       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5770         return Corrected;
5771     }
5772   }
5773   return TypoCorrection();
5774 }
5775 
5776 /// ConvertArgumentsForCall - Converts the arguments specified in
5777 /// Args/NumArgs to the parameter types of the function FDecl with
5778 /// function prototype Proto. Call is the call expression itself, and
5779 /// Fn is the function expression. For a C++ member function, this
5780 /// routine does not attempt to convert the object argument. Returns
5781 /// true if the call is ill-formed.
5782 bool
5783 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5784                               FunctionDecl *FDecl,
5785                               const FunctionProtoType *Proto,
5786                               ArrayRef<Expr *> Args,
5787                               SourceLocation RParenLoc,
5788                               bool IsExecConfig) {
5789   // Bail out early if calling a builtin with custom typechecking.
5790   if (FDecl)
5791     if (unsigned ID = FDecl->getBuiltinID())
5792       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5793         return false;
5794 
5795   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5796   // assignment, to the types of the corresponding parameter, ...
5797   unsigned NumParams = Proto->getNumParams();
5798   bool Invalid = false;
5799   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5800   unsigned FnKind = Fn->getType()->isBlockPointerType()
5801                        ? 1 /* block */
5802                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5803                                        : 0 /* function */);
5804 
5805   // If too few arguments are available (and we don't have default
5806   // arguments for the remaining parameters), don't make the call.
5807   if (Args.size() < NumParams) {
5808     if (Args.size() < MinArgs) {
5809       TypoCorrection TC;
5810       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5811         unsigned diag_id =
5812             MinArgs == NumParams && !Proto->isVariadic()
5813                 ? diag::err_typecheck_call_too_few_args_suggest
5814                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5815         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5816                                         << static_cast<unsigned>(Args.size())
5817                                         << TC.getCorrectionRange());
5818       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5819         Diag(RParenLoc,
5820              MinArgs == NumParams && !Proto->isVariadic()
5821                  ? diag::err_typecheck_call_too_few_args_one
5822                  : diag::err_typecheck_call_too_few_args_at_least_one)
5823             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5824       else
5825         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5826                             ? diag::err_typecheck_call_too_few_args
5827                             : diag::err_typecheck_call_too_few_args_at_least)
5828             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5829             << Fn->getSourceRange();
5830 
5831       // Emit the location of the prototype.
5832       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5833         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5834 
5835       return true;
5836     }
5837     // We reserve space for the default arguments when we create
5838     // the call expression, before calling ConvertArgumentsForCall.
5839     assert((Call->getNumArgs() == NumParams) &&
5840            "We should have reserved space for the default arguments before!");
5841   }
5842 
5843   // If too many are passed and not variadic, error on the extras and drop
5844   // them.
5845   if (Args.size() > NumParams) {
5846     if (!Proto->isVariadic()) {
5847       TypoCorrection TC;
5848       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5849         unsigned diag_id =
5850             MinArgs == NumParams && !Proto->isVariadic()
5851                 ? diag::err_typecheck_call_too_many_args_suggest
5852                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5853         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5854                                         << static_cast<unsigned>(Args.size())
5855                                         << TC.getCorrectionRange());
5856       } else if (NumParams == 1 && FDecl &&
5857                  FDecl->getParamDecl(0)->getDeclName())
5858         Diag(Args[NumParams]->getBeginLoc(),
5859              MinArgs == NumParams
5860                  ? diag::err_typecheck_call_too_many_args_one
5861                  : diag::err_typecheck_call_too_many_args_at_most_one)
5862             << FnKind << FDecl->getParamDecl(0)
5863             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5864             << SourceRange(Args[NumParams]->getBeginLoc(),
5865                            Args.back()->getEndLoc());
5866       else
5867         Diag(Args[NumParams]->getBeginLoc(),
5868              MinArgs == NumParams
5869                  ? diag::err_typecheck_call_too_many_args
5870                  : diag::err_typecheck_call_too_many_args_at_most)
5871             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5872             << Fn->getSourceRange()
5873             << SourceRange(Args[NumParams]->getBeginLoc(),
5874                            Args.back()->getEndLoc());
5875 
5876       // Emit the location of the prototype.
5877       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5878         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5879 
5880       // This deletes the extra arguments.
5881       Call->shrinkNumArgs(NumParams);
5882       return true;
5883     }
5884   }
5885   SmallVector<Expr *, 8> AllArgs;
5886   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5887 
5888   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5889                                    AllArgs, CallType);
5890   if (Invalid)
5891     return true;
5892   unsigned TotalNumArgs = AllArgs.size();
5893   for (unsigned i = 0; i < TotalNumArgs; ++i)
5894     Call->setArg(i, AllArgs[i]);
5895 
5896   return false;
5897 }
5898 
5899 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5900                                   const FunctionProtoType *Proto,
5901                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5902                                   SmallVectorImpl<Expr *> &AllArgs,
5903                                   VariadicCallType CallType, bool AllowExplicit,
5904                                   bool IsListInitialization) {
5905   unsigned NumParams = Proto->getNumParams();
5906   bool Invalid = false;
5907   size_t ArgIx = 0;
5908   // Continue to check argument types (even if we have too few/many args).
5909   for (unsigned i = FirstParam; i < NumParams; i++) {
5910     QualType ProtoArgType = Proto->getParamType(i);
5911 
5912     Expr *Arg;
5913     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5914     if (ArgIx < Args.size()) {
5915       Arg = Args[ArgIx++];
5916 
5917       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5918                               diag::err_call_incomplete_argument, Arg))
5919         return true;
5920 
5921       // Strip the unbridged-cast placeholder expression off, if applicable.
5922       bool CFAudited = false;
5923       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5924           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5925           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5926         Arg = stripARCUnbridgedCast(Arg);
5927       else if (getLangOpts().ObjCAutoRefCount &&
5928                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5929                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5930         CFAudited = true;
5931 
5932       if (Proto->getExtParameterInfo(i).isNoEscape())
5933         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5934           BE->getBlockDecl()->setDoesNotEscape();
5935 
5936       InitializedEntity Entity =
5937           Param ? InitializedEntity::InitializeParameter(Context, Param,
5938                                                          ProtoArgType)
5939                 : InitializedEntity::InitializeParameter(
5940                       Context, ProtoArgType, Proto->isParamConsumed(i));
5941 
5942       // Remember that parameter belongs to a CF audited API.
5943       if (CFAudited)
5944         Entity.setParameterCFAudited();
5945 
5946       ExprResult ArgE = PerformCopyInitialization(
5947           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5948       if (ArgE.isInvalid())
5949         return true;
5950 
5951       Arg = ArgE.getAs<Expr>();
5952     } else {
5953       assert(Param && "can't use default arguments without a known callee");
5954 
5955       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5956       if (ArgExpr.isInvalid())
5957         return true;
5958 
5959       Arg = ArgExpr.getAs<Expr>();
5960     }
5961 
5962     // Check for array bounds violations for each argument to the call. This
5963     // check only triggers warnings when the argument isn't a more complex Expr
5964     // with its own checking, such as a BinaryOperator.
5965     CheckArrayAccess(Arg);
5966 
5967     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5968     CheckStaticArrayArgument(CallLoc, Param, Arg);
5969 
5970     AllArgs.push_back(Arg);
5971   }
5972 
5973   // If this is a variadic call, handle args passed through "...".
5974   if (CallType != VariadicDoesNotApply) {
5975     // Assume that extern "C" functions with variadic arguments that
5976     // return __unknown_anytype aren't *really* variadic.
5977     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5978         FDecl->isExternC()) {
5979       for (Expr *A : Args.slice(ArgIx)) {
5980         QualType paramType; // ignored
5981         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5982         Invalid |= arg.isInvalid();
5983         AllArgs.push_back(arg.get());
5984       }
5985 
5986     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5987     } else {
5988       for (Expr *A : Args.slice(ArgIx)) {
5989         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5990         Invalid |= Arg.isInvalid();
5991         AllArgs.push_back(Arg.get());
5992       }
5993     }
5994 
5995     // Check for array bounds violations.
5996     for (Expr *A : Args.slice(ArgIx))
5997       CheckArrayAccess(A);
5998   }
5999   return Invalid;
6000 }
6001 
6002 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6003   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6004   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6005     TL = DTL.getOriginalLoc();
6006   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6007     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6008       << ATL.getLocalSourceRange();
6009 }
6010 
6011 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6012 /// array parameter, check that it is non-null, and that if it is formed by
6013 /// array-to-pointer decay, the underlying array is sufficiently large.
6014 ///
6015 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6016 /// array type derivation, then for each call to the function, the value of the
6017 /// corresponding actual argument shall provide access to the first element of
6018 /// an array with at least as many elements as specified by the size expression.
6019 void
6020 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6021                                ParmVarDecl *Param,
6022                                const Expr *ArgExpr) {
6023   // Static array parameters are not supported in C++.
6024   if (!Param || getLangOpts().CPlusPlus)
6025     return;
6026 
6027   QualType OrigTy = Param->getOriginalType();
6028 
6029   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6030   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6031     return;
6032 
6033   if (ArgExpr->isNullPointerConstant(Context,
6034                                      Expr::NPC_NeverValueDependent)) {
6035     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6036     DiagnoseCalleeStaticArrayParam(*this, Param);
6037     return;
6038   }
6039 
6040   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6041   if (!CAT)
6042     return;
6043 
6044   const ConstantArrayType *ArgCAT =
6045     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6046   if (!ArgCAT)
6047     return;
6048 
6049   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6050                                              ArgCAT->getElementType())) {
6051     if (ArgCAT->getSize().ult(CAT->getSize())) {
6052       Diag(CallLoc, diag::warn_static_array_too_small)
6053           << ArgExpr->getSourceRange()
6054           << (unsigned)ArgCAT->getSize().getZExtValue()
6055           << (unsigned)CAT->getSize().getZExtValue() << 0;
6056       DiagnoseCalleeStaticArrayParam(*this, Param);
6057     }
6058     return;
6059   }
6060 
6061   Optional<CharUnits> ArgSize =
6062       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6063   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6064   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6065     Diag(CallLoc, diag::warn_static_array_too_small)
6066         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6067         << (unsigned)ParmSize->getQuantity() << 1;
6068     DiagnoseCalleeStaticArrayParam(*this, Param);
6069   }
6070 }
6071 
6072 /// Given a function expression of unknown-any type, try to rebuild it
6073 /// to have a function type.
6074 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6075 
6076 /// Is the given type a placeholder that we need to lower out
6077 /// immediately during argument processing?
6078 static bool isPlaceholderToRemoveAsArg(QualType type) {
6079   // Placeholders are never sugared.
6080   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6081   if (!placeholder) return false;
6082 
6083   switch (placeholder->getKind()) {
6084   // Ignore all the non-placeholder types.
6085 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6086   case BuiltinType::Id:
6087 #include "clang/Basic/OpenCLImageTypes.def"
6088 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6089   case BuiltinType::Id:
6090 #include "clang/Basic/OpenCLExtensionTypes.def"
6091   // In practice we'll never use this, since all SVE types are sugared
6092   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6093 #define SVE_TYPE(Name, Id, SingletonId) \
6094   case BuiltinType::Id:
6095 #include "clang/Basic/AArch64SVEACLETypes.def"
6096 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6097   case BuiltinType::Id:
6098 #include "clang/Basic/PPCTypes.def"
6099 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6100 #include "clang/Basic/RISCVVTypes.def"
6101 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6102 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6103 #include "clang/AST/BuiltinTypes.def"
6104     return false;
6105 
6106   // We cannot lower out overload sets; they might validly be resolved
6107   // by the call machinery.
6108   case BuiltinType::Overload:
6109     return false;
6110 
6111   // Unbridged casts in ARC can be handled in some call positions and
6112   // should be left in place.
6113   case BuiltinType::ARCUnbridgedCast:
6114     return false;
6115 
6116   // Pseudo-objects should be converted as soon as possible.
6117   case BuiltinType::PseudoObject:
6118     return true;
6119 
6120   // The debugger mode could theoretically but currently does not try
6121   // to resolve unknown-typed arguments based on known parameter types.
6122   case BuiltinType::UnknownAny:
6123     return true;
6124 
6125   // These are always invalid as call arguments and should be reported.
6126   case BuiltinType::BoundMember:
6127   case BuiltinType::BuiltinFn:
6128   case BuiltinType::IncompleteMatrixIdx:
6129   case BuiltinType::OMPArraySection:
6130   case BuiltinType::OMPArrayShaping:
6131   case BuiltinType::OMPIterator:
6132     return true;
6133 
6134   }
6135   llvm_unreachable("bad builtin type kind");
6136 }
6137 
6138 /// Check an argument list for placeholders that we won't try to
6139 /// handle later.
6140 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6141   // Apply this processing to all the arguments at once instead of
6142   // dying at the first failure.
6143   bool hasInvalid = false;
6144   for (size_t i = 0, e = args.size(); i != e; i++) {
6145     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6146       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6147       if (result.isInvalid()) hasInvalid = true;
6148       else args[i] = result.get();
6149     }
6150   }
6151   return hasInvalid;
6152 }
6153 
6154 /// If a builtin function has a pointer argument with no explicit address
6155 /// space, then it should be able to accept a pointer to any address
6156 /// space as input.  In order to do this, we need to replace the
6157 /// standard builtin declaration with one that uses the same address space
6158 /// as the call.
6159 ///
6160 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6161 ///                  it does not contain any pointer arguments without
6162 ///                  an address space qualifer.  Otherwise the rewritten
6163 ///                  FunctionDecl is returned.
6164 /// TODO: Handle pointer return types.
6165 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6166                                                 FunctionDecl *FDecl,
6167                                                 MultiExprArg ArgExprs) {
6168 
6169   QualType DeclType = FDecl->getType();
6170   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6171 
6172   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6173       ArgExprs.size() < FT->getNumParams())
6174     return nullptr;
6175 
6176   bool NeedsNewDecl = false;
6177   unsigned i = 0;
6178   SmallVector<QualType, 8> OverloadParams;
6179 
6180   for (QualType ParamType : FT->param_types()) {
6181 
6182     // Convert array arguments to pointer to simplify type lookup.
6183     ExprResult ArgRes =
6184         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6185     if (ArgRes.isInvalid())
6186       return nullptr;
6187     Expr *Arg = ArgRes.get();
6188     QualType ArgType = Arg->getType();
6189     if (!ParamType->isPointerType() ||
6190         ParamType.hasAddressSpace() ||
6191         !ArgType->isPointerType() ||
6192         !ArgType->getPointeeType().hasAddressSpace()) {
6193       OverloadParams.push_back(ParamType);
6194       continue;
6195     }
6196 
6197     QualType PointeeType = ParamType->getPointeeType();
6198     if (PointeeType.hasAddressSpace())
6199       continue;
6200 
6201     NeedsNewDecl = true;
6202     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6203 
6204     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6205     OverloadParams.push_back(Context.getPointerType(PointeeType));
6206   }
6207 
6208   if (!NeedsNewDecl)
6209     return nullptr;
6210 
6211   FunctionProtoType::ExtProtoInfo EPI;
6212   EPI.Variadic = FT->isVariadic();
6213   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6214                                                 OverloadParams, EPI);
6215   DeclContext *Parent = FDecl->getParent();
6216   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6217                                                     FDecl->getLocation(),
6218                                                     FDecl->getLocation(),
6219                                                     FDecl->getIdentifier(),
6220                                                     OverloadTy,
6221                                                     /*TInfo=*/nullptr,
6222                                                     SC_Extern, false,
6223                                                     /*hasPrototype=*/true);
6224   SmallVector<ParmVarDecl*, 16> Params;
6225   FT = cast<FunctionProtoType>(OverloadTy);
6226   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6227     QualType ParamType = FT->getParamType(i);
6228     ParmVarDecl *Parm =
6229         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6230                                 SourceLocation(), nullptr, ParamType,
6231                                 /*TInfo=*/nullptr, SC_None, nullptr);
6232     Parm->setScopeInfo(0, i);
6233     Params.push_back(Parm);
6234   }
6235   OverloadDecl->setParams(Params);
6236   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6237   return OverloadDecl;
6238 }
6239 
6240 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6241                                     FunctionDecl *Callee,
6242                                     MultiExprArg ArgExprs) {
6243   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6244   // similar attributes) really don't like it when functions are called with an
6245   // invalid number of args.
6246   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6247                          /*PartialOverloading=*/false) &&
6248       !Callee->isVariadic())
6249     return;
6250   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6251     return;
6252 
6253   if (const EnableIfAttr *Attr =
6254           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6255     S.Diag(Fn->getBeginLoc(),
6256            isa<CXXMethodDecl>(Callee)
6257                ? diag::err_ovl_no_viable_member_function_in_call
6258                : diag::err_ovl_no_viable_function_in_call)
6259         << Callee << Callee->getSourceRange();
6260     S.Diag(Callee->getLocation(),
6261            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6262         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6263     return;
6264   }
6265 }
6266 
6267 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6268     const UnresolvedMemberExpr *const UME, Sema &S) {
6269 
6270   const auto GetFunctionLevelDCIfCXXClass =
6271       [](Sema &S) -> const CXXRecordDecl * {
6272     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6273     if (!DC || !DC->getParent())
6274       return nullptr;
6275 
6276     // If the call to some member function was made from within a member
6277     // function body 'M' return return 'M's parent.
6278     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6279       return MD->getParent()->getCanonicalDecl();
6280     // else the call was made from within a default member initializer of a
6281     // class, so return the class.
6282     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6283       return RD->getCanonicalDecl();
6284     return nullptr;
6285   };
6286   // If our DeclContext is neither a member function nor a class (in the
6287   // case of a lambda in a default member initializer), we can't have an
6288   // enclosing 'this'.
6289 
6290   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6291   if (!CurParentClass)
6292     return false;
6293 
6294   // The naming class for implicit member functions call is the class in which
6295   // name lookup starts.
6296   const CXXRecordDecl *const NamingClass =
6297       UME->getNamingClass()->getCanonicalDecl();
6298   assert(NamingClass && "Must have naming class even for implicit access");
6299 
6300   // If the unresolved member functions were found in a 'naming class' that is
6301   // related (either the same or derived from) to the class that contains the
6302   // member function that itself contained the implicit member access.
6303 
6304   return CurParentClass == NamingClass ||
6305          CurParentClass->isDerivedFrom(NamingClass);
6306 }
6307 
6308 static void
6309 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6310     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6311 
6312   if (!UME)
6313     return;
6314 
6315   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6316   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6317   // already been captured, or if this is an implicit member function call (if
6318   // it isn't, an attempt to capture 'this' should already have been made).
6319   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6320       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6321     return;
6322 
6323   // Check if the naming class in which the unresolved members were found is
6324   // related (same as or is a base of) to the enclosing class.
6325 
6326   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6327     return;
6328 
6329 
6330   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6331   // If the enclosing function is not dependent, then this lambda is
6332   // capture ready, so if we can capture this, do so.
6333   if (!EnclosingFunctionCtx->isDependentContext()) {
6334     // If the current lambda and all enclosing lambdas can capture 'this' -
6335     // then go ahead and capture 'this' (since our unresolved overload set
6336     // contains at least one non-static member function).
6337     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6338       S.CheckCXXThisCapture(CallLoc);
6339   } else if (S.CurContext->isDependentContext()) {
6340     // ... since this is an implicit member reference, that might potentially
6341     // involve a 'this' capture, mark 'this' for potential capture in
6342     // enclosing lambdas.
6343     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6344       CurLSI->addPotentialThisCapture(CallLoc);
6345   }
6346 }
6347 
6348 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6349                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6350                                Expr *ExecConfig) {
6351   ExprResult Call =
6352       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6353                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6354   if (Call.isInvalid())
6355     return Call;
6356 
6357   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6358   // language modes.
6359   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6360     if (ULE->hasExplicitTemplateArgs() &&
6361         ULE->decls_begin() == ULE->decls_end()) {
6362       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6363                                  ? diag::warn_cxx17_compat_adl_only_template_id
6364                                  : diag::ext_adl_only_template_id)
6365           << ULE->getName();
6366     }
6367   }
6368 
6369   if (LangOpts.OpenMP)
6370     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6371                            ExecConfig);
6372 
6373   return Call;
6374 }
6375 
6376 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6377 /// This provides the location of the left/right parens and a list of comma
6378 /// locations.
6379 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6380                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6381                                Expr *ExecConfig, bool IsExecConfig,
6382                                bool AllowRecovery) {
6383   // Since this might be a postfix expression, get rid of ParenListExprs.
6384   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6385   if (Result.isInvalid()) return ExprError();
6386   Fn = Result.get();
6387 
6388   if (checkArgsForPlaceholders(*this, ArgExprs))
6389     return ExprError();
6390 
6391   if (getLangOpts().CPlusPlus) {
6392     // If this is a pseudo-destructor expression, build the call immediately.
6393     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6394       if (!ArgExprs.empty()) {
6395         // Pseudo-destructor calls should not have any arguments.
6396         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6397             << FixItHint::CreateRemoval(
6398                    SourceRange(ArgExprs.front()->getBeginLoc(),
6399                                ArgExprs.back()->getEndLoc()));
6400       }
6401 
6402       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6403                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6404     }
6405     if (Fn->getType() == Context.PseudoObjectTy) {
6406       ExprResult result = CheckPlaceholderExpr(Fn);
6407       if (result.isInvalid()) return ExprError();
6408       Fn = result.get();
6409     }
6410 
6411     // Determine whether this is a dependent call inside a C++ template,
6412     // in which case we won't do any semantic analysis now.
6413     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6414       if (ExecConfig) {
6415         return CUDAKernelCallExpr::Create(
6416             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6417             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6418       } else {
6419 
6420         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6421             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6422             Fn->getBeginLoc());
6423 
6424         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6425                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6426       }
6427     }
6428 
6429     // Determine whether this is a call to an object (C++ [over.call.object]).
6430     if (Fn->getType()->isRecordType())
6431       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6432                                           RParenLoc);
6433 
6434     if (Fn->getType() == Context.UnknownAnyTy) {
6435       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6436       if (result.isInvalid()) return ExprError();
6437       Fn = result.get();
6438     }
6439 
6440     if (Fn->getType() == Context.BoundMemberTy) {
6441       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6442                                        RParenLoc, AllowRecovery);
6443     }
6444   }
6445 
6446   // Check for overloaded calls.  This can happen even in C due to extensions.
6447   if (Fn->getType() == Context.OverloadTy) {
6448     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6449 
6450     // We aren't supposed to apply this logic if there's an '&' involved.
6451     if (!find.HasFormOfMemberPointer) {
6452       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6453         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6454                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6455       OverloadExpr *ovl = find.Expression;
6456       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6457         return BuildOverloadedCallExpr(
6458             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6459             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6460       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6461                                        RParenLoc, AllowRecovery);
6462     }
6463   }
6464 
6465   // If we're directly calling a function, get the appropriate declaration.
6466   if (Fn->getType() == Context.UnknownAnyTy) {
6467     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6468     if (result.isInvalid()) return ExprError();
6469     Fn = result.get();
6470   }
6471 
6472   Expr *NakedFn = Fn->IgnoreParens();
6473 
6474   bool CallingNDeclIndirectly = false;
6475   NamedDecl *NDecl = nullptr;
6476   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6477     if (UnOp->getOpcode() == UO_AddrOf) {
6478       CallingNDeclIndirectly = true;
6479       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6480     }
6481   }
6482 
6483   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6484     NDecl = DRE->getDecl();
6485 
6486     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6487     if (FDecl && FDecl->getBuiltinID()) {
6488       // Rewrite the function decl for this builtin by replacing parameters
6489       // with no explicit address space with the address space of the arguments
6490       // in ArgExprs.
6491       if ((FDecl =
6492                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6493         NDecl = FDecl;
6494         Fn = DeclRefExpr::Create(
6495             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6496             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6497             nullptr, DRE->isNonOdrUse());
6498       }
6499     }
6500   } else if (isa<MemberExpr>(NakedFn))
6501     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6502 
6503   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6504     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6505                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6506       return ExprError();
6507 
6508     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6509       return ExprError();
6510 
6511     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6512   }
6513 
6514   if (Context.isDependenceAllowed() &&
6515       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6516     assert(!getLangOpts().CPlusPlus);
6517     assert((Fn->containsErrors() ||
6518             llvm::any_of(ArgExprs,
6519                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6520            "should only occur in error-recovery path.");
6521     QualType ReturnType =
6522         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6523             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6524             : Context.DependentTy;
6525     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6526                             Expr::getValueKindForType(ReturnType), RParenLoc,
6527                             CurFPFeatureOverrides());
6528   }
6529   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6530                                ExecConfig, IsExecConfig);
6531 }
6532 
6533 /// Parse a __builtin_astype expression.
6534 ///
6535 /// __builtin_astype( value, dst type )
6536 ///
6537 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6538                                  SourceLocation BuiltinLoc,
6539                                  SourceLocation RParenLoc) {
6540   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6541   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6542 }
6543 
6544 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6545 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6546                                  SourceLocation BuiltinLoc,
6547                                  SourceLocation RParenLoc) {
6548   ExprValueKind VK = VK_RValue;
6549   ExprObjectKind OK = OK_Ordinary;
6550   QualType SrcTy = E->getType();
6551   if (!SrcTy->isDependentType() &&
6552       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6553     return ExprError(
6554         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6555         << DestTy << SrcTy << E->getSourceRange());
6556   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6557 }
6558 
6559 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6560 /// provided arguments.
6561 ///
6562 /// __builtin_convertvector( value, dst type )
6563 ///
6564 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6565                                         SourceLocation BuiltinLoc,
6566                                         SourceLocation RParenLoc) {
6567   TypeSourceInfo *TInfo;
6568   GetTypeFromParser(ParsedDestTy, &TInfo);
6569   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6570 }
6571 
6572 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6573 /// i.e. an expression not of \p OverloadTy.  The expression should
6574 /// unary-convert to an expression of function-pointer or
6575 /// block-pointer type.
6576 ///
6577 /// \param NDecl the declaration being called, if available
6578 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6579                                        SourceLocation LParenLoc,
6580                                        ArrayRef<Expr *> Args,
6581                                        SourceLocation RParenLoc, Expr *Config,
6582                                        bool IsExecConfig, ADLCallKind UsesADL) {
6583   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6584   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6585 
6586   // Functions with 'interrupt' attribute cannot be called directly.
6587   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6588     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6589     return ExprError();
6590   }
6591 
6592   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6593   // so there's some risk when calling out to non-interrupt handler functions
6594   // that the callee might not preserve them. This is easy to diagnose here,
6595   // but can be very challenging to debug.
6596   // Likewise, X86 interrupt handlers may only call routines with attribute
6597   // no_caller_saved_registers since there is no efficient way to
6598   // save and restore the non-GPR state.
6599   if (auto *Caller = getCurFunctionDecl()) {
6600     if (Caller->hasAttr<ARMInterruptAttr>()) {
6601       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6602       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6603         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6604         if (FDecl)
6605           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6606       }
6607     }
6608     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6609         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6610       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6611       if (FDecl)
6612         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6613     }
6614   }
6615 
6616   // Promote the function operand.
6617   // We special-case function promotion here because we only allow promoting
6618   // builtin functions to function pointers in the callee of a call.
6619   ExprResult Result;
6620   QualType ResultTy;
6621   if (BuiltinID &&
6622       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6623     // Extract the return type from the (builtin) function pointer type.
6624     // FIXME Several builtins still have setType in
6625     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6626     // Builtins.def to ensure they are correct before removing setType calls.
6627     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6628     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6629     ResultTy = FDecl->getCallResultType();
6630   } else {
6631     Result = CallExprUnaryConversions(Fn);
6632     ResultTy = Context.BoolTy;
6633   }
6634   if (Result.isInvalid())
6635     return ExprError();
6636   Fn = Result.get();
6637 
6638   // Check for a valid function type, but only if it is not a builtin which
6639   // requires custom type checking. These will be handled by
6640   // CheckBuiltinFunctionCall below just after creation of the call expression.
6641   const FunctionType *FuncT = nullptr;
6642   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6643   retry:
6644     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6645       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6646       // have type pointer to function".
6647       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6648       if (!FuncT)
6649         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6650                          << Fn->getType() << Fn->getSourceRange());
6651     } else if (const BlockPointerType *BPT =
6652                    Fn->getType()->getAs<BlockPointerType>()) {
6653       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6654     } else {
6655       // Handle calls to expressions of unknown-any type.
6656       if (Fn->getType() == Context.UnknownAnyTy) {
6657         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6658         if (rewrite.isInvalid())
6659           return ExprError();
6660         Fn = rewrite.get();
6661         goto retry;
6662       }
6663 
6664       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6665                        << Fn->getType() << Fn->getSourceRange());
6666     }
6667   }
6668 
6669   // Get the number of parameters in the function prototype, if any.
6670   // We will allocate space for max(Args.size(), NumParams) arguments
6671   // in the call expression.
6672   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6673   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6674 
6675   CallExpr *TheCall;
6676   if (Config) {
6677     assert(UsesADL == ADLCallKind::NotADL &&
6678            "CUDAKernelCallExpr should not use ADL");
6679     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6680                                          Args, ResultTy, VK_RValue, RParenLoc,
6681                                          CurFPFeatureOverrides(), NumParams);
6682   } else {
6683     TheCall =
6684         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6685                          CurFPFeatureOverrides(), NumParams, UsesADL);
6686   }
6687 
6688   if (!Context.isDependenceAllowed()) {
6689     // Forget about the nulled arguments since typo correction
6690     // do not handle them well.
6691     TheCall->shrinkNumArgs(Args.size());
6692     // C cannot always handle TypoExpr nodes in builtin calls and direct
6693     // function calls as their argument checking don't necessarily handle
6694     // dependent types properly, so make sure any TypoExprs have been
6695     // dealt with.
6696     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6697     if (!Result.isUsable()) return ExprError();
6698     CallExpr *TheOldCall = TheCall;
6699     TheCall = dyn_cast<CallExpr>(Result.get());
6700     bool CorrectedTypos = TheCall != TheOldCall;
6701     if (!TheCall) return Result;
6702     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6703 
6704     // A new call expression node was created if some typos were corrected.
6705     // However it may not have been constructed with enough storage. In this
6706     // case, rebuild the node with enough storage. The waste of space is
6707     // immaterial since this only happens when some typos were corrected.
6708     if (CorrectedTypos && Args.size() < NumParams) {
6709       if (Config)
6710         TheCall = CUDAKernelCallExpr::Create(
6711             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6712             RParenLoc, CurFPFeatureOverrides(), NumParams);
6713       else
6714         TheCall =
6715             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6716                              CurFPFeatureOverrides(), NumParams, UsesADL);
6717     }
6718     // We can now handle the nulled arguments for the default arguments.
6719     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6720   }
6721 
6722   // Bail out early if calling a builtin with custom type checking.
6723   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6724     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6725 
6726   if (getLangOpts().CUDA) {
6727     if (Config) {
6728       // CUDA: Kernel calls must be to global functions
6729       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6730         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6731             << FDecl << Fn->getSourceRange());
6732 
6733       // CUDA: Kernel function must have 'void' return type
6734       if (!FuncT->getReturnType()->isVoidType() &&
6735           !FuncT->getReturnType()->getAs<AutoType>() &&
6736           !FuncT->getReturnType()->isInstantiationDependentType())
6737         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6738             << Fn->getType() << Fn->getSourceRange());
6739     } else {
6740       // CUDA: Calls to global functions must be configured
6741       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6742         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6743             << FDecl << Fn->getSourceRange());
6744     }
6745   }
6746 
6747   // Check for a valid return type
6748   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6749                           FDecl))
6750     return ExprError();
6751 
6752   // We know the result type of the call, set it.
6753   TheCall->setType(FuncT->getCallResultType(Context));
6754   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6755 
6756   if (Proto) {
6757     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6758                                 IsExecConfig))
6759       return ExprError();
6760   } else {
6761     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6762 
6763     if (FDecl) {
6764       // Check if we have too few/too many template arguments, based
6765       // on our knowledge of the function definition.
6766       const FunctionDecl *Def = nullptr;
6767       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6768         Proto = Def->getType()->getAs<FunctionProtoType>();
6769        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6770           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6771           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6772       }
6773 
6774       // If the function we're calling isn't a function prototype, but we have
6775       // a function prototype from a prior declaratiom, use that prototype.
6776       if (!FDecl->hasPrototype())
6777         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6778     }
6779 
6780     // Promote the arguments (C99 6.5.2.2p6).
6781     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6782       Expr *Arg = Args[i];
6783 
6784       if (Proto && i < Proto->getNumParams()) {
6785         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6786             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6787         ExprResult ArgE =
6788             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6789         if (ArgE.isInvalid())
6790           return true;
6791 
6792         Arg = ArgE.getAs<Expr>();
6793 
6794       } else {
6795         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6796 
6797         if (ArgE.isInvalid())
6798           return true;
6799 
6800         Arg = ArgE.getAs<Expr>();
6801       }
6802 
6803       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6804                               diag::err_call_incomplete_argument, Arg))
6805         return ExprError();
6806 
6807       TheCall->setArg(i, Arg);
6808     }
6809   }
6810 
6811   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6812     if (!Method->isStatic())
6813       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6814         << Fn->getSourceRange());
6815 
6816   // Check for sentinels
6817   if (NDecl)
6818     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6819 
6820   // Warn for unions passing across security boundary (CMSE).
6821   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6822     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6823       if (const auto *RT =
6824               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6825         if (RT->getDecl()->isOrContainsUnion())
6826           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6827               << 0 << i;
6828       }
6829     }
6830   }
6831 
6832   // Do special checking on direct calls to functions.
6833   if (FDecl) {
6834     if (CheckFunctionCall(FDecl, TheCall, Proto))
6835       return ExprError();
6836 
6837     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6838 
6839     if (BuiltinID)
6840       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6841   } else if (NDecl) {
6842     if (CheckPointerCall(NDecl, TheCall, Proto))
6843       return ExprError();
6844   } else {
6845     if (CheckOtherCall(TheCall, Proto))
6846       return ExprError();
6847   }
6848 
6849   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6850 }
6851 
6852 ExprResult
6853 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6854                            SourceLocation RParenLoc, Expr *InitExpr) {
6855   assert(Ty && "ActOnCompoundLiteral(): missing type");
6856   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6857 
6858   TypeSourceInfo *TInfo;
6859   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6860   if (!TInfo)
6861     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6862 
6863   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6864 }
6865 
6866 ExprResult
6867 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6868                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6869   QualType literalType = TInfo->getType();
6870 
6871   if (literalType->isArrayType()) {
6872     if (RequireCompleteSizedType(
6873             LParenLoc, Context.getBaseElementType(literalType),
6874             diag::err_array_incomplete_or_sizeless_type,
6875             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6876       return ExprError();
6877     if (literalType->isVariableArrayType()) {
6878       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6879                                            diag::err_variable_object_no_init)) {
6880         return ExprError();
6881       }
6882     }
6883   } else if (!literalType->isDependentType() &&
6884              RequireCompleteType(LParenLoc, literalType,
6885                diag::err_typecheck_decl_incomplete_type,
6886                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6887     return ExprError();
6888 
6889   InitializedEntity Entity
6890     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6891   InitializationKind Kind
6892     = InitializationKind::CreateCStyleCast(LParenLoc,
6893                                            SourceRange(LParenLoc, RParenLoc),
6894                                            /*InitList=*/true);
6895   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6896   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6897                                       &literalType);
6898   if (Result.isInvalid())
6899     return ExprError();
6900   LiteralExpr = Result.get();
6901 
6902   bool isFileScope = !CurContext->isFunctionOrMethod();
6903 
6904   // In C, compound literals are l-values for some reason.
6905   // For GCC compatibility, in C++, file-scope array compound literals with
6906   // constant initializers are also l-values, and compound literals are
6907   // otherwise prvalues.
6908   //
6909   // (GCC also treats C++ list-initialized file-scope array prvalues with
6910   // constant initializers as l-values, but that's non-conforming, so we don't
6911   // follow it there.)
6912   //
6913   // FIXME: It would be better to handle the lvalue cases as materializing and
6914   // lifetime-extending a temporary object, but our materialized temporaries
6915   // representation only supports lifetime extension from a variable, not "out
6916   // of thin air".
6917   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6918   // is bound to the result of applying array-to-pointer decay to the compound
6919   // literal.
6920   // FIXME: GCC supports compound literals of reference type, which should
6921   // obviously have a value kind derived from the kind of reference involved.
6922   ExprValueKind VK =
6923       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6924           ? VK_RValue
6925           : VK_LValue;
6926 
6927   if (isFileScope)
6928     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6929       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6930         Expr *Init = ILE->getInit(i);
6931         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6932       }
6933 
6934   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6935                                               VK, LiteralExpr, isFileScope);
6936   if (isFileScope) {
6937     if (!LiteralExpr->isTypeDependent() &&
6938         !LiteralExpr->isValueDependent() &&
6939         !literalType->isDependentType()) // C99 6.5.2.5p3
6940       if (CheckForConstantInitializer(LiteralExpr, literalType))
6941         return ExprError();
6942   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6943              literalType.getAddressSpace() != LangAS::Default) {
6944     // Embedded-C extensions to C99 6.5.2.5:
6945     //   "If the compound literal occurs inside the body of a function, the
6946     //   type name shall not be qualified by an address-space qualifier."
6947     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6948       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6949     return ExprError();
6950   }
6951 
6952   if (!isFileScope && !getLangOpts().CPlusPlus) {
6953     // Compound literals that have automatic storage duration are destroyed at
6954     // the end of the scope in C; in C++, they're just temporaries.
6955 
6956     // Emit diagnostics if it is or contains a C union type that is non-trivial
6957     // to destruct.
6958     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6959       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6960                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6961 
6962     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6963     if (literalType.isDestructedType()) {
6964       Cleanup.setExprNeedsCleanups(true);
6965       ExprCleanupObjects.push_back(E);
6966       getCurFunction()->setHasBranchProtectedScope();
6967     }
6968   }
6969 
6970   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6971       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6972     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6973                                        E->getInitializer()->getExprLoc());
6974 
6975   return MaybeBindToTemporary(E);
6976 }
6977 
6978 ExprResult
6979 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6980                     SourceLocation RBraceLoc) {
6981   // Only produce each kind of designated initialization diagnostic once.
6982   SourceLocation FirstDesignator;
6983   bool DiagnosedArrayDesignator = false;
6984   bool DiagnosedNestedDesignator = false;
6985   bool DiagnosedMixedDesignator = false;
6986 
6987   // Check that any designated initializers are syntactically valid in the
6988   // current language mode.
6989   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6990     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6991       if (FirstDesignator.isInvalid())
6992         FirstDesignator = DIE->getBeginLoc();
6993 
6994       if (!getLangOpts().CPlusPlus)
6995         break;
6996 
6997       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6998         DiagnosedNestedDesignator = true;
6999         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7000           << DIE->getDesignatorsSourceRange();
7001       }
7002 
7003       for (auto &Desig : DIE->designators()) {
7004         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7005           DiagnosedArrayDesignator = true;
7006           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7007             << Desig.getSourceRange();
7008         }
7009       }
7010 
7011       if (!DiagnosedMixedDesignator &&
7012           !isa<DesignatedInitExpr>(InitArgList[0])) {
7013         DiagnosedMixedDesignator = true;
7014         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7015           << DIE->getSourceRange();
7016         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7017           << InitArgList[0]->getSourceRange();
7018       }
7019     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7020                isa<DesignatedInitExpr>(InitArgList[0])) {
7021       DiagnosedMixedDesignator = true;
7022       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7023       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7024         << DIE->getSourceRange();
7025       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7026         << InitArgList[I]->getSourceRange();
7027     }
7028   }
7029 
7030   if (FirstDesignator.isValid()) {
7031     // Only diagnose designated initiaization as a C++20 extension if we didn't
7032     // already diagnose use of (non-C++20) C99 designator syntax.
7033     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7034         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7035       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7036                                 ? diag::warn_cxx17_compat_designated_init
7037                                 : diag::ext_cxx_designated_init);
7038     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7039       Diag(FirstDesignator, diag::ext_designated_init);
7040     }
7041   }
7042 
7043   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7044 }
7045 
7046 ExprResult
7047 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7048                     SourceLocation RBraceLoc) {
7049   // Semantic analysis for initializers is done by ActOnDeclarator() and
7050   // CheckInitializer() - it requires knowledge of the object being initialized.
7051 
7052   // Immediately handle non-overload placeholders.  Overloads can be
7053   // resolved contextually, but everything else here can't.
7054   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7055     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7056       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7057 
7058       // Ignore failures; dropping the entire initializer list because
7059       // of one failure would be terrible for indexing/etc.
7060       if (result.isInvalid()) continue;
7061 
7062       InitArgList[I] = result.get();
7063     }
7064   }
7065 
7066   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7067                                                RBraceLoc);
7068   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7069   return E;
7070 }
7071 
7072 /// Do an explicit extend of the given block pointer if we're in ARC.
7073 void Sema::maybeExtendBlockObject(ExprResult &E) {
7074   assert(E.get()->getType()->isBlockPointerType());
7075   assert(E.get()->isRValue());
7076 
7077   // Only do this in an r-value context.
7078   if (!getLangOpts().ObjCAutoRefCount) return;
7079 
7080   E = ImplicitCastExpr::Create(
7081       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7082       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7083   Cleanup.setExprNeedsCleanups(true);
7084 }
7085 
7086 /// Prepare a conversion of the given expression to an ObjC object
7087 /// pointer type.
7088 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7089   QualType type = E.get()->getType();
7090   if (type->isObjCObjectPointerType()) {
7091     return CK_BitCast;
7092   } else if (type->isBlockPointerType()) {
7093     maybeExtendBlockObject(E);
7094     return CK_BlockPointerToObjCPointerCast;
7095   } else {
7096     assert(type->isPointerType());
7097     return CK_CPointerToObjCPointerCast;
7098   }
7099 }
7100 
7101 /// Prepares for a scalar cast, performing all the necessary stages
7102 /// except the final cast and returning the kind required.
7103 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7104   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7105   // Also, callers should have filtered out the invalid cases with
7106   // pointers.  Everything else should be possible.
7107 
7108   QualType SrcTy = Src.get()->getType();
7109   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7110     return CK_NoOp;
7111 
7112   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7113   case Type::STK_MemberPointer:
7114     llvm_unreachable("member pointer type in C");
7115 
7116   case Type::STK_CPointer:
7117   case Type::STK_BlockPointer:
7118   case Type::STK_ObjCObjectPointer:
7119     switch (DestTy->getScalarTypeKind()) {
7120     case Type::STK_CPointer: {
7121       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7122       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7123       if (SrcAS != DestAS)
7124         return CK_AddressSpaceConversion;
7125       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7126         return CK_NoOp;
7127       return CK_BitCast;
7128     }
7129     case Type::STK_BlockPointer:
7130       return (SrcKind == Type::STK_BlockPointer
7131                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7132     case Type::STK_ObjCObjectPointer:
7133       if (SrcKind == Type::STK_ObjCObjectPointer)
7134         return CK_BitCast;
7135       if (SrcKind == Type::STK_CPointer)
7136         return CK_CPointerToObjCPointerCast;
7137       maybeExtendBlockObject(Src);
7138       return CK_BlockPointerToObjCPointerCast;
7139     case Type::STK_Bool:
7140       return CK_PointerToBoolean;
7141     case Type::STK_Integral:
7142       return CK_PointerToIntegral;
7143     case Type::STK_Floating:
7144     case Type::STK_FloatingComplex:
7145     case Type::STK_IntegralComplex:
7146     case Type::STK_MemberPointer:
7147     case Type::STK_FixedPoint:
7148       llvm_unreachable("illegal cast from pointer");
7149     }
7150     llvm_unreachable("Should have returned before this");
7151 
7152   case Type::STK_FixedPoint:
7153     switch (DestTy->getScalarTypeKind()) {
7154     case Type::STK_FixedPoint:
7155       return CK_FixedPointCast;
7156     case Type::STK_Bool:
7157       return CK_FixedPointToBoolean;
7158     case Type::STK_Integral:
7159       return CK_FixedPointToIntegral;
7160     case Type::STK_Floating:
7161       return CK_FixedPointToFloating;
7162     case Type::STK_IntegralComplex:
7163     case Type::STK_FloatingComplex:
7164       Diag(Src.get()->getExprLoc(),
7165            diag::err_unimplemented_conversion_with_fixed_point_type)
7166           << DestTy;
7167       return CK_IntegralCast;
7168     case Type::STK_CPointer:
7169     case Type::STK_ObjCObjectPointer:
7170     case Type::STK_BlockPointer:
7171     case Type::STK_MemberPointer:
7172       llvm_unreachable("illegal cast to pointer type");
7173     }
7174     llvm_unreachable("Should have returned before this");
7175 
7176   case Type::STK_Bool: // casting from bool is like casting from an integer
7177   case Type::STK_Integral:
7178     switch (DestTy->getScalarTypeKind()) {
7179     case Type::STK_CPointer:
7180     case Type::STK_ObjCObjectPointer:
7181     case Type::STK_BlockPointer:
7182       if (Src.get()->isNullPointerConstant(Context,
7183                                            Expr::NPC_ValueDependentIsNull))
7184         return CK_NullToPointer;
7185       return CK_IntegralToPointer;
7186     case Type::STK_Bool:
7187       return CK_IntegralToBoolean;
7188     case Type::STK_Integral:
7189       return CK_IntegralCast;
7190     case Type::STK_Floating:
7191       return CK_IntegralToFloating;
7192     case Type::STK_IntegralComplex:
7193       Src = ImpCastExprToType(Src.get(),
7194                       DestTy->castAs<ComplexType>()->getElementType(),
7195                       CK_IntegralCast);
7196       return CK_IntegralRealToComplex;
7197     case Type::STK_FloatingComplex:
7198       Src = ImpCastExprToType(Src.get(),
7199                       DestTy->castAs<ComplexType>()->getElementType(),
7200                       CK_IntegralToFloating);
7201       return CK_FloatingRealToComplex;
7202     case Type::STK_MemberPointer:
7203       llvm_unreachable("member pointer type in C");
7204     case Type::STK_FixedPoint:
7205       return CK_IntegralToFixedPoint;
7206     }
7207     llvm_unreachable("Should have returned before this");
7208 
7209   case Type::STK_Floating:
7210     switch (DestTy->getScalarTypeKind()) {
7211     case Type::STK_Floating:
7212       return CK_FloatingCast;
7213     case Type::STK_Bool:
7214       return CK_FloatingToBoolean;
7215     case Type::STK_Integral:
7216       return CK_FloatingToIntegral;
7217     case Type::STK_FloatingComplex:
7218       Src = ImpCastExprToType(Src.get(),
7219                               DestTy->castAs<ComplexType>()->getElementType(),
7220                               CK_FloatingCast);
7221       return CK_FloatingRealToComplex;
7222     case Type::STK_IntegralComplex:
7223       Src = ImpCastExprToType(Src.get(),
7224                               DestTy->castAs<ComplexType>()->getElementType(),
7225                               CK_FloatingToIntegral);
7226       return CK_IntegralRealToComplex;
7227     case Type::STK_CPointer:
7228     case Type::STK_ObjCObjectPointer:
7229     case Type::STK_BlockPointer:
7230       llvm_unreachable("valid float->pointer cast?");
7231     case Type::STK_MemberPointer:
7232       llvm_unreachable("member pointer type in C");
7233     case Type::STK_FixedPoint:
7234       return CK_FloatingToFixedPoint;
7235     }
7236     llvm_unreachable("Should have returned before this");
7237 
7238   case Type::STK_FloatingComplex:
7239     switch (DestTy->getScalarTypeKind()) {
7240     case Type::STK_FloatingComplex:
7241       return CK_FloatingComplexCast;
7242     case Type::STK_IntegralComplex:
7243       return CK_FloatingComplexToIntegralComplex;
7244     case Type::STK_Floating: {
7245       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7246       if (Context.hasSameType(ET, DestTy))
7247         return CK_FloatingComplexToReal;
7248       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7249       return CK_FloatingCast;
7250     }
7251     case Type::STK_Bool:
7252       return CK_FloatingComplexToBoolean;
7253     case Type::STK_Integral:
7254       Src = ImpCastExprToType(Src.get(),
7255                               SrcTy->castAs<ComplexType>()->getElementType(),
7256                               CK_FloatingComplexToReal);
7257       return CK_FloatingToIntegral;
7258     case Type::STK_CPointer:
7259     case Type::STK_ObjCObjectPointer:
7260     case Type::STK_BlockPointer:
7261       llvm_unreachable("valid complex float->pointer cast?");
7262     case Type::STK_MemberPointer:
7263       llvm_unreachable("member pointer type in C");
7264     case Type::STK_FixedPoint:
7265       Diag(Src.get()->getExprLoc(),
7266            diag::err_unimplemented_conversion_with_fixed_point_type)
7267           << SrcTy;
7268       return CK_IntegralCast;
7269     }
7270     llvm_unreachable("Should have returned before this");
7271 
7272   case Type::STK_IntegralComplex:
7273     switch (DestTy->getScalarTypeKind()) {
7274     case Type::STK_FloatingComplex:
7275       return CK_IntegralComplexToFloatingComplex;
7276     case Type::STK_IntegralComplex:
7277       return CK_IntegralComplexCast;
7278     case Type::STK_Integral: {
7279       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7280       if (Context.hasSameType(ET, DestTy))
7281         return CK_IntegralComplexToReal;
7282       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7283       return CK_IntegralCast;
7284     }
7285     case Type::STK_Bool:
7286       return CK_IntegralComplexToBoolean;
7287     case Type::STK_Floating:
7288       Src = ImpCastExprToType(Src.get(),
7289                               SrcTy->castAs<ComplexType>()->getElementType(),
7290                               CK_IntegralComplexToReal);
7291       return CK_IntegralToFloating;
7292     case Type::STK_CPointer:
7293     case Type::STK_ObjCObjectPointer:
7294     case Type::STK_BlockPointer:
7295       llvm_unreachable("valid complex int->pointer cast?");
7296     case Type::STK_MemberPointer:
7297       llvm_unreachable("member pointer type in C");
7298     case Type::STK_FixedPoint:
7299       Diag(Src.get()->getExprLoc(),
7300            diag::err_unimplemented_conversion_with_fixed_point_type)
7301           << SrcTy;
7302       return CK_IntegralCast;
7303     }
7304     llvm_unreachable("Should have returned before this");
7305   }
7306 
7307   llvm_unreachable("Unhandled scalar cast");
7308 }
7309 
7310 static bool breakDownVectorType(QualType type, uint64_t &len,
7311                                 QualType &eltType) {
7312   // Vectors are simple.
7313   if (const VectorType *vecType = type->getAs<VectorType>()) {
7314     len = vecType->getNumElements();
7315     eltType = vecType->getElementType();
7316     assert(eltType->isScalarType());
7317     return true;
7318   }
7319 
7320   // We allow lax conversion to and from non-vector types, but only if
7321   // they're real types (i.e. non-complex, non-pointer scalar types).
7322   if (!type->isRealType()) return false;
7323 
7324   len = 1;
7325   eltType = type;
7326   return true;
7327 }
7328 
7329 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7330 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7331 /// allowed?
7332 ///
7333 /// This will also return false if the two given types do not make sense from
7334 /// the perspective of SVE bitcasts.
7335 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7336   assert(srcTy->isVectorType() || destTy->isVectorType());
7337 
7338   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7339     if (!FirstType->isSizelessBuiltinType())
7340       return false;
7341 
7342     const auto *VecTy = SecondType->getAs<VectorType>();
7343     return VecTy &&
7344            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7345   };
7346 
7347   return ValidScalableConversion(srcTy, destTy) ||
7348          ValidScalableConversion(destTy, srcTy);
7349 }
7350 
7351 /// Are the two types matrix types and do they have the same dimensions i.e.
7352 /// do they have the same number of rows and the same number of columns?
7353 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7354   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7355     return false;
7356 
7357   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7358   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7359 
7360   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7361          matSrcType->getNumColumns() == matDestType->getNumColumns();
7362 }
7363 
7364 /// Are the two types lax-compatible vector types?  That is, given
7365 /// that one of them is a vector, do they have equal storage sizes,
7366 /// where the storage size is the number of elements times the element
7367 /// size?
7368 ///
7369 /// This will also return false if either of the types is neither a
7370 /// vector nor a real type.
7371 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7372   assert(destTy->isVectorType() || srcTy->isVectorType());
7373 
7374   // Disallow lax conversions between scalars and ExtVectors (these
7375   // conversions are allowed for other vector types because common headers
7376   // depend on them).  Most scalar OP ExtVector cases are handled by the
7377   // splat path anyway, which does what we want (convert, not bitcast).
7378   // What this rules out for ExtVectors is crazy things like char4*float.
7379   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7380   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7381 
7382   uint64_t srcLen, destLen;
7383   QualType srcEltTy, destEltTy;
7384   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7385   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7386 
7387   // ASTContext::getTypeSize will return the size rounded up to a
7388   // power of 2, so instead of using that, we need to use the raw
7389   // element size multiplied by the element count.
7390   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7391   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7392 
7393   return (srcLen * srcEltSize == destLen * destEltSize);
7394 }
7395 
7396 /// Is this a legal conversion between two types, one of which is
7397 /// known to be a vector type?
7398 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7399   assert(destTy->isVectorType() || srcTy->isVectorType());
7400 
7401   switch (Context.getLangOpts().getLaxVectorConversions()) {
7402   case LangOptions::LaxVectorConversionKind::None:
7403     return false;
7404 
7405   case LangOptions::LaxVectorConversionKind::Integer:
7406     if (!srcTy->isIntegralOrEnumerationType()) {
7407       auto *Vec = srcTy->getAs<VectorType>();
7408       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7409         return false;
7410     }
7411     if (!destTy->isIntegralOrEnumerationType()) {
7412       auto *Vec = destTy->getAs<VectorType>();
7413       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7414         return false;
7415     }
7416     // OK, integer (vector) -> integer (vector) bitcast.
7417     break;
7418 
7419     case LangOptions::LaxVectorConversionKind::All:
7420     break;
7421   }
7422 
7423   return areLaxCompatibleVectorTypes(srcTy, destTy);
7424 }
7425 
7426 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7427                            CastKind &Kind) {
7428   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7429     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7430       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7431              << DestTy << SrcTy << R;
7432     }
7433   } else if (SrcTy->isMatrixType()) {
7434     return Diag(R.getBegin(),
7435                 diag::err_invalid_conversion_between_matrix_and_type)
7436            << SrcTy << DestTy << R;
7437   } else if (DestTy->isMatrixType()) {
7438     return Diag(R.getBegin(),
7439                 diag::err_invalid_conversion_between_matrix_and_type)
7440            << DestTy << SrcTy << R;
7441   }
7442 
7443   Kind = CK_MatrixCast;
7444   return false;
7445 }
7446 
7447 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7448                            CastKind &Kind) {
7449   assert(VectorTy->isVectorType() && "Not a vector type!");
7450 
7451   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7452     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7453       return Diag(R.getBegin(),
7454                   Ty->isVectorType() ?
7455                   diag::err_invalid_conversion_between_vectors :
7456                   diag::err_invalid_conversion_between_vector_and_integer)
7457         << VectorTy << Ty << R;
7458   } else
7459     return Diag(R.getBegin(),
7460                 diag::err_invalid_conversion_between_vector_and_scalar)
7461       << VectorTy << Ty << R;
7462 
7463   Kind = CK_BitCast;
7464   return false;
7465 }
7466 
7467 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7468   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7469 
7470   if (DestElemTy == SplattedExpr->getType())
7471     return SplattedExpr;
7472 
7473   assert(DestElemTy->isFloatingType() ||
7474          DestElemTy->isIntegralOrEnumerationType());
7475 
7476   CastKind CK;
7477   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7478     // OpenCL requires that we convert `true` boolean expressions to -1, but
7479     // only when splatting vectors.
7480     if (DestElemTy->isFloatingType()) {
7481       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7482       // in two steps: boolean to signed integral, then to floating.
7483       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7484                                                  CK_BooleanToSignedIntegral);
7485       SplattedExpr = CastExprRes.get();
7486       CK = CK_IntegralToFloating;
7487     } else {
7488       CK = CK_BooleanToSignedIntegral;
7489     }
7490   } else {
7491     ExprResult CastExprRes = SplattedExpr;
7492     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7493     if (CastExprRes.isInvalid())
7494       return ExprError();
7495     SplattedExpr = CastExprRes.get();
7496   }
7497   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7498 }
7499 
7500 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7501                                     Expr *CastExpr, CastKind &Kind) {
7502   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7503 
7504   QualType SrcTy = CastExpr->getType();
7505 
7506   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7507   // an ExtVectorType.
7508   // In OpenCL, casts between vectors of different types are not allowed.
7509   // (See OpenCL 6.2).
7510   if (SrcTy->isVectorType()) {
7511     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7512         (getLangOpts().OpenCL &&
7513          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7514       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7515         << DestTy << SrcTy << R;
7516       return ExprError();
7517     }
7518     Kind = CK_BitCast;
7519     return CastExpr;
7520   }
7521 
7522   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7523   // conversion will take place first from scalar to elt type, and then
7524   // splat from elt type to vector.
7525   if (SrcTy->isPointerType())
7526     return Diag(R.getBegin(),
7527                 diag::err_invalid_conversion_between_vector_and_scalar)
7528       << DestTy << SrcTy << R;
7529 
7530   Kind = CK_VectorSplat;
7531   return prepareVectorSplat(DestTy, CastExpr);
7532 }
7533 
7534 ExprResult
7535 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7536                     Declarator &D, ParsedType &Ty,
7537                     SourceLocation RParenLoc, Expr *CastExpr) {
7538   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7539          "ActOnCastExpr(): missing type or expr");
7540 
7541   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7542   if (D.isInvalidType())
7543     return ExprError();
7544 
7545   if (getLangOpts().CPlusPlus) {
7546     // Check that there are no default arguments (C++ only).
7547     CheckExtraCXXDefaultArguments(D);
7548   } else {
7549     // Make sure any TypoExprs have been dealt with.
7550     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7551     if (!Res.isUsable())
7552       return ExprError();
7553     CastExpr = Res.get();
7554   }
7555 
7556   checkUnusedDeclAttributes(D);
7557 
7558   QualType castType = castTInfo->getType();
7559   Ty = CreateParsedType(castType, castTInfo);
7560 
7561   bool isVectorLiteral = false;
7562 
7563   // Check for an altivec or OpenCL literal,
7564   // i.e. all the elements are integer constants.
7565   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7566   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7567   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7568        && castType->isVectorType() && (PE || PLE)) {
7569     if (PLE && PLE->getNumExprs() == 0) {
7570       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7571       return ExprError();
7572     }
7573     if (PE || PLE->getNumExprs() == 1) {
7574       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7575       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7576         isVectorLiteral = true;
7577     }
7578     else
7579       isVectorLiteral = true;
7580   }
7581 
7582   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7583   // then handle it as such.
7584   if (isVectorLiteral)
7585     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7586 
7587   // If the Expr being casted is a ParenListExpr, handle it specially.
7588   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7589   // sequence of BinOp comma operators.
7590   if (isa<ParenListExpr>(CastExpr)) {
7591     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7592     if (Result.isInvalid()) return ExprError();
7593     CastExpr = Result.get();
7594   }
7595 
7596   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7597       !getSourceManager().isInSystemMacro(LParenLoc))
7598     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7599 
7600   CheckTollFreeBridgeCast(castType, CastExpr);
7601 
7602   CheckObjCBridgeRelatedCast(castType, CastExpr);
7603 
7604   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7605 
7606   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7607 }
7608 
7609 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7610                                     SourceLocation RParenLoc, Expr *E,
7611                                     TypeSourceInfo *TInfo) {
7612   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7613          "Expected paren or paren list expression");
7614 
7615   Expr **exprs;
7616   unsigned numExprs;
7617   Expr *subExpr;
7618   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7619   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7620     LiteralLParenLoc = PE->getLParenLoc();
7621     LiteralRParenLoc = PE->getRParenLoc();
7622     exprs = PE->getExprs();
7623     numExprs = PE->getNumExprs();
7624   } else { // isa<ParenExpr> by assertion at function entrance
7625     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7626     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7627     subExpr = cast<ParenExpr>(E)->getSubExpr();
7628     exprs = &subExpr;
7629     numExprs = 1;
7630   }
7631 
7632   QualType Ty = TInfo->getType();
7633   assert(Ty->isVectorType() && "Expected vector type");
7634 
7635   SmallVector<Expr *, 8> initExprs;
7636   const VectorType *VTy = Ty->castAs<VectorType>();
7637   unsigned numElems = VTy->getNumElements();
7638 
7639   // '(...)' form of vector initialization in AltiVec: the number of
7640   // initializers must be one or must match the size of the vector.
7641   // If a single value is specified in the initializer then it will be
7642   // replicated to all the components of the vector
7643   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7644     // The number of initializers must be one or must match the size of the
7645     // vector. If a single value is specified in the initializer then it will
7646     // be replicated to all the components of the vector
7647     if (numExprs == 1) {
7648       QualType ElemTy = VTy->getElementType();
7649       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7650       if (Literal.isInvalid())
7651         return ExprError();
7652       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7653                                   PrepareScalarCast(Literal, ElemTy));
7654       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7655     }
7656     else if (numExprs < numElems) {
7657       Diag(E->getExprLoc(),
7658            diag::err_incorrect_number_of_vector_initializers);
7659       return ExprError();
7660     }
7661     else
7662       initExprs.append(exprs, exprs + numExprs);
7663   }
7664   else {
7665     // For OpenCL, when the number of initializers is a single value,
7666     // it will be replicated to all components of the vector.
7667     if (getLangOpts().OpenCL &&
7668         VTy->getVectorKind() == VectorType::GenericVector &&
7669         numExprs == 1) {
7670         QualType ElemTy = VTy->getElementType();
7671         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7672         if (Literal.isInvalid())
7673           return ExprError();
7674         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7675                                     PrepareScalarCast(Literal, ElemTy));
7676         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7677     }
7678 
7679     initExprs.append(exprs, exprs + numExprs);
7680   }
7681   // FIXME: This means that pretty-printing the final AST will produce curly
7682   // braces instead of the original commas.
7683   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7684                                                    initExprs, LiteralRParenLoc);
7685   initE->setType(Ty);
7686   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7687 }
7688 
7689 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7690 /// the ParenListExpr into a sequence of comma binary operators.
7691 ExprResult
7692 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7693   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7694   if (!E)
7695     return OrigExpr;
7696 
7697   ExprResult Result(E->getExpr(0));
7698 
7699   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7700     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7701                         E->getExpr(i));
7702 
7703   if (Result.isInvalid()) return ExprError();
7704 
7705   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7706 }
7707 
7708 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7709                                     SourceLocation R,
7710                                     MultiExprArg Val) {
7711   return ParenListExpr::Create(Context, L, Val, R);
7712 }
7713 
7714 /// Emit a specialized diagnostic when one expression is a null pointer
7715 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7716 /// emitted.
7717 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7718                                       SourceLocation QuestionLoc) {
7719   Expr *NullExpr = LHSExpr;
7720   Expr *NonPointerExpr = RHSExpr;
7721   Expr::NullPointerConstantKind NullKind =
7722       NullExpr->isNullPointerConstant(Context,
7723                                       Expr::NPC_ValueDependentIsNotNull);
7724 
7725   if (NullKind == Expr::NPCK_NotNull) {
7726     NullExpr = RHSExpr;
7727     NonPointerExpr = LHSExpr;
7728     NullKind =
7729         NullExpr->isNullPointerConstant(Context,
7730                                         Expr::NPC_ValueDependentIsNotNull);
7731   }
7732 
7733   if (NullKind == Expr::NPCK_NotNull)
7734     return false;
7735 
7736   if (NullKind == Expr::NPCK_ZeroExpression)
7737     return false;
7738 
7739   if (NullKind == Expr::NPCK_ZeroLiteral) {
7740     // In this case, check to make sure that we got here from a "NULL"
7741     // string in the source code.
7742     NullExpr = NullExpr->IgnoreParenImpCasts();
7743     SourceLocation loc = NullExpr->getExprLoc();
7744     if (!findMacroSpelling(loc, "NULL"))
7745       return false;
7746   }
7747 
7748   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7749   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7750       << NonPointerExpr->getType() << DiagType
7751       << NonPointerExpr->getSourceRange();
7752   return true;
7753 }
7754 
7755 /// Return false if the condition expression is valid, true otherwise.
7756 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7757   QualType CondTy = Cond->getType();
7758 
7759   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7760   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7761     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7762       << CondTy << Cond->getSourceRange();
7763     return true;
7764   }
7765 
7766   // C99 6.5.15p2
7767   if (CondTy->isScalarType()) return false;
7768 
7769   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7770     << CondTy << Cond->getSourceRange();
7771   return true;
7772 }
7773 
7774 /// Handle when one or both operands are void type.
7775 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7776                                          ExprResult &RHS) {
7777     Expr *LHSExpr = LHS.get();
7778     Expr *RHSExpr = RHS.get();
7779 
7780     if (!LHSExpr->getType()->isVoidType())
7781       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7782           << RHSExpr->getSourceRange();
7783     if (!RHSExpr->getType()->isVoidType())
7784       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7785           << LHSExpr->getSourceRange();
7786     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7787     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7788     return S.Context.VoidTy;
7789 }
7790 
7791 /// Return false if the NullExpr can be promoted to PointerTy,
7792 /// true otherwise.
7793 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7794                                         QualType PointerTy) {
7795   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7796       !NullExpr.get()->isNullPointerConstant(S.Context,
7797                                             Expr::NPC_ValueDependentIsNull))
7798     return true;
7799 
7800   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7801   return false;
7802 }
7803 
7804 /// Checks compatibility between two pointers and return the resulting
7805 /// type.
7806 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7807                                                      ExprResult &RHS,
7808                                                      SourceLocation Loc) {
7809   QualType LHSTy = LHS.get()->getType();
7810   QualType RHSTy = RHS.get()->getType();
7811 
7812   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7813     // Two identical pointers types are always compatible.
7814     return LHSTy;
7815   }
7816 
7817   QualType lhptee, rhptee;
7818 
7819   // Get the pointee types.
7820   bool IsBlockPointer = false;
7821   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7822     lhptee = LHSBTy->getPointeeType();
7823     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7824     IsBlockPointer = true;
7825   } else {
7826     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7827     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7828   }
7829 
7830   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7831   // differently qualified versions of compatible types, the result type is
7832   // a pointer to an appropriately qualified version of the composite
7833   // type.
7834 
7835   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7836   // clause doesn't make sense for our extensions. E.g. address space 2 should
7837   // be incompatible with address space 3: they may live on different devices or
7838   // anything.
7839   Qualifiers lhQual = lhptee.getQualifiers();
7840   Qualifiers rhQual = rhptee.getQualifiers();
7841 
7842   LangAS ResultAddrSpace = LangAS::Default;
7843   LangAS LAddrSpace = lhQual.getAddressSpace();
7844   LangAS RAddrSpace = rhQual.getAddressSpace();
7845 
7846   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7847   // spaces is disallowed.
7848   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7849     ResultAddrSpace = LAddrSpace;
7850   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7851     ResultAddrSpace = RAddrSpace;
7852   else {
7853     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7854         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7855         << RHS.get()->getSourceRange();
7856     return QualType();
7857   }
7858 
7859   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7860   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7861   lhQual.removeCVRQualifiers();
7862   rhQual.removeCVRQualifiers();
7863 
7864   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7865   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7866   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7867   // qual types are compatible iff
7868   //  * corresponded types are compatible
7869   //  * CVR qualifiers are equal
7870   //  * address spaces are equal
7871   // Thus for conditional operator we merge CVR and address space unqualified
7872   // pointees and if there is a composite type we return a pointer to it with
7873   // merged qualifiers.
7874   LHSCastKind =
7875       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7876   RHSCastKind =
7877       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7878   lhQual.removeAddressSpace();
7879   rhQual.removeAddressSpace();
7880 
7881   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7882   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7883 
7884   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7885 
7886   if (CompositeTy.isNull()) {
7887     // In this situation, we assume void* type. No especially good
7888     // reason, but this is what gcc does, and we do have to pick
7889     // to get a consistent AST.
7890     QualType incompatTy;
7891     incompatTy = S.Context.getPointerType(
7892         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7893     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7894     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7895 
7896     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7897     // for casts between types with incompatible address space qualifiers.
7898     // For the following code the compiler produces casts between global and
7899     // local address spaces of the corresponded innermost pointees:
7900     // local int *global *a;
7901     // global int *global *b;
7902     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7903     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7904         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7905         << RHS.get()->getSourceRange();
7906 
7907     return incompatTy;
7908   }
7909 
7910   // The pointer types are compatible.
7911   // In case of OpenCL ResultTy should have the address space qualifier
7912   // which is a superset of address spaces of both the 2nd and the 3rd
7913   // operands of the conditional operator.
7914   QualType ResultTy = [&, ResultAddrSpace]() {
7915     if (S.getLangOpts().OpenCL) {
7916       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7917       CompositeQuals.setAddressSpace(ResultAddrSpace);
7918       return S.Context
7919           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7920           .withCVRQualifiers(MergedCVRQual);
7921     }
7922     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7923   }();
7924   if (IsBlockPointer)
7925     ResultTy = S.Context.getBlockPointerType(ResultTy);
7926   else
7927     ResultTy = S.Context.getPointerType(ResultTy);
7928 
7929   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7930   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7931   return ResultTy;
7932 }
7933 
7934 /// Return the resulting type when the operands are both block pointers.
7935 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7936                                                           ExprResult &LHS,
7937                                                           ExprResult &RHS,
7938                                                           SourceLocation Loc) {
7939   QualType LHSTy = LHS.get()->getType();
7940   QualType RHSTy = RHS.get()->getType();
7941 
7942   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7943     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7944       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7945       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7946       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7947       return destType;
7948     }
7949     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7950       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7951       << RHS.get()->getSourceRange();
7952     return QualType();
7953   }
7954 
7955   // We have 2 block pointer types.
7956   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7957 }
7958 
7959 /// Return the resulting type when the operands are both pointers.
7960 static QualType
7961 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7962                                             ExprResult &RHS,
7963                                             SourceLocation Loc) {
7964   // get the pointer types
7965   QualType LHSTy = LHS.get()->getType();
7966   QualType RHSTy = RHS.get()->getType();
7967 
7968   // get the "pointed to" types
7969   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7970   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7971 
7972   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7973   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7974     // Figure out necessary qualifiers (C99 6.5.15p6)
7975     QualType destPointee
7976       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7977     QualType destType = S.Context.getPointerType(destPointee);
7978     // Add qualifiers if necessary.
7979     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7980     // Promote to void*.
7981     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7982     return destType;
7983   }
7984   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7985     QualType destPointee
7986       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7987     QualType destType = S.Context.getPointerType(destPointee);
7988     // Add qualifiers if necessary.
7989     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7990     // Promote to void*.
7991     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7992     return destType;
7993   }
7994 
7995   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7996 }
7997 
7998 /// Return false if the first expression is not an integer and the second
7999 /// expression is not a pointer, true otherwise.
8000 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8001                                         Expr* PointerExpr, SourceLocation Loc,
8002                                         bool IsIntFirstExpr) {
8003   if (!PointerExpr->getType()->isPointerType() ||
8004       !Int.get()->getType()->isIntegerType())
8005     return false;
8006 
8007   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8008   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8009 
8010   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8011     << Expr1->getType() << Expr2->getType()
8012     << Expr1->getSourceRange() << Expr2->getSourceRange();
8013   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8014                             CK_IntegralToPointer);
8015   return true;
8016 }
8017 
8018 /// Simple conversion between integer and floating point types.
8019 ///
8020 /// Used when handling the OpenCL conditional operator where the
8021 /// condition is a vector while the other operands are scalar.
8022 ///
8023 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8024 /// types are either integer or floating type. Between the two
8025 /// operands, the type with the higher rank is defined as the "result
8026 /// type". The other operand needs to be promoted to the same type. No
8027 /// other type promotion is allowed. We cannot use
8028 /// UsualArithmeticConversions() for this purpose, since it always
8029 /// promotes promotable types.
8030 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8031                                             ExprResult &RHS,
8032                                             SourceLocation QuestionLoc) {
8033   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8034   if (LHS.isInvalid())
8035     return QualType();
8036   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8037   if (RHS.isInvalid())
8038     return QualType();
8039 
8040   // For conversion purposes, we ignore any qualifiers.
8041   // For example, "const float" and "float" are equivalent.
8042   QualType LHSType =
8043     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8044   QualType RHSType =
8045     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8046 
8047   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8048     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8049       << LHSType << LHS.get()->getSourceRange();
8050     return QualType();
8051   }
8052 
8053   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8054     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8055       << RHSType << RHS.get()->getSourceRange();
8056     return QualType();
8057   }
8058 
8059   // If both types are identical, no conversion is needed.
8060   if (LHSType == RHSType)
8061     return LHSType;
8062 
8063   // Now handle "real" floating types (i.e. float, double, long double).
8064   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8065     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8066                                  /*IsCompAssign = */ false);
8067 
8068   // Finally, we have two differing integer types.
8069   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8070   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8071 }
8072 
8073 /// Convert scalar operands to a vector that matches the
8074 ///        condition in length.
8075 ///
8076 /// Used when handling the OpenCL conditional operator where the
8077 /// condition is a vector while the other operands are scalar.
8078 ///
8079 /// We first compute the "result type" for the scalar operands
8080 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8081 /// into a vector of that type where the length matches the condition
8082 /// vector type. s6.11.6 requires that the element types of the result
8083 /// and the condition must have the same number of bits.
8084 static QualType
8085 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8086                               QualType CondTy, SourceLocation QuestionLoc) {
8087   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8088   if (ResTy.isNull()) return QualType();
8089 
8090   const VectorType *CV = CondTy->getAs<VectorType>();
8091   assert(CV);
8092 
8093   // Determine the vector result type
8094   unsigned NumElements = CV->getNumElements();
8095   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8096 
8097   // Ensure that all types have the same number of bits
8098   if (S.Context.getTypeSize(CV->getElementType())
8099       != S.Context.getTypeSize(ResTy)) {
8100     // Since VectorTy is created internally, it does not pretty print
8101     // with an OpenCL name. Instead, we just print a description.
8102     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8103     SmallString<64> Str;
8104     llvm::raw_svector_ostream OS(Str);
8105     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8106     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8107       << CondTy << OS.str();
8108     return QualType();
8109   }
8110 
8111   // Convert operands to the vector result type
8112   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8113   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8114 
8115   return VectorTy;
8116 }
8117 
8118 /// Return false if this is a valid OpenCL condition vector
8119 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8120                                        SourceLocation QuestionLoc) {
8121   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8122   // integral type.
8123   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8124   assert(CondTy);
8125   QualType EleTy = CondTy->getElementType();
8126   if (EleTy->isIntegerType()) return false;
8127 
8128   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8129     << Cond->getType() << Cond->getSourceRange();
8130   return true;
8131 }
8132 
8133 /// Return false if the vector condition type and the vector
8134 ///        result type are compatible.
8135 ///
8136 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8137 /// number of elements, and their element types have the same number
8138 /// of bits.
8139 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8140                               SourceLocation QuestionLoc) {
8141   const VectorType *CV = CondTy->getAs<VectorType>();
8142   const VectorType *RV = VecResTy->getAs<VectorType>();
8143   assert(CV && RV);
8144 
8145   if (CV->getNumElements() != RV->getNumElements()) {
8146     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8147       << CondTy << VecResTy;
8148     return true;
8149   }
8150 
8151   QualType CVE = CV->getElementType();
8152   QualType RVE = RV->getElementType();
8153 
8154   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8155     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8156       << CondTy << VecResTy;
8157     return true;
8158   }
8159 
8160   return false;
8161 }
8162 
8163 /// Return the resulting type for the conditional operator in
8164 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8165 ///        s6.3.i) when the condition is a vector type.
8166 static QualType
8167 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8168                              ExprResult &LHS, ExprResult &RHS,
8169                              SourceLocation QuestionLoc) {
8170   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8171   if (Cond.isInvalid())
8172     return QualType();
8173   QualType CondTy = Cond.get()->getType();
8174 
8175   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8176     return QualType();
8177 
8178   // If either operand is a vector then find the vector type of the
8179   // result as specified in OpenCL v1.1 s6.3.i.
8180   if (LHS.get()->getType()->isVectorType() ||
8181       RHS.get()->getType()->isVectorType()) {
8182     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8183                                               /*isCompAssign*/false,
8184                                               /*AllowBothBool*/true,
8185                                               /*AllowBoolConversions*/false);
8186     if (VecResTy.isNull()) return QualType();
8187     // The result type must match the condition type as specified in
8188     // OpenCL v1.1 s6.11.6.
8189     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8190       return QualType();
8191     return VecResTy;
8192   }
8193 
8194   // Both operands are scalar.
8195   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8196 }
8197 
8198 /// Return true if the Expr is block type
8199 static bool checkBlockType(Sema &S, const Expr *E) {
8200   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8201     QualType Ty = CE->getCallee()->getType();
8202     if (Ty->isBlockPointerType()) {
8203       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8204       return true;
8205     }
8206   }
8207   return false;
8208 }
8209 
8210 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8211 /// In that case, LHS = cond.
8212 /// C99 6.5.15
8213 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8214                                         ExprResult &RHS, ExprValueKind &VK,
8215                                         ExprObjectKind &OK,
8216                                         SourceLocation QuestionLoc) {
8217 
8218   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8219   if (!LHSResult.isUsable()) return QualType();
8220   LHS = LHSResult;
8221 
8222   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8223   if (!RHSResult.isUsable()) return QualType();
8224   RHS = RHSResult;
8225 
8226   // C++ is sufficiently different to merit its own checker.
8227   if (getLangOpts().CPlusPlus)
8228     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8229 
8230   VK = VK_RValue;
8231   OK = OK_Ordinary;
8232 
8233   if (Context.isDependenceAllowed() &&
8234       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8235        RHS.get()->isTypeDependent())) {
8236     assert(!getLangOpts().CPlusPlus);
8237     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8238             RHS.get()->containsErrors()) &&
8239            "should only occur in error-recovery path.");
8240     return Context.DependentTy;
8241   }
8242 
8243   // The OpenCL operator with a vector condition is sufficiently
8244   // different to merit its own checker.
8245   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8246       Cond.get()->getType()->isExtVectorType())
8247     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8248 
8249   // First, check the condition.
8250   Cond = UsualUnaryConversions(Cond.get());
8251   if (Cond.isInvalid())
8252     return QualType();
8253   if (checkCondition(*this, Cond.get(), QuestionLoc))
8254     return QualType();
8255 
8256   // Now check the two expressions.
8257   if (LHS.get()->getType()->isVectorType() ||
8258       RHS.get()->getType()->isVectorType())
8259     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8260                                /*AllowBothBool*/true,
8261                                /*AllowBoolConversions*/false);
8262 
8263   QualType ResTy =
8264       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8265   if (LHS.isInvalid() || RHS.isInvalid())
8266     return QualType();
8267 
8268   QualType LHSTy = LHS.get()->getType();
8269   QualType RHSTy = RHS.get()->getType();
8270 
8271   // Diagnose attempts to convert between __float128 and long double where
8272   // such conversions currently can't be handled.
8273   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8274     Diag(QuestionLoc,
8275          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8276       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8277     return QualType();
8278   }
8279 
8280   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8281   // selection operator (?:).
8282   if (getLangOpts().OpenCL &&
8283       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8284     return QualType();
8285   }
8286 
8287   // If both operands have arithmetic type, do the usual arithmetic conversions
8288   // to find a common type: C99 6.5.15p3,5.
8289   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8290     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8291     // different sizes, or between ExtInts and other types.
8292     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8293       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8294           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8295           << RHS.get()->getSourceRange();
8296       return QualType();
8297     }
8298 
8299     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8300     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8301 
8302     return ResTy;
8303   }
8304 
8305   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8306   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8307     return LHSTy;
8308   }
8309 
8310   // If both operands are the same structure or union type, the result is that
8311   // type.
8312   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8313     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8314       if (LHSRT->getDecl() == RHSRT->getDecl())
8315         // "If both the operands have structure or union type, the result has
8316         // that type."  This implies that CV qualifiers are dropped.
8317         return LHSTy.getUnqualifiedType();
8318     // FIXME: Type of conditional expression must be complete in C mode.
8319   }
8320 
8321   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8322   // The following || allows only one side to be void (a GCC-ism).
8323   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8324     return checkConditionalVoidType(*this, LHS, RHS);
8325   }
8326 
8327   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8328   // the type of the other operand."
8329   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8330   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8331 
8332   // All objective-c pointer type analysis is done here.
8333   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8334                                                         QuestionLoc);
8335   if (LHS.isInvalid() || RHS.isInvalid())
8336     return QualType();
8337   if (!compositeType.isNull())
8338     return compositeType;
8339 
8340 
8341   // Handle block pointer types.
8342   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8343     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8344                                                      QuestionLoc);
8345 
8346   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8347   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8348     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8349                                                        QuestionLoc);
8350 
8351   // GCC compatibility: soften pointer/integer mismatch.  Note that
8352   // null pointers have been filtered out by this point.
8353   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8354       /*IsIntFirstExpr=*/true))
8355     return RHSTy;
8356   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8357       /*IsIntFirstExpr=*/false))
8358     return LHSTy;
8359 
8360   // Allow ?: operations in which both operands have the same
8361   // built-in sizeless type.
8362   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8363     return LHSTy;
8364 
8365   // Emit a better diagnostic if one of the expressions is a null pointer
8366   // constant and the other is not a pointer type. In this case, the user most
8367   // likely forgot to take the address of the other expression.
8368   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8369     return QualType();
8370 
8371   // Otherwise, the operands are not compatible.
8372   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8373     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8374     << RHS.get()->getSourceRange();
8375   return QualType();
8376 }
8377 
8378 /// FindCompositeObjCPointerType - Helper method to find composite type of
8379 /// two objective-c pointer types of the two input expressions.
8380 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8381                                             SourceLocation QuestionLoc) {
8382   QualType LHSTy = LHS.get()->getType();
8383   QualType RHSTy = RHS.get()->getType();
8384 
8385   // Handle things like Class and struct objc_class*.  Here we case the result
8386   // to the pseudo-builtin, because that will be implicitly cast back to the
8387   // redefinition type if an attempt is made to access its fields.
8388   if (LHSTy->isObjCClassType() &&
8389       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8390     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8391     return LHSTy;
8392   }
8393   if (RHSTy->isObjCClassType() &&
8394       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8395     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8396     return RHSTy;
8397   }
8398   // And the same for struct objc_object* / id
8399   if (LHSTy->isObjCIdType() &&
8400       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8401     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8402     return LHSTy;
8403   }
8404   if (RHSTy->isObjCIdType() &&
8405       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8406     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8407     return RHSTy;
8408   }
8409   // And the same for struct objc_selector* / SEL
8410   if (Context.isObjCSelType(LHSTy) &&
8411       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8412     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8413     return LHSTy;
8414   }
8415   if (Context.isObjCSelType(RHSTy) &&
8416       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8417     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8418     return RHSTy;
8419   }
8420   // Check constraints for Objective-C object pointers types.
8421   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8422 
8423     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8424       // Two identical object pointer types are always compatible.
8425       return LHSTy;
8426     }
8427     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8428     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8429     QualType compositeType = LHSTy;
8430 
8431     // If both operands are interfaces and either operand can be
8432     // assigned to the other, use that type as the composite
8433     // type. This allows
8434     //   xxx ? (A*) a : (B*) b
8435     // where B is a subclass of A.
8436     //
8437     // Additionally, as for assignment, if either type is 'id'
8438     // allow silent coercion. Finally, if the types are
8439     // incompatible then make sure to use 'id' as the composite
8440     // type so the result is acceptable for sending messages to.
8441 
8442     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8443     // It could return the composite type.
8444     if (!(compositeType =
8445           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8446       // Nothing more to do.
8447     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8448       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8449     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8450       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8451     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8452                 RHSOPT->isObjCQualifiedIdType()) &&
8453                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8454                                                          true)) {
8455       // Need to handle "id<xx>" explicitly.
8456       // GCC allows qualified id and any Objective-C type to devolve to
8457       // id. Currently localizing to here until clear this should be
8458       // part of ObjCQualifiedIdTypesAreCompatible.
8459       compositeType = Context.getObjCIdType();
8460     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8461       compositeType = Context.getObjCIdType();
8462     } else {
8463       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8464       << LHSTy << RHSTy
8465       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8466       QualType incompatTy = Context.getObjCIdType();
8467       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8468       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8469       return incompatTy;
8470     }
8471     // The object pointer types are compatible.
8472     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8473     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8474     return compositeType;
8475   }
8476   // Check Objective-C object pointer types and 'void *'
8477   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8478     if (getLangOpts().ObjCAutoRefCount) {
8479       // ARC forbids the implicit conversion of object pointers to 'void *',
8480       // so these types are not compatible.
8481       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8482           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8483       LHS = RHS = true;
8484       return QualType();
8485     }
8486     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8487     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8488     QualType destPointee
8489     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8490     QualType destType = Context.getPointerType(destPointee);
8491     // Add qualifiers if necessary.
8492     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8493     // Promote to void*.
8494     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8495     return destType;
8496   }
8497   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8498     if (getLangOpts().ObjCAutoRefCount) {
8499       // ARC forbids the implicit conversion of object pointers to 'void *',
8500       // so these types are not compatible.
8501       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8502           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8503       LHS = RHS = true;
8504       return QualType();
8505     }
8506     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8507     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8508     QualType destPointee
8509     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8510     QualType destType = Context.getPointerType(destPointee);
8511     // Add qualifiers if necessary.
8512     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8513     // Promote to void*.
8514     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8515     return destType;
8516   }
8517   return QualType();
8518 }
8519 
8520 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8521 /// ParenRange in parentheses.
8522 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8523                                const PartialDiagnostic &Note,
8524                                SourceRange ParenRange) {
8525   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8526   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8527       EndLoc.isValid()) {
8528     Self.Diag(Loc, Note)
8529       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8530       << FixItHint::CreateInsertion(EndLoc, ")");
8531   } else {
8532     // We can't display the parentheses, so just show the bare note.
8533     Self.Diag(Loc, Note) << ParenRange;
8534   }
8535 }
8536 
8537 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8538   return BinaryOperator::isAdditiveOp(Opc) ||
8539          BinaryOperator::isMultiplicativeOp(Opc) ||
8540          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8541   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8542   // not any of the logical operators.  Bitwise-xor is commonly used as a
8543   // logical-xor because there is no logical-xor operator.  The logical
8544   // operators, including uses of xor, have a high false positive rate for
8545   // precedence warnings.
8546 }
8547 
8548 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8549 /// expression, either using a built-in or overloaded operator,
8550 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8551 /// expression.
8552 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8553                                    Expr **RHSExprs) {
8554   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8555   E = E->IgnoreImpCasts();
8556   E = E->IgnoreConversionOperatorSingleStep();
8557   E = E->IgnoreImpCasts();
8558   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8559     E = MTE->getSubExpr();
8560     E = E->IgnoreImpCasts();
8561   }
8562 
8563   // Built-in binary operator.
8564   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8565     if (IsArithmeticOp(OP->getOpcode())) {
8566       *Opcode = OP->getOpcode();
8567       *RHSExprs = OP->getRHS();
8568       return true;
8569     }
8570   }
8571 
8572   // Overloaded operator.
8573   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8574     if (Call->getNumArgs() != 2)
8575       return false;
8576 
8577     // Make sure this is really a binary operator that is safe to pass into
8578     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8579     OverloadedOperatorKind OO = Call->getOperator();
8580     if (OO < OO_Plus || OO > OO_Arrow ||
8581         OO == OO_PlusPlus || OO == OO_MinusMinus)
8582       return false;
8583 
8584     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8585     if (IsArithmeticOp(OpKind)) {
8586       *Opcode = OpKind;
8587       *RHSExprs = Call->getArg(1);
8588       return true;
8589     }
8590   }
8591 
8592   return false;
8593 }
8594 
8595 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8596 /// or is a logical expression such as (x==y) which has int type, but is
8597 /// commonly interpreted as boolean.
8598 static bool ExprLooksBoolean(Expr *E) {
8599   E = E->IgnoreParenImpCasts();
8600 
8601   if (E->getType()->isBooleanType())
8602     return true;
8603   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8604     return OP->isComparisonOp() || OP->isLogicalOp();
8605   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8606     return OP->getOpcode() == UO_LNot;
8607   if (E->getType()->isPointerType())
8608     return true;
8609   // FIXME: What about overloaded operator calls returning "unspecified boolean
8610   // type"s (commonly pointer-to-members)?
8611 
8612   return false;
8613 }
8614 
8615 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8616 /// and binary operator are mixed in a way that suggests the programmer assumed
8617 /// the conditional operator has higher precedence, for example:
8618 /// "int x = a + someBinaryCondition ? 1 : 2".
8619 static void DiagnoseConditionalPrecedence(Sema &Self,
8620                                           SourceLocation OpLoc,
8621                                           Expr *Condition,
8622                                           Expr *LHSExpr,
8623                                           Expr *RHSExpr) {
8624   BinaryOperatorKind CondOpcode;
8625   Expr *CondRHS;
8626 
8627   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8628     return;
8629   if (!ExprLooksBoolean(CondRHS))
8630     return;
8631 
8632   // The condition is an arithmetic binary expression, with a right-
8633   // hand side that looks boolean, so warn.
8634 
8635   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8636                         ? diag::warn_precedence_bitwise_conditional
8637                         : diag::warn_precedence_conditional;
8638 
8639   Self.Diag(OpLoc, DiagID)
8640       << Condition->getSourceRange()
8641       << BinaryOperator::getOpcodeStr(CondOpcode);
8642 
8643   SuggestParentheses(
8644       Self, OpLoc,
8645       Self.PDiag(diag::note_precedence_silence)
8646           << BinaryOperator::getOpcodeStr(CondOpcode),
8647       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8648 
8649   SuggestParentheses(Self, OpLoc,
8650                      Self.PDiag(diag::note_precedence_conditional_first),
8651                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8652 }
8653 
8654 /// Compute the nullability of a conditional expression.
8655 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8656                                               QualType LHSTy, QualType RHSTy,
8657                                               ASTContext &Ctx) {
8658   if (!ResTy->isAnyPointerType())
8659     return ResTy;
8660 
8661   auto GetNullability = [&Ctx](QualType Ty) {
8662     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8663     if (Kind) {
8664       // For our purposes, treat _Nullable_result as _Nullable.
8665       if (*Kind == NullabilityKind::NullableResult)
8666         return NullabilityKind::Nullable;
8667       return *Kind;
8668     }
8669     return NullabilityKind::Unspecified;
8670   };
8671 
8672   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8673   NullabilityKind MergedKind;
8674 
8675   // Compute nullability of a binary conditional expression.
8676   if (IsBin) {
8677     if (LHSKind == NullabilityKind::NonNull)
8678       MergedKind = NullabilityKind::NonNull;
8679     else
8680       MergedKind = RHSKind;
8681   // Compute nullability of a normal conditional expression.
8682   } else {
8683     if (LHSKind == NullabilityKind::Nullable ||
8684         RHSKind == NullabilityKind::Nullable)
8685       MergedKind = NullabilityKind::Nullable;
8686     else if (LHSKind == NullabilityKind::NonNull)
8687       MergedKind = RHSKind;
8688     else if (RHSKind == NullabilityKind::NonNull)
8689       MergedKind = LHSKind;
8690     else
8691       MergedKind = NullabilityKind::Unspecified;
8692   }
8693 
8694   // Return if ResTy already has the correct nullability.
8695   if (GetNullability(ResTy) == MergedKind)
8696     return ResTy;
8697 
8698   // Strip all nullability from ResTy.
8699   while (ResTy->getNullability(Ctx))
8700     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8701 
8702   // Create a new AttributedType with the new nullability kind.
8703   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8704   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8705 }
8706 
8707 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8708 /// in the case of a the GNU conditional expr extension.
8709 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8710                                     SourceLocation ColonLoc,
8711                                     Expr *CondExpr, Expr *LHSExpr,
8712                                     Expr *RHSExpr) {
8713   if (!Context.isDependenceAllowed()) {
8714     // C cannot handle TypoExpr nodes in the condition because it
8715     // doesn't handle dependent types properly, so make sure any TypoExprs have
8716     // been dealt with before checking the operands.
8717     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8718     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8719     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8720 
8721     if (!CondResult.isUsable())
8722       return ExprError();
8723 
8724     if (LHSExpr) {
8725       if (!LHSResult.isUsable())
8726         return ExprError();
8727     }
8728 
8729     if (!RHSResult.isUsable())
8730       return ExprError();
8731 
8732     CondExpr = CondResult.get();
8733     LHSExpr = LHSResult.get();
8734     RHSExpr = RHSResult.get();
8735   }
8736 
8737   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8738   // was the condition.
8739   OpaqueValueExpr *opaqueValue = nullptr;
8740   Expr *commonExpr = nullptr;
8741   if (!LHSExpr) {
8742     commonExpr = CondExpr;
8743     // Lower out placeholder types first.  This is important so that we don't
8744     // try to capture a placeholder. This happens in few cases in C++; such
8745     // as Objective-C++'s dictionary subscripting syntax.
8746     if (commonExpr->hasPlaceholderType()) {
8747       ExprResult result = CheckPlaceholderExpr(commonExpr);
8748       if (!result.isUsable()) return ExprError();
8749       commonExpr = result.get();
8750     }
8751     // We usually want to apply unary conversions *before* saving, except
8752     // in the special case of a C++ l-value conditional.
8753     if (!(getLangOpts().CPlusPlus
8754           && !commonExpr->isTypeDependent()
8755           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8756           && commonExpr->isGLValue()
8757           && commonExpr->isOrdinaryOrBitFieldObject()
8758           && RHSExpr->isOrdinaryOrBitFieldObject()
8759           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8760       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8761       if (commonRes.isInvalid())
8762         return ExprError();
8763       commonExpr = commonRes.get();
8764     }
8765 
8766     // If the common expression is a class or array prvalue, materialize it
8767     // so that we can safely refer to it multiple times.
8768     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8769                                    commonExpr->getType()->isArrayType())) {
8770       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8771       if (MatExpr.isInvalid())
8772         return ExprError();
8773       commonExpr = MatExpr.get();
8774     }
8775 
8776     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8777                                                 commonExpr->getType(),
8778                                                 commonExpr->getValueKind(),
8779                                                 commonExpr->getObjectKind(),
8780                                                 commonExpr);
8781     LHSExpr = CondExpr = opaqueValue;
8782   }
8783 
8784   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8785   ExprValueKind VK = VK_RValue;
8786   ExprObjectKind OK = OK_Ordinary;
8787   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8788   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8789                                              VK, OK, QuestionLoc);
8790   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8791       RHS.isInvalid())
8792     return ExprError();
8793 
8794   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8795                                 RHS.get());
8796 
8797   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8798 
8799   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8800                                          Context);
8801 
8802   if (!commonExpr)
8803     return new (Context)
8804         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8805                             RHS.get(), result, VK, OK);
8806 
8807   return new (Context) BinaryConditionalOperator(
8808       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8809       ColonLoc, result, VK, OK);
8810 }
8811 
8812 // Check if we have a conversion between incompatible cmse function pointer
8813 // types, that is, a conversion between a function pointer with the
8814 // cmse_nonsecure_call attribute and one without.
8815 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8816                                           QualType ToType) {
8817   if (const auto *ToFn =
8818           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8819     if (const auto *FromFn =
8820             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8821       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8822       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8823 
8824       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8825     }
8826   }
8827   return false;
8828 }
8829 
8830 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8831 // being closely modeled after the C99 spec:-). The odd characteristic of this
8832 // routine is it effectively iqnores the qualifiers on the top level pointee.
8833 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8834 // FIXME: add a couple examples in this comment.
8835 static Sema::AssignConvertType
8836 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8837   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8838   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8839 
8840   // get the "pointed to" type (ignoring qualifiers at the top level)
8841   const Type *lhptee, *rhptee;
8842   Qualifiers lhq, rhq;
8843   std::tie(lhptee, lhq) =
8844       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8845   std::tie(rhptee, rhq) =
8846       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8847 
8848   Sema::AssignConvertType ConvTy = Sema::Compatible;
8849 
8850   // C99 6.5.16.1p1: This following citation is common to constraints
8851   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8852   // qualifiers of the type *pointed to* by the right;
8853 
8854   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8855   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8856       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8857     // Ignore lifetime for further calculation.
8858     lhq.removeObjCLifetime();
8859     rhq.removeObjCLifetime();
8860   }
8861 
8862   if (!lhq.compatiblyIncludes(rhq)) {
8863     // Treat address-space mismatches as fatal.
8864     if (!lhq.isAddressSpaceSupersetOf(rhq))
8865       return Sema::IncompatiblePointerDiscardsQualifiers;
8866 
8867     // It's okay to add or remove GC or lifetime qualifiers when converting to
8868     // and from void*.
8869     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8870                         .compatiblyIncludes(
8871                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8872              && (lhptee->isVoidType() || rhptee->isVoidType()))
8873       ; // keep old
8874 
8875     // Treat lifetime mismatches as fatal.
8876     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8877       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8878 
8879     // For GCC/MS compatibility, other qualifier mismatches are treated
8880     // as still compatible in C.
8881     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8882   }
8883 
8884   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8885   // incomplete type and the other is a pointer to a qualified or unqualified
8886   // version of void...
8887   if (lhptee->isVoidType()) {
8888     if (rhptee->isIncompleteOrObjectType())
8889       return ConvTy;
8890 
8891     // As an extension, we allow cast to/from void* to function pointer.
8892     assert(rhptee->isFunctionType());
8893     return Sema::FunctionVoidPointer;
8894   }
8895 
8896   if (rhptee->isVoidType()) {
8897     if (lhptee->isIncompleteOrObjectType())
8898       return ConvTy;
8899 
8900     // As an extension, we allow cast to/from void* to function pointer.
8901     assert(lhptee->isFunctionType());
8902     return Sema::FunctionVoidPointer;
8903   }
8904 
8905   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8906   // unqualified versions of compatible types, ...
8907   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8908   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8909     // Check if the pointee types are compatible ignoring the sign.
8910     // We explicitly check for char so that we catch "char" vs
8911     // "unsigned char" on systems where "char" is unsigned.
8912     if (lhptee->isCharType())
8913       ltrans = S.Context.UnsignedCharTy;
8914     else if (lhptee->hasSignedIntegerRepresentation())
8915       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8916 
8917     if (rhptee->isCharType())
8918       rtrans = S.Context.UnsignedCharTy;
8919     else if (rhptee->hasSignedIntegerRepresentation())
8920       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8921 
8922     if (ltrans == rtrans) {
8923       // Types are compatible ignoring the sign. Qualifier incompatibility
8924       // takes priority over sign incompatibility because the sign
8925       // warning can be disabled.
8926       if (ConvTy != Sema::Compatible)
8927         return ConvTy;
8928 
8929       return Sema::IncompatiblePointerSign;
8930     }
8931 
8932     // If we are a multi-level pointer, it's possible that our issue is simply
8933     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8934     // the eventual target type is the same and the pointers have the same
8935     // level of indirection, this must be the issue.
8936     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8937       do {
8938         std::tie(lhptee, lhq) =
8939           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8940         std::tie(rhptee, rhq) =
8941           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8942 
8943         // Inconsistent address spaces at this point is invalid, even if the
8944         // address spaces would be compatible.
8945         // FIXME: This doesn't catch address space mismatches for pointers of
8946         // different nesting levels, like:
8947         //   __local int *** a;
8948         //   int ** b = a;
8949         // It's not clear how to actually determine when such pointers are
8950         // invalidly incompatible.
8951         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8952           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8953 
8954       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8955 
8956       if (lhptee == rhptee)
8957         return Sema::IncompatibleNestedPointerQualifiers;
8958     }
8959 
8960     // General pointer incompatibility takes priority over qualifiers.
8961     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8962       return Sema::IncompatibleFunctionPointer;
8963     return Sema::IncompatiblePointer;
8964   }
8965   if (!S.getLangOpts().CPlusPlus &&
8966       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8967     return Sema::IncompatibleFunctionPointer;
8968   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8969     return Sema::IncompatibleFunctionPointer;
8970   return ConvTy;
8971 }
8972 
8973 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8974 /// block pointer types are compatible or whether a block and normal pointer
8975 /// are compatible. It is more restrict than comparing two function pointer
8976 // types.
8977 static Sema::AssignConvertType
8978 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8979                                     QualType RHSType) {
8980   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8981   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8982 
8983   QualType lhptee, rhptee;
8984 
8985   // get the "pointed to" type (ignoring qualifiers at the top level)
8986   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8987   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8988 
8989   // In C++, the types have to match exactly.
8990   if (S.getLangOpts().CPlusPlus)
8991     return Sema::IncompatibleBlockPointer;
8992 
8993   Sema::AssignConvertType ConvTy = Sema::Compatible;
8994 
8995   // For blocks we enforce that qualifiers are identical.
8996   Qualifiers LQuals = lhptee.getLocalQualifiers();
8997   Qualifiers RQuals = rhptee.getLocalQualifiers();
8998   if (S.getLangOpts().OpenCL) {
8999     LQuals.removeAddressSpace();
9000     RQuals.removeAddressSpace();
9001   }
9002   if (LQuals != RQuals)
9003     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9004 
9005   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9006   // assignment.
9007   // The current behavior is similar to C++ lambdas. A block might be
9008   // assigned to a variable iff its return type and parameters are compatible
9009   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9010   // an assignment. Presumably it should behave in way that a function pointer
9011   // assignment does in C, so for each parameter and return type:
9012   //  * CVR and address space of LHS should be a superset of CVR and address
9013   //  space of RHS.
9014   //  * unqualified types should be compatible.
9015   if (S.getLangOpts().OpenCL) {
9016     if (!S.Context.typesAreBlockPointerCompatible(
9017             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9018             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9019       return Sema::IncompatibleBlockPointer;
9020   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9021     return Sema::IncompatibleBlockPointer;
9022 
9023   return ConvTy;
9024 }
9025 
9026 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9027 /// for assignment compatibility.
9028 static Sema::AssignConvertType
9029 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9030                                    QualType RHSType) {
9031   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9032   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9033 
9034   if (LHSType->isObjCBuiltinType()) {
9035     // Class is not compatible with ObjC object pointers.
9036     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9037         !RHSType->isObjCQualifiedClassType())
9038       return Sema::IncompatiblePointer;
9039     return Sema::Compatible;
9040   }
9041   if (RHSType->isObjCBuiltinType()) {
9042     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9043         !LHSType->isObjCQualifiedClassType())
9044       return Sema::IncompatiblePointer;
9045     return Sema::Compatible;
9046   }
9047   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9048   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9049 
9050   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9051       // make an exception for id<P>
9052       !LHSType->isObjCQualifiedIdType())
9053     return Sema::CompatiblePointerDiscardsQualifiers;
9054 
9055   if (S.Context.typesAreCompatible(LHSType, RHSType))
9056     return Sema::Compatible;
9057   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9058     return Sema::IncompatibleObjCQualifiedId;
9059   return Sema::IncompatiblePointer;
9060 }
9061 
9062 Sema::AssignConvertType
9063 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9064                                  QualType LHSType, QualType RHSType) {
9065   // Fake up an opaque expression.  We don't actually care about what
9066   // cast operations are required, so if CheckAssignmentConstraints
9067   // adds casts to this they'll be wasted, but fortunately that doesn't
9068   // usually happen on valid code.
9069   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
9070   ExprResult RHSPtr = &RHSExpr;
9071   CastKind K;
9072 
9073   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9074 }
9075 
9076 /// This helper function returns true if QT is a vector type that has element
9077 /// type ElementType.
9078 static bool isVector(QualType QT, QualType ElementType) {
9079   if (const VectorType *VT = QT->getAs<VectorType>())
9080     return VT->getElementType().getCanonicalType() == ElementType;
9081   return false;
9082 }
9083 
9084 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9085 /// has code to accommodate several GCC extensions when type checking
9086 /// pointers. Here are some objectionable examples that GCC considers warnings:
9087 ///
9088 ///  int a, *pint;
9089 ///  short *pshort;
9090 ///  struct foo *pfoo;
9091 ///
9092 ///  pint = pshort; // warning: assignment from incompatible pointer type
9093 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9094 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9095 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9096 ///
9097 /// As a result, the code for dealing with pointers is more complex than the
9098 /// C99 spec dictates.
9099 ///
9100 /// Sets 'Kind' for any result kind except Incompatible.
9101 Sema::AssignConvertType
9102 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9103                                  CastKind &Kind, bool ConvertRHS) {
9104   QualType RHSType = RHS.get()->getType();
9105   QualType OrigLHSType = LHSType;
9106 
9107   // Get canonical types.  We're not formatting these types, just comparing
9108   // them.
9109   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9110   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9111 
9112   // Common case: no conversion required.
9113   if (LHSType == RHSType) {
9114     Kind = CK_NoOp;
9115     return Compatible;
9116   }
9117 
9118   // If we have an atomic type, try a non-atomic assignment, then just add an
9119   // atomic qualification step.
9120   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9121     Sema::AssignConvertType result =
9122       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9123     if (result != Compatible)
9124       return result;
9125     if (Kind != CK_NoOp && ConvertRHS)
9126       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9127     Kind = CK_NonAtomicToAtomic;
9128     return Compatible;
9129   }
9130 
9131   // If the left-hand side is a reference type, then we are in a
9132   // (rare!) case where we've allowed the use of references in C,
9133   // e.g., as a parameter type in a built-in function. In this case,
9134   // just make sure that the type referenced is compatible with the
9135   // right-hand side type. The caller is responsible for adjusting
9136   // LHSType so that the resulting expression does not have reference
9137   // type.
9138   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9139     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9140       Kind = CK_LValueBitCast;
9141       return Compatible;
9142     }
9143     return Incompatible;
9144   }
9145 
9146   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9147   // to the same ExtVector type.
9148   if (LHSType->isExtVectorType()) {
9149     if (RHSType->isExtVectorType())
9150       return Incompatible;
9151     if (RHSType->isArithmeticType()) {
9152       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9153       if (ConvertRHS)
9154         RHS = prepareVectorSplat(LHSType, RHS.get());
9155       Kind = CK_VectorSplat;
9156       return Compatible;
9157     }
9158   }
9159 
9160   // Conversions to or from vector type.
9161   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9162     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9163       // Allow assignments of an AltiVec vector type to an equivalent GCC
9164       // vector type and vice versa
9165       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9166         Kind = CK_BitCast;
9167         return Compatible;
9168       }
9169 
9170       // If we are allowing lax vector conversions, and LHS and RHS are both
9171       // vectors, the total size only needs to be the same. This is a bitcast;
9172       // no bits are changed but the result type is different.
9173       if (isLaxVectorConversion(RHSType, LHSType)) {
9174         Kind = CK_BitCast;
9175         return IncompatibleVectors;
9176       }
9177     }
9178 
9179     // When the RHS comes from another lax conversion (e.g. binops between
9180     // scalars and vectors) the result is canonicalized as a vector. When the
9181     // LHS is also a vector, the lax is allowed by the condition above. Handle
9182     // the case where LHS is a scalar.
9183     if (LHSType->isScalarType()) {
9184       const VectorType *VecType = RHSType->getAs<VectorType>();
9185       if (VecType && VecType->getNumElements() == 1 &&
9186           isLaxVectorConversion(RHSType, LHSType)) {
9187         ExprResult *VecExpr = &RHS;
9188         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9189         Kind = CK_BitCast;
9190         return Compatible;
9191       }
9192     }
9193 
9194     // Allow assignments between fixed-length and sizeless SVE vectors.
9195     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9196         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9197       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9198           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9199         Kind = CK_BitCast;
9200         return Compatible;
9201       }
9202 
9203     return Incompatible;
9204   }
9205 
9206   // Diagnose attempts to convert between __float128 and long double where
9207   // such conversions currently can't be handled.
9208   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9209     return Incompatible;
9210 
9211   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9212   // discards the imaginary part.
9213   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9214       !LHSType->getAs<ComplexType>())
9215     return Incompatible;
9216 
9217   // Arithmetic conversions.
9218   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9219       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9220     if (ConvertRHS)
9221       Kind = PrepareScalarCast(RHS, LHSType);
9222     return Compatible;
9223   }
9224 
9225   // Conversions to normal pointers.
9226   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9227     // U* -> T*
9228     if (isa<PointerType>(RHSType)) {
9229       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9230       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9231       if (AddrSpaceL != AddrSpaceR)
9232         Kind = CK_AddressSpaceConversion;
9233       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9234         Kind = CK_NoOp;
9235       else
9236         Kind = CK_BitCast;
9237       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9238     }
9239 
9240     // int -> T*
9241     if (RHSType->isIntegerType()) {
9242       Kind = CK_IntegralToPointer; // FIXME: null?
9243       return IntToPointer;
9244     }
9245 
9246     // C pointers are not compatible with ObjC object pointers,
9247     // with two exceptions:
9248     if (isa<ObjCObjectPointerType>(RHSType)) {
9249       //  - conversions to void*
9250       if (LHSPointer->getPointeeType()->isVoidType()) {
9251         Kind = CK_BitCast;
9252         return Compatible;
9253       }
9254 
9255       //  - conversions from 'Class' to the redefinition type
9256       if (RHSType->isObjCClassType() &&
9257           Context.hasSameType(LHSType,
9258                               Context.getObjCClassRedefinitionType())) {
9259         Kind = CK_BitCast;
9260         return Compatible;
9261       }
9262 
9263       Kind = CK_BitCast;
9264       return IncompatiblePointer;
9265     }
9266 
9267     // U^ -> void*
9268     if (RHSType->getAs<BlockPointerType>()) {
9269       if (LHSPointer->getPointeeType()->isVoidType()) {
9270         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9271         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9272                                 ->getPointeeType()
9273                                 .getAddressSpace();
9274         Kind =
9275             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9276         return Compatible;
9277       }
9278     }
9279 
9280     return Incompatible;
9281   }
9282 
9283   // Conversions to block pointers.
9284   if (isa<BlockPointerType>(LHSType)) {
9285     // U^ -> T^
9286     if (RHSType->isBlockPointerType()) {
9287       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9288                               ->getPointeeType()
9289                               .getAddressSpace();
9290       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9291                               ->getPointeeType()
9292                               .getAddressSpace();
9293       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9294       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9295     }
9296 
9297     // int or null -> T^
9298     if (RHSType->isIntegerType()) {
9299       Kind = CK_IntegralToPointer; // FIXME: null
9300       return IntToBlockPointer;
9301     }
9302 
9303     // id -> T^
9304     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9305       Kind = CK_AnyPointerToBlockPointerCast;
9306       return Compatible;
9307     }
9308 
9309     // void* -> T^
9310     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9311       if (RHSPT->getPointeeType()->isVoidType()) {
9312         Kind = CK_AnyPointerToBlockPointerCast;
9313         return Compatible;
9314       }
9315 
9316     return Incompatible;
9317   }
9318 
9319   // Conversions to Objective-C pointers.
9320   if (isa<ObjCObjectPointerType>(LHSType)) {
9321     // A* -> B*
9322     if (RHSType->isObjCObjectPointerType()) {
9323       Kind = CK_BitCast;
9324       Sema::AssignConvertType result =
9325         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9326       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9327           result == Compatible &&
9328           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9329         result = IncompatibleObjCWeakRef;
9330       return result;
9331     }
9332 
9333     // int or null -> A*
9334     if (RHSType->isIntegerType()) {
9335       Kind = CK_IntegralToPointer; // FIXME: null
9336       return IntToPointer;
9337     }
9338 
9339     // In general, C pointers are not compatible with ObjC object pointers,
9340     // with two exceptions:
9341     if (isa<PointerType>(RHSType)) {
9342       Kind = CK_CPointerToObjCPointerCast;
9343 
9344       //  - conversions from 'void*'
9345       if (RHSType->isVoidPointerType()) {
9346         return Compatible;
9347       }
9348 
9349       //  - conversions to 'Class' from its redefinition type
9350       if (LHSType->isObjCClassType() &&
9351           Context.hasSameType(RHSType,
9352                               Context.getObjCClassRedefinitionType())) {
9353         return Compatible;
9354       }
9355 
9356       return IncompatiblePointer;
9357     }
9358 
9359     // Only under strict condition T^ is compatible with an Objective-C pointer.
9360     if (RHSType->isBlockPointerType() &&
9361         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9362       if (ConvertRHS)
9363         maybeExtendBlockObject(RHS);
9364       Kind = CK_BlockPointerToObjCPointerCast;
9365       return Compatible;
9366     }
9367 
9368     return Incompatible;
9369   }
9370 
9371   // Conversions from pointers that are not covered by the above.
9372   if (isa<PointerType>(RHSType)) {
9373     // T* -> _Bool
9374     if (LHSType == Context.BoolTy) {
9375       Kind = CK_PointerToBoolean;
9376       return Compatible;
9377     }
9378 
9379     // T* -> int
9380     if (LHSType->isIntegerType()) {
9381       Kind = CK_PointerToIntegral;
9382       return PointerToInt;
9383     }
9384 
9385     return Incompatible;
9386   }
9387 
9388   // Conversions from Objective-C pointers that are not covered by the above.
9389   if (isa<ObjCObjectPointerType>(RHSType)) {
9390     // T* -> _Bool
9391     if (LHSType == Context.BoolTy) {
9392       Kind = CK_PointerToBoolean;
9393       return Compatible;
9394     }
9395 
9396     // T* -> int
9397     if (LHSType->isIntegerType()) {
9398       Kind = CK_PointerToIntegral;
9399       return PointerToInt;
9400     }
9401 
9402     return Incompatible;
9403   }
9404 
9405   // struct A -> struct B
9406   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9407     if (Context.typesAreCompatible(LHSType, RHSType)) {
9408       Kind = CK_NoOp;
9409       return Compatible;
9410     }
9411   }
9412 
9413   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9414     Kind = CK_IntToOCLSampler;
9415     return Compatible;
9416   }
9417 
9418   return Incompatible;
9419 }
9420 
9421 /// Constructs a transparent union from an expression that is
9422 /// used to initialize the transparent union.
9423 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9424                                       ExprResult &EResult, QualType UnionType,
9425                                       FieldDecl *Field) {
9426   // Build an initializer list that designates the appropriate member
9427   // of the transparent union.
9428   Expr *E = EResult.get();
9429   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9430                                                    E, SourceLocation());
9431   Initializer->setType(UnionType);
9432   Initializer->setInitializedFieldInUnion(Field);
9433 
9434   // Build a compound literal constructing a value of the transparent
9435   // union type from this initializer list.
9436   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9437   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9438                                         VK_RValue, Initializer, false);
9439 }
9440 
9441 Sema::AssignConvertType
9442 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9443                                                ExprResult &RHS) {
9444   QualType RHSType = RHS.get()->getType();
9445 
9446   // If the ArgType is a Union type, we want to handle a potential
9447   // transparent_union GCC extension.
9448   const RecordType *UT = ArgType->getAsUnionType();
9449   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9450     return Incompatible;
9451 
9452   // The field to initialize within the transparent union.
9453   RecordDecl *UD = UT->getDecl();
9454   FieldDecl *InitField = nullptr;
9455   // It's compatible if the expression matches any of the fields.
9456   for (auto *it : UD->fields()) {
9457     if (it->getType()->isPointerType()) {
9458       // If the transparent union contains a pointer type, we allow:
9459       // 1) void pointer
9460       // 2) null pointer constant
9461       if (RHSType->isPointerType())
9462         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9463           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9464           InitField = it;
9465           break;
9466         }
9467 
9468       if (RHS.get()->isNullPointerConstant(Context,
9469                                            Expr::NPC_ValueDependentIsNull)) {
9470         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9471                                 CK_NullToPointer);
9472         InitField = it;
9473         break;
9474       }
9475     }
9476 
9477     CastKind Kind;
9478     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9479           == Compatible) {
9480       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9481       InitField = it;
9482       break;
9483     }
9484   }
9485 
9486   if (!InitField)
9487     return Incompatible;
9488 
9489   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9490   return Compatible;
9491 }
9492 
9493 Sema::AssignConvertType
9494 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9495                                        bool Diagnose,
9496                                        bool DiagnoseCFAudited,
9497                                        bool ConvertRHS) {
9498   // We need to be able to tell the caller whether we diagnosed a problem, if
9499   // they ask us to issue diagnostics.
9500   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9501 
9502   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9503   // we can't avoid *all* modifications at the moment, so we need some somewhere
9504   // to put the updated value.
9505   ExprResult LocalRHS = CallerRHS;
9506   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9507 
9508   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9509     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9510       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9511           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9512         Diag(RHS.get()->getExprLoc(),
9513              diag::warn_noderef_to_dereferenceable_pointer)
9514             << RHS.get()->getSourceRange();
9515       }
9516     }
9517   }
9518 
9519   if (getLangOpts().CPlusPlus) {
9520     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9521       // C++ 5.17p3: If the left operand is not of class type, the
9522       // expression is implicitly converted (C++ 4) to the
9523       // cv-unqualified type of the left operand.
9524       QualType RHSType = RHS.get()->getType();
9525       if (Diagnose) {
9526         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9527                                         AA_Assigning);
9528       } else {
9529         ImplicitConversionSequence ICS =
9530             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9531                                   /*SuppressUserConversions=*/false,
9532                                   AllowedExplicit::None,
9533                                   /*InOverloadResolution=*/false,
9534                                   /*CStyle=*/false,
9535                                   /*AllowObjCWritebackConversion=*/false);
9536         if (ICS.isFailure())
9537           return Incompatible;
9538         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9539                                         ICS, AA_Assigning);
9540       }
9541       if (RHS.isInvalid())
9542         return Incompatible;
9543       Sema::AssignConvertType result = Compatible;
9544       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9545           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9546         result = IncompatibleObjCWeakRef;
9547       return result;
9548     }
9549 
9550     // FIXME: Currently, we fall through and treat C++ classes like C
9551     // structures.
9552     // FIXME: We also fall through for atomics; not sure what should
9553     // happen there, though.
9554   } else if (RHS.get()->getType() == Context.OverloadTy) {
9555     // As a set of extensions to C, we support overloading on functions. These
9556     // functions need to be resolved here.
9557     DeclAccessPair DAP;
9558     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9559             RHS.get(), LHSType, /*Complain=*/false, DAP))
9560       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9561     else
9562       return Incompatible;
9563   }
9564 
9565   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9566   // a null pointer constant.
9567   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9568        LHSType->isBlockPointerType()) &&
9569       RHS.get()->isNullPointerConstant(Context,
9570                                        Expr::NPC_ValueDependentIsNull)) {
9571     if (Diagnose || ConvertRHS) {
9572       CastKind Kind;
9573       CXXCastPath Path;
9574       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9575                              /*IgnoreBaseAccess=*/false, Diagnose);
9576       if (ConvertRHS)
9577         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9578     }
9579     return Compatible;
9580   }
9581 
9582   // OpenCL queue_t type assignment.
9583   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9584                                  Context, Expr::NPC_ValueDependentIsNull)) {
9585     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9586     return Compatible;
9587   }
9588 
9589   // This check seems unnatural, however it is necessary to ensure the proper
9590   // conversion of functions/arrays. If the conversion were done for all
9591   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9592   // expressions that suppress this implicit conversion (&, sizeof).
9593   //
9594   // Suppress this for references: C++ 8.5.3p5.
9595   if (!LHSType->isReferenceType()) {
9596     // FIXME: We potentially allocate here even if ConvertRHS is false.
9597     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9598     if (RHS.isInvalid())
9599       return Incompatible;
9600   }
9601   CastKind Kind;
9602   Sema::AssignConvertType result =
9603     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9604 
9605   // C99 6.5.16.1p2: The value of the right operand is converted to the
9606   // type of the assignment expression.
9607   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9608   // so that we can use references in built-in functions even in C.
9609   // The getNonReferenceType() call makes sure that the resulting expression
9610   // does not have reference type.
9611   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9612     QualType Ty = LHSType.getNonLValueExprType(Context);
9613     Expr *E = RHS.get();
9614 
9615     // Check for various Objective-C errors. If we are not reporting
9616     // diagnostics and just checking for errors, e.g., during overload
9617     // resolution, return Incompatible to indicate the failure.
9618     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9619         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9620                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9621       if (!Diagnose)
9622         return Incompatible;
9623     }
9624     if (getLangOpts().ObjC &&
9625         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9626                                            E->getType(), E, Diagnose) ||
9627          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9628       if (!Diagnose)
9629         return Incompatible;
9630       // Replace the expression with a corrected version and continue so we
9631       // can find further errors.
9632       RHS = E;
9633       return Compatible;
9634     }
9635 
9636     if (ConvertRHS)
9637       RHS = ImpCastExprToType(E, Ty, Kind);
9638   }
9639 
9640   return result;
9641 }
9642 
9643 namespace {
9644 /// The original operand to an operator, prior to the application of the usual
9645 /// arithmetic conversions and converting the arguments of a builtin operator
9646 /// candidate.
9647 struct OriginalOperand {
9648   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9649     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9650       Op = MTE->getSubExpr();
9651     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9652       Op = BTE->getSubExpr();
9653     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9654       Orig = ICE->getSubExprAsWritten();
9655       Conversion = ICE->getConversionFunction();
9656     }
9657   }
9658 
9659   QualType getType() const { return Orig->getType(); }
9660 
9661   Expr *Orig;
9662   NamedDecl *Conversion;
9663 };
9664 }
9665 
9666 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9667                                ExprResult &RHS) {
9668   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9669 
9670   Diag(Loc, diag::err_typecheck_invalid_operands)
9671     << OrigLHS.getType() << OrigRHS.getType()
9672     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9673 
9674   // If a user-defined conversion was applied to either of the operands prior
9675   // to applying the built-in operator rules, tell the user about it.
9676   if (OrigLHS.Conversion) {
9677     Diag(OrigLHS.Conversion->getLocation(),
9678          diag::note_typecheck_invalid_operands_converted)
9679       << 0 << LHS.get()->getType();
9680   }
9681   if (OrigRHS.Conversion) {
9682     Diag(OrigRHS.Conversion->getLocation(),
9683          diag::note_typecheck_invalid_operands_converted)
9684       << 1 << RHS.get()->getType();
9685   }
9686 
9687   return QualType();
9688 }
9689 
9690 // Diagnose cases where a scalar was implicitly converted to a vector and
9691 // diagnose the underlying types. Otherwise, diagnose the error
9692 // as invalid vector logical operands for non-C++ cases.
9693 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9694                                             ExprResult &RHS) {
9695   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9696   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9697 
9698   bool LHSNatVec = LHSType->isVectorType();
9699   bool RHSNatVec = RHSType->isVectorType();
9700 
9701   if (!(LHSNatVec && RHSNatVec)) {
9702     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9703     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9704     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9705         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9706         << Vector->getSourceRange();
9707     return QualType();
9708   }
9709 
9710   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9711       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9712       << RHS.get()->getSourceRange();
9713 
9714   return QualType();
9715 }
9716 
9717 /// Try to convert a value of non-vector type to a vector type by converting
9718 /// the type to the element type of the vector and then performing a splat.
9719 /// If the language is OpenCL, we only use conversions that promote scalar
9720 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9721 /// for float->int.
9722 ///
9723 /// OpenCL V2.0 6.2.6.p2:
9724 /// An error shall occur if any scalar operand type has greater rank
9725 /// than the type of the vector element.
9726 ///
9727 /// \param scalar - if non-null, actually perform the conversions
9728 /// \return true if the operation fails (but without diagnosing the failure)
9729 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9730                                      QualType scalarTy,
9731                                      QualType vectorEltTy,
9732                                      QualType vectorTy,
9733                                      unsigned &DiagID) {
9734   // The conversion to apply to the scalar before splatting it,
9735   // if necessary.
9736   CastKind scalarCast = CK_NoOp;
9737 
9738   if (vectorEltTy->isIntegralType(S.Context)) {
9739     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9740         (scalarTy->isIntegerType() &&
9741          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9742       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9743       return true;
9744     }
9745     if (!scalarTy->isIntegralType(S.Context))
9746       return true;
9747     scalarCast = CK_IntegralCast;
9748   } else if (vectorEltTy->isRealFloatingType()) {
9749     if (scalarTy->isRealFloatingType()) {
9750       if (S.getLangOpts().OpenCL &&
9751           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9752         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9753         return true;
9754       }
9755       scalarCast = CK_FloatingCast;
9756     }
9757     else if (scalarTy->isIntegralType(S.Context))
9758       scalarCast = CK_IntegralToFloating;
9759     else
9760       return true;
9761   } else {
9762     return true;
9763   }
9764 
9765   // Adjust scalar if desired.
9766   if (scalar) {
9767     if (scalarCast != CK_NoOp)
9768       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9769     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9770   }
9771   return false;
9772 }
9773 
9774 /// Convert vector E to a vector with the same number of elements but different
9775 /// element type.
9776 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9777   const auto *VecTy = E->getType()->getAs<VectorType>();
9778   assert(VecTy && "Expression E must be a vector");
9779   QualType NewVecTy = S.Context.getVectorType(ElementType,
9780                                               VecTy->getNumElements(),
9781                                               VecTy->getVectorKind());
9782 
9783   // Look through the implicit cast. Return the subexpression if its type is
9784   // NewVecTy.
9785   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9786     if (ICE->getSubExpr()->getType() == NewVecTy)
9787       return ICE->getSubExpr();
9788 
9789   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9790   return S.ImpCastExprToType(E, NewVecTy, Cast);
9791 }
9792 
9793 /// Test if a (constant) integer Int can be casted to another integer type
9794 /// IntTy without losing precision.
9795 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9796                                       QualType OtherIntTy) {
9797   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9798 
9799   // Reject cases where the value of the Int is unknown as that would
9800   // possibly cause truncation, but accept cases where the scalar can be
9801   // demoted without loss of precision.
9802   Expr::EvalResult EVResult;
9803   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9804   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9805   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9806   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9807 
9808   if (CstInt) {
9809     // If the scalar is constant and is of a higher order and has more active
9810     // bits that the vector element type, reject it.
9811     llvm::APSInt Result = EVResult.Val.getInt();
9812     unsigned NumBits = IntSigned
9813                            ? (Result.isNegative() ? Result.getMinSignedBits()
9814                                                   : Result.getActiveBits())
9815                            : Result.getActiveBits();
9816     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9817       return true;
9818 
9819     // If the signedness of the scalar type and the vector element type
9820     // differs and the number of bits is greater than that of the vector
9821     // element reject it.
9822     return (IntSigned != OtherIntSigned &&
9823             NumBits > S.Context.getIntWidth(OtherIntTy));
9824   }
9825 
9826   // Reject cases where the value of the scalar is not constant and it's
9827   // order is greater than that of the vector element type.
9828   return (Order < 0);
9829 }
9830 
9831 /// Test if a (constant) integer Int can be casted to floating point type
9832 /// FloatTy without losing precision.
9833 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9834                                      QualType FloatTy) {
9835   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9836 
9837   // Determine if the integer constant can be expressed as a floating point
9838   // number of the appropriate type.
9839   Expr::EvalResult EVResult;
9840   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9841 
9842   uint64_t Bits = 0;
9843   if (CstInt) {
9844     // Reject constants that would be truncated if they were converted to
9845     // the floating point type. Test by simple to/from conversion.
9846     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9847     //        could be avoided if there was a convertFromAPInt method
9848     //        which could signal back if implicit truncation occurred.
9849     llvm::APSInt Result = EVResult.Val.getInt();
9850     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9851     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9852                            llvm::APFloat::rmTowardZero);
9853     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9854                              !IntTy->hasSignedIntegerRepresentation());
9855     bool Ignored = false;
9856     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9857                            &Ignored);
9858     if (Result != ConvertBack)
9859       return true;
9860   } else {
9861     // Reject types that cannot be fully encoded into the mantissa of
9862     // the float.
9863     Bits = S.Context.getTypeSize(IntTy);
9864     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9865         S.Context.getFloatTypeSemantics(FloatTy));
9866     if (Bits > FloatPrec)
9867       return true;
9868   }
9869 
9870   return false;
9871 }
9872 
9873 /// Attempt to convert and splat Scalar into a vector whose types matches
9874 /// Vector following GCC conversion rules. The rule is that implicit
9875 /// conversion can occur when Scalar can be casted to match Vector's element
9876 /// type without causing truncation of Scalar.
9877 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9878                                         ExprResult *Vector) {
9879   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9880   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9881   const VectorType *VT = VectorTy->getAs<VectorType>();
9882 
9883   assert(!isa<ExtVectorType>(VT) &&
9884          "ExtVectorTypes should not be handled here!");
9885 
9886   QualType VectorEltTy = VT->getElementType();
9887 
9888   // Reject cases where the vector element type or the scalar element type are
9889   // not integral or floating point types.
9890   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9891     return true;
9892 
9893   // The conversion to apply to the scalar before splatting it,
9894   // if necessary.
9895   CastKind ScalarCast = CK_NoOp;
9896 
9897   // Accept cases where the vector elements are integers and the scalar is
9898   // an integer.
9899   // FIXME: Notionally if the scalar was a floating point value with a precise
9900   //        integral representation, we could cast it to an appropriate integer
9901   //        type and then perform the rest of the checks here. GCC will perform
9902   //        this conversion in some cases as determined by the input language.
9903   //        We should accept it on a language independent basis.
9904   if (VectorEltTy->isIntegralType(S.Context) &&
9905       ScalarTy->isIntegralType(S.Context) &&
9906       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9907 
9908     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9909       return true;
9910 
9911     ScalarCast = CK_IntegralCast;
9912   } else if (VectorEltTy->isIntegralType(S.Context) &&
9913              ScalarTy->isRealFloatingType()) {
9914     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9915       ScalarCast = CK_FloatingToIntegral;
9916     else
9917       return true;
9918   } else if (VectorEltTy->isRealFloatingType()) {
9919     if (ScalarTy->isRealFloatingType()) {
9920 
9921       // Reject cases where the scalar type is not a constant and has a higher
9922       // Order than the vector element type.
9923       llvm::APFloat Result(0.0);
9924 
9925       // Determine whether this is a constant scalar. In the event that the
9926       // value is dependent (and thus cannot be evaluated by the constant
9927       // evaluator), skip the evaluation. This will then diagnose once the
9928       // expression is instantiated.
9929       bool CstScalar = Scalar->get()->isValueDependent() ||
9930                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9931       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9932       if (!CstScalar && Order < 0)
9933         return true;
9934 
9935       // If the scalar cannot be safely casted to the vector element type,
9936       // reject it.
9937       if (CstScalar) {
9938         bool Truncated = false;
9939         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9940                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9941         if (Truncated)
9942           return true;
9943       }
9944 
9945       ScalarCast = CK_FloatingCast;
9946     } else if (ScalarTy->isIntegralType(S.Context)) {
9947       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9948         return true;
9949 
9950       ScalarCast = CK_IntegralToFloating;
9951     } else
9952       return true;
9953   } else if (ScalarTy->isEnumeralType())
9954     return true;
9955 
9956   // Adjust scalar if desired.
9957   if (Scalar) {
9958     if (ScalarCast != CK_NoOp)
9959       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9960     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9961   }
9962   return false;
9963 }
9964 
9965 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9966                                    SourceLocation Loc, bool IsCompAssign,
9967                                    bool AllowBothBool,
9968                                    bool AllowBoolConversions) {
9969   if (!IsCompAssign) {
9970     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9971     if (LHS.isInvalid())
9972       return QualType();
9973   }
9974   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9975   if (RHS.isInvalid())
9976     return QualType();
9977 
9978   // For conversion purposes, we ignore any qualifiers.
9979   // For example, "const float" and "float" are equivalent.
9980   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9981   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9982 
9983   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9984   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9985   assert(LHSVecType || RHSVecType);
9986 
9987   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9988       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9989     return InvalidOperands(Loc, LHS, RHS);
9990 
9991   // AltiVec-style "vector bool op vector bool" combinations are allowed
9992   // for some operators but not others.
9993   if (!AllowBothBool &&
9994       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9995       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9996     return InvalidOperands(Loc, LHS, RHS);
9997 
9998   // If the vector types are identical, return.
9999   if (Context.hasSameType(LHSType, RHSType))
10000     return LHSType;
10001 
10002   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10003   if (LHSVecType && RHSVecType &&
10004       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10005     if (isa<ExtVectorType>(LHSVecType)) {
10006       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10007       return LHSType;
10008     }
10009 
10010     if (!IsCompAssign)
10011       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10012     return RHSType;
10013   }
10014 
10015   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10016   // can be mixed, with the result being the non-bool type.  The non-bool
10017   // operand must have integer element type.
10018   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10019       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10020       (Context.getTypeSize(LHSVecType->getElementType()) ==
10021        Context.getTypeSize(RHSVecType->getElementType()))) {
10022     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10023         LHSVecType->getElementType()->isIntegerType() &&
10024         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10025       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10026       return LHSType;
10027     }
10028     if (!IsCompAssign &&
10029         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10030         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10031         RHSVecType->getElementType()->isIntegerType()) {
10032       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10033       return RHSType;
10034     }
10035   }
10036 
10037   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10038   // since the ambiguity can affect the ABI.
10039   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10040     const VectorType *VecType = SecondType->getAs<VectorType>();
10041     return FirstType->isSizelessBuiltinType() && VecType &&
10042            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10043             VecType->getVectorKind() ==
10044                 VectorType::SveFixedLengthPredicateVector);
10045   };
10046 
10047   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10048     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10049     return QualType();
10050   }
10051 
10052   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10053   // since the ambiguity can affect the ABI.
10054   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10055     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10056     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10057 
10058     if (FirstVecType && SecondVecType)
10059       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10060              (SecondVecType->getVectorKind() ==
10061                   VectorType::SveFixedLengthDataVector ||
10062               SecondVecType->getVectorKind() ==
10063                   VectorType::SveFixedLengthPredicateVector);
10064 
10065     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10066            SecondVecType->getVectorKind() == VectorType::GenericVector;
10067   };
10068 
10069   if (IsSveGnuConversion(LHSType, RHSType) ||
10070       IsSveGnuConversion(RHSType, LHSType)) {
10071     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10072     return QualType();
10073   }
10074 
10075   // If there's a vector type and a scalar, try to convert the scalar to
10076   // the vector element type and splat.
10077   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10078   if (!RHSVecType) {
10079     if (isa<ExtVectorType>(LHSVecType)) {
10080       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10081                                     LHSVecType->getElementType(), LHSType,
10082                                     DiagID))
10083         return LHSType;
10084     } else {
10085       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10086         return LHSType;
10087     }
10088   }
10089   if (!LHSVecType) {
10090     if (isa<ExtVectorType>(RHSVecType)) {
10091       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10092                                     LHSType, RHSVecType->getElementType(),
10093                                     RHSType, DiagID))
10094         return RHSType;
10095     } else {
10096       if (LHS.get()->getValueKind() == VK_LValue ||
10097           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10098         return RHSType;
10099     }
10100   }
10101 
10102   // FIXME: The code below also handles conversion between vectors and
10103   // non-scalars, we should break this down into fine grained specific checks
10104   // and emit proper diagnostics.
10105   QualType VecType = LHSVecType ? LHSType : RHSType;
10106   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10107   QualType OtherType = LHSVecType ? RHSType : LHSType;
10108   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10109   if (isLaxVectorConversion(OtherType, VecType)) {
10110     // If we're allowing lax vector conversions, only the total (data) size
10111     // needs to be the same. For non compound assignment, if one of the types is
10112     // scalar, the result is always the vector type.
10113     if (!IsCompAssign) {
10114       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10115       return VecType;
10116     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10117     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10118     // type. Note that this is already done by non-compound assignments in
10119     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10120     // <1 x T> -> T. The result is also a vector type.
10121     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10122                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10123       ExprResult *RHSExpr = &RHS;
10124       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10125       return VecType;
10126     }
10127   }
10128 
10129   // Okay, the expression is invalid.
10130 
10131   // If there's a non-vector, non-real operand, diagnose that.
10132   if ((!RHSVecType && !RHSType->isRealType()) ||
10133       (!LHSVecType && !LHSType->isRealType())) {
10134     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10135       << LHSType << RHSType
10136       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10137     return QualType();
10138   }
10139 
10140   // OpenCL V1.1 6.2.6.p1:
10141   // If the operands are of more than one vector type, then an error shall
10142   // occur. Implicit conversions between vector types are not permitted, per
10143   // section 6.2.1.
10144   if (getLangOpts().OpenCL &&
10145       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10146       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10147     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10148                                                            << RHSType;
10149     return QualType();
10150   }
10151 
10152 
10153   // If there is a vector type that is not a ExtVector and a scalar, we reach
10154   // this point if scalar could not be converted to the vector's element type
10155   // without truncation.
10156   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10157       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10158     QualType Scalar = LHSVecType ? RHSType : LHSType;
10159     QualType Vector = LHSVecType ? LHSType : RHSType;
10160     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10161     Diag(Loc,
10162          diag::err_typecheck_vector_not_convertable_implict_truncation)
10163         << ScalarOrVector << Scalar << Vector;
10164 
10165     return QualType();
10166   }
10167 
10168   // Otherwise, use the generic diagnostic.
10169   Diag(Loc, DiagID)
10170     << LHSType << RHSType
10171     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10172   return QualType();
10173 }
10174 
10175 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10176 // expression.  These are mainly cases where the null pointer is used as an
10177 // integer instead of a pointer.
10178 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10179                                 SourceLocation Loc, bool IsCompare) {
10180   // The canonical way to check for a GNU null is with isNullPointerConstant,
10181   // but we use a bit of a hack here for speed; this is a relatively
10182   // hot path, and isNullPointerConstant is slow.
10183   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10184   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10185 
10186   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10187 
10188   // Avoid analyzing cases where the result will either be invalid (and
10189   // diagnosed as such) or entirely valid and not something to warn about.
10190   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10191       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10192     return;
10193 
10194   // Comparison operations would not make sense with a null pointer no matter
10195   // what the other expression is.
10196   if (!IsCompare) {
10197     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10198         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10199         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10200     return;
10201   }
10202 
10203   // The rest of the operations only make sense with a null pointer
10204   // if the other expression is a pointer.
10205   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10206       NonNullType->canDecayToPointerType())
10207     return;
10208 
10209   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10210       << LHSNull /* LHS is NULL */ << NonNullType
10211       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10212 }
10213 
10214 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10215                                           SourceLocation Loc) {
10216   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10217   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10218   if (!LUE || !RUE)
10219     return;
10220   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10221       RUE->getKind() != UETT_SizeOf)
10222     return;
10223 
10224   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10225   QualType LHSTy = LHSArg->getType();
10226   QualType RHSTy;
10227 
10228   if (RUE->isArgumentType())
10229     RHSTy = RUE->getArgumentType().getNonReferenceType();
10230   else
10231     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10232 
10233   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10234     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10235       return;
10236 
10237     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10238     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10239       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10240         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10241             << LHSArgDecl;
10242     }
10243   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10244     QualType ArrayElemTy = ArrayTy->getElementType();
10245     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10246         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10247         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10248         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10249       return;
10250     S.Diag(Loc, diag::warn_division_sizeof_array)
10251         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10252     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10253       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10254         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10255             << LHSArgDecl;
10256     }
10257 
10258     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10259   }
10260 }
10261 
10262 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10263                                                ExprResult &RHS,
10264                                                SourceLocation Loc, bool IsDiv) {
10265   // Check for division/remainder by zero.
10266   Expr::EvalResult RHSValue;
10267   if (!RHS.get()->isValueDependent() &&
10268       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10269       RHSValue.Val.getInt() == 0)
10270     S.DiagRuntimeBehavior(Loc, RHS.get(),
10271                           S.PDiag(diag::warn_remainder_division_by_zero)
10272                             << IsDiv << RHS.get()->getSourceRange());
10273 }
10274 
10275 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10276                                            SourceLocation Loc,
10277                                            bool IsCompAssign, bool IsDiv) {
10278   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10279 
10280   QualType LHSTy = LHS.get()->getType();
10281   QualType RHSTy = RHS.get()->getType();
10282   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10283     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10284                                /*AllowBothBool*/getLangOpts().AltiVec,
10285                                /*AllowBoolConversions*/false);
10286   if (!IsDiv &&
10287       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10288     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10289   // For division, only matrix-by-scalar is supported. Other combinations with
10290   // matrix types are invalid.
10291   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10292     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10293 
10294   QualType compType = UsualArithmeticConversions(
10295       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10296   if (LHS.isInvalid() || RHS.isInvalid())
10297     return QualType();
10298 
10299 
10300   if (compType.isNull() || !compType->isArithmeticType())
10301     return InvalidOperands(Loc, LHS, RHS);
10302   if (IsDiv) {
10303     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10304     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10305   }
10306   return compType;
10307 }
10308 
10309 QualType Sema::CheckRemainderOperands(
10310   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10311   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10312 
10313   if (LHS.get()->getType()->isVectorType() ||
10314       RHS.get()->getType()->isVectorType()) {
10315     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10316         RHS.get()->getType()->hasIntegerRepresentation())
10317       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10318                                  /*AllowBothBool*/getLangOpts().AltiVec,
10319                                  /*AllowBoolConversions*/false);
10320     return InvalidOperands(Loc, LHS, RHS);
10321   }
10322 
10323   QualType compType = UsualArithmeticConversions(
10324       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10325   if (LHS.isInvalid() || RHS.isInvalid())
10326     return QualType();
10327 
10328   if (compType.isNull() || !compType->isIntegerType())
10329     return InvalidOperands(Loc, LHS, RHS);
10330   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10331   return compType;
10332 }
10333 
10334 /// Diagnose invalid arithmetic on two void pointers.
10335 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10336                                                 Expr *LHSExpr, Expr *RHSExpr) {
10337   S.Diag(Loc, S.getLangOpts().CPlusPlus
10338                 ? diag::err_typecheck_pointer_arith_void_type
10339                 : diag::ext_gnu_void_ptr)
10340     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10341                             << RHSExpr->getSourceRange();
10342 }
10343 
10344 /// Diagnose invalid arithmetic on a void pointer.
10345 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10346                                             Expr *Pointer) {
10347   S.Diag(Loc, S.getLangOpts().CPlusPlus
10348                 ? diag::err_typecheck_pointer_arith_void_type
10349                 : diag::ext_gnu_void_ptr)
10350     << 0 /* one pointer */ << Pointer->getSourceRange();
10351 }
10352 
10353 /// Diagnose invalid arithmetic on a null pointer.
10354 ///
10355 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10356 /// idiom, which we recognize as a GNU extension.
10357 ///
10358 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10359                                             Expr *Pointer, bool IsGNUIdiom) {
10360   if (IsGNUIdiom)
10361     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10362       << Pointer->getSourceRange();
10363   else
10364     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10365       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10366 }
10367 
10368 /// Diagnose invalid arithmetic on two function pointers.
10369 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10370                                                     Expr *LHS, Expr *RHS) {
10371   assert(LHS->getType()->isAnyPointerType());
10372   assert(RHS->getType()->isAnyPointerType());
10373   S.Diag(Loc, S.getLangOpts().CPlusPlus
10374                 ? diag::err_typecheck_pointer_arith_function_type
10375                 : diag::ext_gnu_ptr_func_arith)
10376     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10377     // We only show the second type if it differs from the first.
10378     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10379                                                    RHS->getType())
10380     << RHS->getType()->getPointeeType()
10381     << LHS->getSourceRange() << RHS->getSourceRange();
10382 }
10383 
10384 /// Diagnose invalid arithmetic on a function pointer.
10385 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10386                                                 Expr *Pointer) {
10387   assert(Pointer->getType()->isAnyPointerType());
10388   S.Diag(Loc, S.getLangOpts().CPlusPlus
10389                 ? diag::err_typecheck_pointer_arith_function_type
10390                 : diag::ext_gnu_ptr_func_arith)
10391     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10392     << 0 /* one pointer, so only one type */
10393     << Pointer->getSourceRange();
10394 }
10395 
10396 /// Emit error if Operand is incomplete pointer type
10397 ///
10398 /// \returns True if pointer has incomplete type
10399 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10400                                                  Expr *Operand) {
10401   QualType ResType = Operand->getType();
10402   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10403     ResType = ResAtomicType->getValueType();
10404 
10405   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10406   QualType PointeeTy = ResType->getPointeeType();
10407   return S.RequireCompleteSizedType(
10408       Loc, PointeeTy,
10409       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10410       Operand->getSourceRange());
10411 }
10412 
10413 /// Check the validity of an arithmetic pointer operand.
10414 ///
10415 /// If the operand has pointer type, this code will check for pointer types
10416 /// which are invalid in arithmetic operations. These will be diagnosed
10417 /// appropriately, including whether or not the use is supported as an
10418 /// extension.
10419 ///
10420 /// \returns True when the operand is valid to use (even if as an extension).
10421 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10422                                             Expr *Operand) {
10423   QualType ResType = Operand->getType();
10424   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10425     ResType = ResAtomicType->getValueType();
10426 
10427   if (!ResType->isAnyPointerType()) return true;
10428 
10429   QualType PointeeTy = ResType->getPointeeType();
10430   if (PointeeTy->isVoidType()) {
10431     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10432     return !S.getLangOpts().CPlusPlus;
10433   }
10434   if (PointeeTy->isFunctionType()) {
10435     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10436     return !S.getLangOpts().CPlusPlus;
10437   }
10438 
10439   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10440 
10441   return true;
10442 }
10443 
10444 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10445 /// operands.
10446 ///
10447 /// This routine will diagnose any invalid arithmetic on pointer operands much
10448 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10449 /// for emitting a single diagnostic even for operations where both LHS and RHS
10450 /// are (potentially problematic) pointers.
10451 ///
10452 /// \returns True when the operand is valid to use (even if as an extension).
10453 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10454                                                 Expr *LHSExpr, Expr *RHSExpr) {
10455   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10456   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10457   if (!isLHSPointer && !isRHSPointer) return true;
10458 
10459   QualType LHSPointeeTy, RHSPointeeTy;
10460   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10461   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10462 
10463   // if both are pointers check if operation is valid wrt address spaces
10464   if (isLHSPointer && isRHSPointer) {
10465     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10466       S.Diag(Loc,
10467              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10468           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10469           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10470       return false;
10471     }
10472   }
10473 
10474   // Check for arithmetic on pointers to incomplete types.
10475   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10476   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10477   if (isLHSVoidPtr || isRHSVoidPtr) {
10478     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10479     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10480     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10481 
10482     return !S.getLangOpts().CPlusPlus;
10483   }
10484 
10485   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10486   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10487   if (isLHSFuncPtr || isRHSFuncPtr) {
10488     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10489     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10490                                                                 RHSExpr);
10491     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10492 
10493     return !S.getLangOpts().CPlusPlus;
10494   }
10495 
10496   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10497     return false;
10498   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10499     return false;
10500 
10501   return true;
10502 }
10503 
10504 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10505 /// literal.
10506 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10507                                   Expr *LHSExpr, Expr *RHSExpr) {
10508   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10509   Expr* IndexExpr = RHSExpr;
10510   if (!StrExpr) {
10511     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10512     IndexExpr = LHSExpr;
10513   }
10514 
10515   bool IsStringPlusInt = StrExpr &&
10516       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10517   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10518     return;
10519 
10520   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10521   Self.Diag(OpLoc, diag::warn_string_plus_int)
10522       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10523 
10524   // Only print a fixit for "str" + int, not for int + "str".
10525   if (IndexExpr == RHSExpr) {
10526     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10527     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10528         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10529         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10530         << FixItHint::CreateInsertion(EndLoc, "]");
10531   } else
10532     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10533 }
10534 
10535 /// Emit a warning when adding a char literal to a string.
10536 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10537                                    Expr *LHSExpr, Expr *RHSExpr) {
10538   const Expr *StringRefExpr = LHSExpr;
10539   const CharacterLiteral *CharExpr =
10540       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10541 
10542   if (!CharExpr) {
10543     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10544     StringRefExpr = RHSExpr;
10545   }
10546 
10547   if (!CharExpr || !StringRefExpr)
10548     return;
10549 
10550   const QualType StringType = StringRefExpr->getType();
10551 
10552   // Return if not a PointerType.
10553   if (!StringType->isAnyPointerType())
10554     return;
10555 
10556   // Return if not a CharacterType.
10557   if (!StringType->getPointeeType()->isAnyCharacterType())
10558     return;
10559 
10560   ASTContext &Ctx = Self.getASTContext();
10561   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10562 
10563   const QualType CharType = CharExpr->getType();
10564   if (!CharType->isAnyCharacterType() &&
10565       CharType->isIntegerType() &&
10566       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10567     Self.Diag(OpLoc, diag::warn_string_plus_char)
10568         << DiagRange << Ctx.CharTy;
10569   } else {
10570     Self.Diag(OpLoc, diag::warn_string_plus_char)
10571         << DiagRange << CharExpr->getType();
10572   }
10573 
10574   // Only print a fixit for str + char, not for char + str.
10575   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10576     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10577     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10578         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10579         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10580         << FixItHint::CreateInsertion(EndLoc, "]");
10581   } else {
10582     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10583   }
10584 }
10585 
10586 /// Emit error when two pointers are incompatible.
10587 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10588                                            Expr *LHSExpr, Expr *RHSExpr) {
10589   assert(LHSExpr->getType()->isAnyPointerType());
10590   assert(RHSExpr->getType()->isAnyPointerType());
10591   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10592     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10593     << RHSExpr->getSourceRange();
10594 }
10595 
10596 // C99 6.5.6
10597 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10598                                      SourceLocation Loc, BinaryOperatorKind Opc,
10599                                      QualType* CompLHSTy) {
10600   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10601 
10602   if (LHS.get()->getType()->isVectorType() ||
10603       RHS.get()->getType()->isVectorType()) {
10604     QualType compType = CheckVectorOperands(
10605         LHS, RHS, Loc, CompLHSTy,
10606         /*AllowBothBool*/getLangOpts().AltiVec,
10607         /*AllowBoolConversions*/getLangOpts().ZVector);
10608     if (CompLHSTy) *CompLHSTy = compType;
10609     return compType;
10610   }
10611 
10612   if (LHS.get()->getType()->isConstantMatrixType() ||
10613       RHS.get()->getType()->isConstantMatrixType()) {
10614     QualType compType =
10615         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10616     if (CompLHSTy)
10617       *CompLHSTy = compType;
10618     return compType;
10619   }
10620 
10621   QualType compType = UsualArithmeticConversions(
10622       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10623   if (LHS.isInvalid() || RHS.isInvalid())
10624     return QualType();
10625 
10626   // Diagnose "string literal" '+' int and string '+' "char literal".
10627   if (Opc == BO_Add) {
10628     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10629     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10630   }
10631 
10632   // handle the common case first (both operands are arithmetic).
10633   if (!compType.isNull() && compType->isArithmeticType()) {
10634     if (CompLHSTy) *CompLHSTy = compType;
10635     return compType;
10636   }
10637 
10638   // Type-checking.  Ultimately the pointer's going to be in PExp;
10639   // note that we bias towards the LHS being the pointer.
10640   Expr *PExp = LHS.get(), *IExp = RHS.get();
10641 
10642   bool isObjCPointer;
10643   if (PExp->getType()->isPointerType()) {
10644     isObjCPointer = false;
10645   } else if (PExp->getType()->isObjCObjectPointerType()) {
10646     isObjCPointer = true;
10647   } else {
10648     std::swap(PExp, IExp);
10649     if (PExp->getType()->isPointerType()) {
10650       isObjCPointer = false;
10651     } else if (PExp->getType()->isObjCObjectPointerType()) {
10652       isObjCPointer = true;
10653     } else {
10654       return InvalidOperands(Loc, LHS, RHS);
10655     }
10656   }
10657   assert(PExp->getType()->isAnyPointerType());
10658 
10659   if (!IExp->getType()->isIntegerType())
10660     return InvalidOperands(Loc, LHS, RHS);
10661 
10662   // Adding to a null pointer results in undefined behavior.
10663   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10664           Context, Expr::NPC_ValueDependentIsNotNull)) {
10665     // In C++ adding zero to a null pointer is defined.
10666     Expr::EvalResult KnownVal;
10667     if (!getLangOpts().CPlusPlus ||
10668         (!IExp->isValueDependent() &&
10669          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10670           KnownVal.Val.getInt() != 0))) {
10671       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10672       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10673           Context, BO_Add, PExp, IExp);
10674       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10675     }
10676   }
10677 
10678   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10679     return QualType();
10680 
10681   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10682     return QualType();
10683 
10684   // Check array bounds for pointer arithemtic
10685   CheckArrayAccess(PExp, IExp);
10686 
10687   if (CompLHSTy) {
10688     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10689     if (LHSTy.isNull()) {
10690       LHSTy = LHS.get()->getType();
10691       if (LHSTy->isPromotableIntegerType())
10692         LHSTy = Context.getPromotedIntegerType(LHSTy);
10693     }
10694     *CompLHSTy = LHSTy;
10695   }
10696 
10697   return PExp->getType();
10698 }
10699 
10700 // C99 6.5.6
10701 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10702                                         SourceLocation Loc,
10703                                         QualType* CompLHSTy) {
10704   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10705 
10706   if (LHS.get()->getType()->isVectorType() ||
10707       RHS.get()->getType()->isVectorType()) {
10708     QualType compType = CheckVectorOperands(
10709         LHS, RHS, Loc, CompLHSTy,
10710         /*AllowBothBool*/getLangOpts().AltiVec,
10711         /*AllowBoolConversions*/getLangOpts().ZVector);
10712     if (CompLHSTy) *CompLHSTy = compType;
10713     return compType;
10714   }
10715 
10716   if (LHS.get()->getType()->isConstantMatrixType() ||
10717       RHS.get()->getType()->isConstantMatrixType()) {
10718     QualType compType =
10719         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10720     if (CompLHSTy)
10721       *CompLHSTy = compType;
10722     return compType;
10723   }
10724 
10725   QualType compType = UsualArithmeticConversions(
10726       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10727   if (LHS.isInvalid() || RHS.isInvalid())
10728     return QualType();
10729 
10730   // Enforce type constraints: C99 6.5.6p3.
10731 
10732   // Handle the common case first (both operands are arithmetic).
10733   if (!compType.isNull() && compType->isArithmeticType()) {
10734     if (CompLHSTy) *CompLHSTy = compType;
10735     return compType;
10736   }
10737 
10738   // Either ptr - int   or   ptr - ptr.
10739   if (LHS.get()->getType()->isAnyPointerType()) {
10740     QualType lpointee = LHS.get()->getType()->getPointeeType();
10741 
10742     // Diagnose bad cases where we step over interface counts.
10743     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10744         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10745       return QualType();
10746 
10747     // The result type of a pointer-int computation is the pointer type.
10748     if (RHS.get()->getType()->isIntegerType()) {
10749       // Subtracting from a null pointer should produce a warning.
10750       // The last argument to the diagnose call says this doesn't match the
10751       // GNU int-to-pointer idiom.
10752       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10753                                            Expr::NPC_ValueDependentIsNotNull)) {
10754         // In C++ adding zero to a null pointer is defined.
10755         Expr::EvalResult KnownVal;
10756         if (!getLangOpts().CPlusPlus ||
10757             (!RHS.get()->isValueDependent() &&
10758              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10759               KnownVal.Val.getInt() != 0))) {
10760           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10761         }
10762       }
10763 
10764       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10765         return QualType();
10766 
10767       // Check array bounds for pointer arithemtic
10768       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10769                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10770 
10771       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10772       return LHS.get()->getType();
10773     }
10774 
10775     // Handle pointer-pointer subtractions.
10776     if (const PointerType *RHSPTy
10777           = RHS.get()->getType()->getAs<PointerType>()) {
10778       QualType rpointee = RHSPTy->getPointeeType();
10779 
10780       if (getLangOpts().CPlusPlus) {
10781         // Pointee types must be the same: C++ [expr.add]
10782         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10783           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10784         }
10785       } else {
10786         // Pointee types must be compatible C99 6.5.6p3
10787         if (!Context.typesAreCompatible(
10788                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10789                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10790           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10791           return QualType();
10792         }
10793       }
10794 
10795       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10796                                                LHS.get(), RHS.get()))
10797         return QualType();
10798 
10799       // FIXME: Add warnings for nullptr - ptr.
10800 
10801       // The pointee type may have zero size.  As an extension, a structure or
10802       // union may have zero size or an array may have zero length.  In this
10803       // case subtraction does not make sense.
10804       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10805         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10806         if (ElementSize.isZero()) {
10807           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10808             << rpointee.getUnqualifiedType()
10809             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10810         }
10811       }
10812 
10813       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10814       return Context.getPointerDiffType();
10815     }
10816   }
10817 
10818   return InvalidOperands(Loc, LHS, RHS);
10819 }
10820 
10821 static bool isScopedEnumerationType(QualType T) {
10822   if (const EnumType *ET = T->getAs<EnumType>())
10823     return ET->getDecl()->isScoped();
10824   return false;
10825 }
10826 
10827 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10828                                    SourceLocation Loc, BinaryOperatorKind Opc,
10829                                    QualType LHSType) {
10830   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10831   // so skip remaining warnings as we don't want to modify values within Sema.
10832   if (S.getLangOpts().OpenCL)
10833     return;
10834 
10835   // Check right/shifter operand
10836   Expr::EvalResult RHSResult;
10837   if (RHS.get()->isValueDependent() ||
10838       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10839     return;
10840   llvm::APSInt Right = RHSResult.Val.getInt();
10841 
10842   if (Right.isNegative()) {
10843     S.DiagRuntimeBehavior(Loc, RHS.get(),
10844                           S.PDiag(diag::warn_shift_negative)
10845                             << RHS.get()->getSourceRange());
10846     return;
10847   }
10848 
10849   QualType LHSExprType = LHS.get()->getType();
10850   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10851   if (LHSExprType->isExtIntType())
10852     LeftSize = S.Context.getIntWidth(LHSExprType);
10853   else if (LHSExprType->isFixedPointType()) {
10854     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10855     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10856   }
10857   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10858   if (Right.uge(LeftBits)) {
10859     S.DiagRuntimeBehavior(Loc, RHS.get(),
10860                           S.PDiag(diag::warn_shift_gt_typewidth)
10861                             << RHS.get()->getSourceRange());
10862     return;
10863   }
10864 
10865   // FIXME: We probably need to handle fixed point types specially here.
10866   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10867     return;
10868 
10869   // When left shifting an ICE which is signed, we can check for overflow which
10870   // according to C++ standards prior to C++2a has undefined behavior
10871   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10872   // more than the maximum value representable in the result type, so never
10873   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10874   // expression is still probably a bug.)
10875   Expr::EvalResult LHSResult;
10876   if (LHS.get()->isValueDependent() ||
10877       LHSType->hasUnsignedIntegerRepresentation() ||
10878       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10879     return;
10880   llvm::APSInt Left = LHSResult.Val.getInt();
10881 
10882   // If LHS does not have a signed type and non-negative value
10883   // then, the behavior is undefined before C++2a. Warn about it.
10884   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10885       !S.getLangOpts().CPlusPlus20) {
10886     S.DiagRuntimeBehavior(Loc, LHS.get(),
10887                           S.PDiag(diag::warn_shift_lhs_negative)
10888                             << LHS.get()->getSourceRange());
10889     return;
10890   }
10891 
10892   llvm::APInt ResultBits =
10893       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10894   if (LeftBits.uge(ResultBits))
10895     return;
10896   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10897   Result = Result.shl(Right);
10898 
10899   // Print the bit representation of the signed integer as an unsigned
10900   // hexadecimal number.
10901   SmallString<40> HexResult;
10902   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10903 
10904   // If we are only missing a sign bit, this is less likely to result in actual
10905   // bugs -- if the result is cast back to an unsigned type, it will have the
10906   // expected value. Thus we place this behind a different warning that can be
10907   // turned off separately if needed.
10908   if (LeftBits == ResultBits - 1) {
10909     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10910         << HexResult << LHSType
10911         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10912     return;
10913   }
10914 
10915   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10916     << HexResult.str() << Result.getMinSignedBits() << LHSType
10917     << Left.getBitWidth() << LHS.get()->getSourceRange()
10918     << RHS.get()->getSourceRange();
10919 }
10920 
10921 /// Return the resulting type when a vector is shifted
10922 ///        by a scalar or vector shift amount.
10923 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10924                                  SourceLocation Loc, bool IsCompAssign) {
10925   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10926   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10927       !LHS.get()->getType()->isVectorType()) {
10928     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10929       << RHS.get()->getType() << LHS.get()->getType()
10930       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10931     return QualType();
10932   }
10933 
10934   if (!IsCompAssign) {
10935     LHS = S.UsualUnaryConversions(LHS.get());
10936     if (LHS.isInvalid()) return QualType();
10937   }
10938 
10939   RHS = S.UsualUnaryConversions(RHS.get());
10940   if (RHS.isInvalid()) return QualType();
10941 
10942   QualType LHSType = LHS.get()->getType();
10943   // Note that LHS might be a scalar because the routine calls not only in
10944   // OpenCL case.
10945   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10946   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10947 
10948   // Note that RHS might not be a vector.
10949   QualType RHSType = RHS.get()->getType();
10950   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10951   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10952 
10953   // The operands need to be integers.
10954   if (!LHSEleType->isIntegerType()) {
10955     S.Diag(Loc, diag::err_typecheck_expect_int)
10956       << LHS.get()->getType() << LHS.get()->getSourceRange();
10957     return QualType();
10958   }
10959 
10960   if (!RHSEleType->isIntegerType()) {
10961     S.Diag(Loc, diag::err_typecheck_expect_int)
10962       << RHS.get()->getType() << RHS.get()->getSourceRange();
10963     return QualType();
10964   }
10965 
10966   if (!LHSVecTy) {
10967     assert(RHSVecTy);
10968     if (IsCompAssign)
10969       return RHSType;
10970     if (LHSEleType != RHSEleType) {
10971       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10972       LHSEleType = RHSEleType;
10973     }
10974     QualType VecTy =
10975         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10976     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10977     LHSType = VecTy;
10978   } else if (RHSVecTy) {
10979     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10980     // are applied component-wise. So if RHS is a vector, then ensure
10981     // that the number of elements is the same as LHS...
10982     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10983       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10984         << LHS.get()->getType() << RHS.get()->getType()
10985         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10986       return QualType();
10987     }
10988     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10989       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10990       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10991       if (LHSBT != RHSBT &&
10992           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10993         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10994             << LHS.get()->getType() << RHS.get()->getType()
10995             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10996       }
10997     }
10998   } else {
10999     // ...else expand RHS to match the number of elements in LHS.
11000     QualType VecTy =
11001       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11002     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11003   }
11004 
11005   return LHSType;
11006 }
11007 
11008 // C99 6.5.7
11009 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11010                                   SourceLocation Loc, BinaryOperatorKind Opc,
11011                                   bool IsCompAssign) {
11012   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11013 
11014   // Vector shifts promote their scalar inputs to vector type.
11015   if (LHS.get()->getType()->isVectorType() ||
11016       RHS.get()->getType()->isVectorType()) {
11017     if (LangOpts.ZVector) {
11018       // The shift operators for the z vector extensions work basically
11019       // like general shifts, except that neither the LHS nor the RHS is
11020       // allowed to be a "vector bool".
11021       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11022         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11023           return InvalidOperands(Loc, LHS, RHS);
11024       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11025         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11026           return InvalidOperands(Loc, LHS, RHS);
11027     }
11028     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11029   }
11030 
11031   // Shifts don't perform usual arithmetic conversions, they just do integer
11032   // promotions on each operand. C99 6.5.7p3
11033 
11034   // For the LHS, do usual unary conversions, but then reset them away
11035   // if this is a compound assignment.
11036   ExprResult OldLHS = LHS;
11037   LHS = UsualUnaryConversions(LHS.get());
11038   if (LHS.isInvalid())
11039     return QualType();
11040   QualType LHSType = LHS.get()->getType();
11041   if (IsCompAssign) LHS = OldLHS;
11042 
11043   // The RHS is simpler.
11044   RHS = UsualUnaryConversions(RHS.get());
11045   if (RHS.isInvalid())
11046     return QualType();
11047   QualType RHSType = RHS.get()->getType();
11048 
11049   // C99 6.5.7p2: Each of the operands shall have integer type.
11050   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11051   if ((!LHSType->isFixedPointOrIntegerType() &&
11052        !LHSType->hasIntegerRepresentation()) ||
11053       !RHSType->hasIntegerRepresentation())
11054     return InvalidOperands(Loc, LHS, RHS);
11055 
11056   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11057   // hasIntegerRepresentation() above instead of this.
11058   if (isScopedEnumerationType(LHSType) ||
11059       isScopedEnumerationType(RHSType)) {
11060     return InvalidOperands(Loc, LHS, RHS);
11061   }
11062   // Sanity-check shift operands
11063   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11064 
11065   // "The type of the result is that of the promoted left operand."
11066   return LHSType;
11067 }
11068 
11069 /// Diagnose bad pointer comparisons.
11070 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11071                                               ExprResult &LHS, ExprResult &RHS,
11072                                               bool IsError) {
11073   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11074                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11075     << LHS.get()->getType() << RHS.get()->getType()
11076     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11077 }
11078 
11079 /// Returns false if the pointers are converted to a composite type,
11080 /// true otherwise.
11081 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11082                                            ExprResult &LHS, ExprResult &RHS) {
11083   // C++ [expr.rel]p2:
11084   //   [...] Pointer conversions (4.10) and qualification
11085   //   conversions (4.4) are performed on pointer operands (or on
11086   //   a pointer operand and a null pointer constant) to bring
11087   //   them to their composite pointer type. [...]
11088   //
11089   // C++ [expr.eq]p1 uses the same notion for (in)equality
11090   // comparisons of pointers.
11091 
11092   QualType LHSType = LHS.get()->getType();
11093   QualType RHSType = RHS.get()->getType();
11094   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11095          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11096 
11097   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11098   if (T.isNull()) {
11099     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11100         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11101       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11102     else
11103       S.InvalidOperands(Loc, LHS, RHS);
11104     return true;
11105   }
11106 
11107   return false;
11108 }
11109 
11110 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11111                                                     ExprResult &LHS,
11112                                                     ExprResult &RHS,
11113                                                     bool IsError) {
11114   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11115                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11116     << LHS.get()->getType() << RHS.get()->getType()
11117     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11118 }
11119 
11120 static bool isObjCObjectLiteral(ExprResult &E) {
11121   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11122   case Stmt::ObjCArrayLiteralClass:
11123   case Stmt::ObjCDictionaryLiteralClass:
11124   case Stmt::ObjCStringLiteralClass:
11125   case Stmt::ObjCBoxedExprClass:
11126     return true;
11127   default:
11128     // Note that ObjCBoolLiteral is NOT an object literal!
11129     return false;
11130   }
11131 }
11132 
11133 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11134   const ObjCObjectPointerType *Type =
11135     LHS->getType()->getAs<ObjCObjectPointerType>();
11136 
11137   // If this is not actually an Objective-C object, bail out.
11138   if (!Type)
11139     return false;
11140 
11141   // Get the LHS object's interface type.
11142   QualType InterfaceType = Type->getPointeeType();
11143 
11144   // If the RHS isn't an Objective-C object, bail out.
11145   if (!RHS->getType()->isObjCObjectPointerType())
11146     return false;
11147 
11148   // Try to find the -isEqual: method.
11149   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11150   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11151                                                       InterfaceType,
11152                                                       /*IsInstance=*/true);
11153   if (!Method) {
11154     if (Type->isObjCIdType()) {
11155       // For 'id', just check the global pool.
11156       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11157                                                   /*receiverId=*/true);
11158     } else {
11159       // Check protocols.
11160       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11161                                              /*IsInstance=*/true);
11162     }
11163   }
11164 
11165   if (!Method)
11166     return false;
11167 
11168   QualType T = Method->parameters()[0]->getType();
11169   if (!T->isObjCObjectPointerType())
11170     return false;
11171 
11172   QualType R = Method->getReturnType();
11173   if (!R->isScalarType())
11174     return false;
11175 
11176   return true;
11177 }
11178 
11179 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11180   FromE = FromE->IgnoreParenImpCasts();
11181   switch (FromE->getStmtClass()) {
11182     default:
11183       break;
11184     case Stmt::ObjCStringLiteralClass:
11185       // "string literal"
11186       return LK_String;
11187     case Stmt::ObjCArrayLiteralClass:
11188       // "array literal"
11189       return LK_Array;
11190     case Stmt::ObjCDictionaryLiteralClass:
11191       // "dictionary literal"
11192       return LK_Dictionary;
11193     case Stmt::BlockExprClass:
11194       return LK_Block;
11195     case Stmt::ObjCBoxedExprClass: {
11196       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11197       switch (Inner->getStmtClass()) {
11198         case Stmt::IntegerLiteralClass:
11199         case Stmt::FloatingLiteralClass:
11200         case Stmt::CharacterLiteralClass:
11201         case Stmt::ObjCBoolLiteralExprClass:
11202         case Stmt::CXXBoolLiteralExprClass:
11203           // "numeric literal"
11204           return LK_Numeric;
11205         case Stmt::ImplicitCastExprClass: {
11206           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11207           // Boolean literals can be represented by implicit casts.
11208           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11209             return LK_Numeric;
11210           break;
11211         }
11212         default:
11213           break;
11214       }
11215       return LK_Boxed;
11216     }
11217   }
11218   return LK_None;
11219 }
11220 
11221 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11222                                           ExprResult &LHS, ExprResult &RHS,
11223                                           BinaryOperator::Opcode Opc){
11224   Expr *Literal;
11225   Expr *Other;
11226   if (isObjCObjectLiteral(LHS)) {
11227     Literal = LHS.get();
11228     Other = RHS.get();
11229   } else {
11230     Literal = RHS.get();
11231     Other = LHS.get();
11232   }
11233 
11234   // Don't warn on comparisons against nil.
11235   Other = Other->IgnoreParenCasts();
11236   if (Other->isNullPointerConstant(S.getASTContext(),
11237                                    Expr::NPC_ValueDependentIsNotNull))
11238     return;
11239 
11240   // This should be kept in sync with warn_objc_literal_comparison.
11241   // LK_String should always be after the other literals, since it has its own
11242   // warning flag.
11243   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11244   assert(LiteralKind != Sema::LK_Block);
11245   if (LiteralKind == Sema::LK_None) {
11246     llvm_unreachable("Unknown Objective-C object literal kind");
11247   }
11248 
11249   if (LiteralKind == Sema::LK_String)
11250     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11251       << Literal->getSourceRange();
11252   else
11253     S.Diag(Loc, diag::warn_objc_literal_comparison)
11254       << LiteralKind << Literal->getSourceRange();
11255 
11256   if (BinaryOperator::isEqualityOp(Opc) &&
11257       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11258     SourceLocation Start = LHS.get()->getBeginLoc();
11259     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11260     CharSourceRange OpRange =
11261       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11262 
11263     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11264       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11265       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11266       << FixItHint::CreateInsertion(End, "]");
11267   }
11268 }
11269 
11270 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11271 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11272                                            ExprResult &RHS, SourceLocation Loc,
11273                                            BinaryOperatorKind Opc) {
11274   // Check that left hand side is !something.
11275   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11276   if (!UO || UO->getOpcode() != UO_LNot) return;
11277 
11278   // Only check if the right hand side is non-bool arithmetic type.
11279   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11280 
11281   // Make sure that the something in !something is not bool.
11282   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11283   if (SubExpr->isKnownToHaveBooleanValue()) return;
11284 
11285   // Emit warning.
11286   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11287   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11288       << Loc << IsBitwiseOp;
11289 
11290   // First note suggest !(x < y)
11291   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11292   SourceLocation FirstClose = RHS.get()->getEndLoc();
11293   FirstClose = S.getLocForEndOfToken(FirstClose);
11294   if (FirstClose.isInvalid())
11295     FirstOpen = SourceLocation();
11296   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11297       << IsBitwiseOp
11298       << FixItHint::CreateInsertion(FirstOpen, "(")
11299       << FixItHint::CreateInsertion(FirstClose, ")");
11300 
11301   // Second note suggests (!x) < y
11302   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11303   SourceLocation SecondClose = LHS.get()->getEndLoc();
11304   SecondClose = S.getLocForEndOfToken(SecondClose);
11305   if (SecondClose.isInvalid())
11306     SecondOpen = SourceLocation();
11307   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11308       << FixItHint::CreateInsertion(SecondOpen, "(")
11309       << FixItHint::CreateInsertion(SecondClose, ")");
11310 }
11311 
11312 // Returns true if E refers to a non-weak array.
11313 static bool checkForArray(const Expr *E) {
11314   const ValueDecl *D = nullptr;
11315   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11316     D = DR->getDecl();
11317   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11318     if (Mem->isImplicitAccess())
11319       D = Mem->getMemberDecl();
11320   }
11321   if (!D)
11322     return false;
11323   return D->getType()->isArrayType() && !D->isWeak();
11324 }
11325 
11326 /// Diagnose some forms of syntactically-obvious tautological comparison.
11327 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11328                                            Expr *LHS, Expr *RHS,
11329                                            BinaryOperatorKind Opc) {
11330   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11331   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11332 
11333   QualType LHSType = LHS->getType();
11334   QualType RHSType = RHS->getType();
11335   if (LHSType->hasFloatingRepresentation() ||
11336       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11337       S.inTemplateInstantiation())
11338     return;
11339 
11340   // Comparisons between two array types are ill-formed for operator<=>, so
11341   // we shouldn't emit any additional warnings about it.
11342   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11343     return;
11344 
11345   // For non-floating point types, check for self-comparisons of the form
11346   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11347   // often indicate logic errors in the program.
11348   //
11349   // NOTE: Don't warn about comparison expressions resulting from macro
11350   // expansion. Also don't warn about comparisons which are only self
11351   // comparisons within a template instantiation. The warnings should catch
11352   // obvious cases in the definition of the template anyways. The idea is to
11353   // warn when the typed comparison operator will always evaluate to the same
11354   // result.
11355 
11356   // Used for indexing into %select in warn_comparison_always
11357   enum {
11358     AlwaysConstant,
11359     AlwaysTrue,
11360     AlwaysFalse,
11361     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11362   };
11363 
11364   // C++2a [depr.array.comp]:
11365   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11366   //   operands of array type are deprecated.
11367   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11368       RHSStripped->getType()->isArrayType()) {
11369     S.Diag(Loc, diag::warn_depr_array_comparison)
11370         << LHS->getSourceRange() << RHS->getSourceRange()
11371         << LHSStripped->getType() << RHSStripped->getType();
11372     // Carry on to produce the tautological comparison warning, if this
11373     // expression is potentially-evaluated, we can resolve the array to a
11374     // non-weak declaration, and so on.
11375   }
11376 
11377   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11378     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11379       unsigned Result;
11380       switch (Opc) {
11381       case BO_EQ:
11382       case BO_LE:
11383       case BO_GE:
11384         Result = AlwaysTrue;
11385         break;
11386       case BO_NE:
11387       case BO_LT:
11388       case BO_GT:
11389         Result = AlwaysFalse;
11390         break;
11391       case BO_Cmp:
11392         Result = AlwaysEqual;
11393         break;
11394       default:
11395         Result = AlwaysConstant;
11396         break;
11397       }
11398       S.DiagRuntimeBehavior(Loc, nullptr,
11399                             S.PDiag(diag::warn_comparison_always)
11400                                 << 0 /*self-comparison*/
11401                                 << Result);
11402     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11403       // What is it always going to evaluate to?
11404       unsigned Result;
11405       switch (Opc) {
11406       case BO_EQ: // e.g. array1 == array2
11407         Result = AlwaysFalse;
11408         break;
11409       case BO_NE: // e.g. array1 != array2
11410         Result = AlwaysTrue;
11411         break;
11412       default: // e.g. array1 <= array2
11413         // The best we can say is 'a constant'
11414         Result = AlwaysConstant;
11415         break;
11416       }
11417       S.DiagRuntimeBehavior(Loc, nullptr,
11418                             S.PDiag(diag::warn_comparison_always)
11419                                 << 1 /*array comparison*/
11420                                 << Result);
11421     }
11422   }
11423 
11424   if (isa<CastExpr>(LHSStripped))
11425     LHSStripped = LHSStripped->IgnoreParenCasts();
11426   if (isa<CastExpr>(RHSStripped))
11427     RHSStripped = RHSStripped->IgnoreParenCasts();
11428 
11429   // Warn about comparisons against a string constant (unless the other
11430   // operand is null); the user probably wants string comparison function.
11431   Expr *LiteralString = nullptr;
11432   Expr *LiteralStringStripped = nullptr;
11433   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11434       !RHSStripped->isNullPointerConstant(S.Context,
11435                                           Expr::NPC_ValueDependentIsNull)) {
11436     LiteralString = LHS;
11437     LiteralStringStripped = LHSStripped;
11438   } else if ((isa<StringLiteral>(RHSStripped) ||
11439               isa<ObjCEncodeExpr>(RHSStripped)) &&
11440              !LHSStripped->isNullPointerConstant(S.Context,
11441                                           Expr::NPC_ValueDependentIsNull)) {
11442     LiteralString = RHS;
11443     LiteralStringStripped = RHSStripped;
11444   }
11445 
11446   if (LiteralString) {
11447     S.DiagRuntimeBehavior(Loc, nullptr,
11448                           S.PDiag(diag::warn_stringcompare)
11449                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11450                               << LiteralString->getSourceRange());
11451   }
11452 }
11453 
11454 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11455   switch (CK) {
11456   default: {
11457 #ifndef NDEBUG
11458     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11459                  << "\n";
11460 #endif
11461     llvm_unreachable("unhandled cast kind");
11462   }
11463   case CK_UserDefinedConversion:
11464     return ICK_Identity;
11465   case CK_LValueToRValue:
11466     return ICK_Lvalue_To_Rvalue;
11467   case CK_ArrayToPointerDecay:
11468     return ICK_Array_To_Pointer;
11469   case CK_FunctionToPointerDecay:
11470     return ICK_Function_To_Pointer;
11471   case CK_IntegralCast:
11472     return ICK_Integral_Conversion;
11473   case CK_FloatingCast:
11474     return ICK_Floating_Conversion;
11475   case CK_IntegralToFloating:
11476   case CK_FloatingToIntegral:
11477     return ICK_Floating_Integral;
11478   case CK_IntegralComplexCast:
11479   case CK_FloatingComplexCast:
11480   case CK_FloatingComplexToIntegralComplex:
11481   case CK_IntegralComplexToFloatingComplex:
11482     return ICK_Complex_Conversion;
11483   case CK_FloatingComplexToReal:
11484   case CK_FloatingRealToComplex:
11485   case CK_IntegralComplexToReal:
11486   case CK_IntegralRealToComplex:
11487     return ICK_Complex_Real;
11488   }
11489 }
11490 
11491 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11492                                              QualType FromType,
11493                                              SourceLocation Loc) {
11494   // Check for a narrowing implicit conversion.
11495   StandardConversionSequence SCS;
11496   SCS.setAsIdentityConversion();
11497   SCS.setToType(0, FromType);
11498   SCS.setToType(1, ToType);
11499   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11500     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11501 
11502   APValue PreNarrowingValue;
11503   QualType PreNarrowingType;
11504   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11505                                PreNarrowingType,
11506                                /*IgnoreFloatToIntegralConversion*/ true)) {
11507   case NK_Dependent_Narrowing:
11508     // Implicit conversion to a narrower type, but the expression is
11509     // value-dependent so we can't tell whether it's actually narrowing.
11510   case NK_Not_Narrowing:
11511     return false;
11512 
11513   case NK_Constant_Narrowing:
11514     // Implicit conversion to a narrower type, and the value is not a constant
11515     // expression.
11516     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11517         << /*Constant*/ 1
11518         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11519     return true;
11520 
11521   case NK_Variable_Narrowing:
11522     // Implicit conversion to a narrower type, and the value is not a constant
11523     // expression.
11524   case NK_Type_Narrowing:
11525     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11526         << /*Constant*/ 0 << FromType << ToType;
11527     // TODO: It's not a constant expression, but what if the user intended it
11528     // to be? Can we produce notes to help them figure out why it isn't?
11529     return true;
11530   }
11531   llvm_unreachable("unhandled case in switch");
11532 }
11533 
11534 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11535                                                          ExprResult &LHS,
11536                                                          ExprResult &RHS,
11537                                                          SourceLocation Loc) {
11538   QualType LHSType = LHS.get()->getType();
11539   QualType RHSType = RHS.get()->getType();
11540   // Dig out the original argument type and expression before implicit casts
11541   // were applied. These are the types/expressions we need to check the
11542   // [expr.spaceship] requirements against.
11543   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11544   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11545   QualType LHSStrippedType = LHSStripped.get()->getType();
11546   QualType RHSStrippedType = RHSStripped.get()->getType();
11547 
11548   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11549   // other is not, the program is ill-formed.
11550   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11551     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11552     return QualType();
11553   }
11554 
11555   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11556   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11557                     RHSStrippedType->isEnumeralType();
11558   if (NumEnumArgs == 1) {
11559     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11560     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11561     if (OtherTy->hasFloatingRepresentation()) {
11562       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11563       return QualType();
11564     }
11565   }
11566   if (NumEnumArgs == 2) {
11567     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11568     // type E, the operator yields the result of converting the operands
11569     // to the underlying type of E and applying <=> to the converted operands.
11570     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11571       S.InvalidOperands(Loc, LHS, RHS);
11572       return QualType();
11573     }
11574     QualType IntType =
11575         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11576     assert(IntType->isArithmeticType());
11577 
11578     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11579     // promote the boolean type, and all other promotable integer types, to
11580     // avoid this.
11581     if (IntType->isPromotableIntegerType())
11582       IntType = S.Context.getPromotedIntegerType(IntType);
11583 
11584     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11585     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11586     LHSType = RHSType = IntType;
11587   }
11588 
11589   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11590   // usual arithmetic conversions are applied to the operands.
11591   QualType Type =
11592       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11593   if (LHS.isInvalid() || RHS.isInvalid())
11594     return QualType();
11595   if (Type.isNull())
11596     return S.InvalidOperands(Loc, LHS, RHS);
11597 
11598   Optional<ComparisonCategoryType> CCT =
11599       getComparisonCategoryForBuiltinCmp(Type);
11600   if (!CCT)
11601     return S.InvalidOperands(Loc, LHS, RHS);
11602 
11603   bool HasNarrowing = checkThreeWayNarrowingConversion(
11604       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11605   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11606                                                    RHS.get()->getBeginLoc());
11607   if (HasNarrowing)
11608     return QualType();
11609 
11610   assert(!Type.isNull() && "composite type for <=> has not been set");
11611 
11612   return S.CheckComparisonCategoryType(
11613       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11614 }
11615 
11616 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11617                                                  ExprResult &RHS,
11618                                                  SourceLocation Loc,
11619                                                  BinaryOperatorKind Opc) {
11620   if (Opc == BO_Cmp)
11621     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11622 
11623   // C99 6.5.8p3 / C99 6.5.9p4
11624   QualType Type =
11625       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11626   if (LHS.isInvalid() || RHS.isInvalid())
11627     return QualType();
11628   if (Type.isNull())
11629     return S.InvalidOperands(Loc, LHS, RHS);
11630   assert(Type->isArithmeticType() || Type->isEnumeralType());
11631 
11632   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11633     return S.InvalidOperands(Loc, LHS, RHS);
11634 
11635   // Check for comparisons of floating point operands using != and ==.
11636   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11637     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11638 
11639   // The result of comparisons is 'bool' in C++, 'int' in C.
11640   return S.Context.getLogicalOperationType();
11641 }
11642 
11643 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11644   if (!NullE.get()->getType()->isAnyPointerType())
11645     return;
11646   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11647   if (!E.get()->getType()->isAnyPointerType() &&
11648       E.get()->isNullPointerConstant(Context,
11649                                      Expr::NPC_ValueDependentIsNotNull) ==
11650         Expr::NPCK_ZeroExpression) {
11651     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11652       if (CL->getValue() == 0)
11653         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11654             << NullValue
11655             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11656                                             NullValue ? "NULL" : "(void *)0");
11657     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11658         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11659         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11660         if (T == Context.CharTy)
11661           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11662               << NullValue
11663               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11664                                               NullValue ? "NULL" : "(void *)0");
11665       }
11666   }
11667 }
11668 
11669 // C99 6.5.8, C++ [expr.rel]
11670 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11671                                     SourceLocation Loc,
11672                                     BinaryOperatorKind Opc) {
11673   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11674   bool IsThreeWay = Opc == BO_Cmp;
11675   bool IsOrdered = IsRelational || IsThreeWay;
11676   auto IsAnyPointerType = [](ExprResult E) {
11677     QualType Ty = E.get()->getType();
11678     return Ty->isPointerType() || Ty->isMemberPointerType();
11679   };
11680 
11681   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11682   // type, array-to-pointer, ..., conversions are performed on both operands to
11683   // bring them to their composite type.
11684   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11685   // any type-related checks.
11686   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11687     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11688     if (LHS.isInvalid())
11689       return QualType();
11690     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11691     if (RHS.isInvalid())
11692       return QualType();
11693   } else {
11694     LHS = DefaultLvalueConversion(LHS.get());
11695     if (LHS.isInvalid())
11696       return QualType();
11697     RHS = DefaultLvalueConversion(RHS.get());
11698     if (RHS.isInvalid())
11699       return QualType();
11700   }
11701 
11702   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11703   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11704     CheckPtrComparisonWithNullChar(LHS, RHS);
11705     CheckPtrComparisonWithNullChar(RHS, LHS);
11706   }
11707 
11708   // Handle vector comparisons separately.
11709   if (LHS.get()->getType()->isVectorType() ||
11710       RHS.get()->getType()->isVectorType())
11711     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11712 
11713   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11714   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11715 
11716   QualType LHSType = LHS.get()->getType();
11717   QualType RHSType = RHS.get()->getType();
11718   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11719       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11720     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11721 
11722   const Expr::NullPointerConstantKind LHSNullKind =
11723       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11724   const Expr::NullPointerConstantKind RHSNullKind =
11725       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11726   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11727   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11728 
11729   auto computeResultTy = [&]() {
11730     if (Opc != BO_Cmp)
11731       return Context.getLogicalOperationType();
11732     assert(getLangOpts().CPlusPlus);
11733     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11734 
11735     QualType CompositeTy = LHS.get()->getType();
11736     assert(!CompositeTy->isReferenceType());
11737 
11738     Optional<ComparisonCategoryType> CCT =
11739         getComparisonCategoryForBuiltinCmp(CompositeTy);
11740     if (!CCT)
11741       return InvalidOperands(Loc, LHS, RHS);
11742 
11743     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11744       // P0946R0: Comparisons between a null pointer constant and an object
11745       // pointer result in std::strong_equality, which is ill-formed under
11746       // P1959R0.
11747       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11748           << (LHSIsNull ? LHS.get()->getSourceRange()
11749                         : RHS.get()->getSourceRange());
11750       return QualType();
11751     }
11752 
11753     return CheckComparisonCategoryType(
11754         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11755   };
11756 
11757   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11758     bool IsEquality = Opc == BO_EQ;
11759     if (RHSIsNull)
11760       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11761                                    RHS.get()->getSourceRange());
11762     else
11763       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11764                                    LHS.get()->getSourceRange());
11765   }
11766 
11767   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11768       (RHSType->isIntegerType() && !RHSIsNull)) {
11769     // Skip normal pointer conversion checks in this case; we have better
11770     // diagnostics for this below.
11771   } else if (getLangOpts().CPlusPlus) {
11772     // Equality comparison of a function pointer to a void pointer is invalid,
11773     // but we allow it as an extension.
11774     // FIXME: If we really want to allow this, should it be part of composite
11775     // pointer type computation so it works in conditionals too?
11776     if (!IsOrdered &&
11777         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11778          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11779       // This is a gcc extension compatibility comparison.
11780       // In a SFINAE context, we treat this as a hard error to maintain
11781       // conformance with the C++ standard.
11782       diagnoseFunctionPointerToVoidComparison(
11783           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11784 
11785       if (isSFINAEContext())
11786         return QualType();
11787 
11788       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11789       return computeResultTy();
11790     }
11791 
11792     // C++ [expr.eq]p2:
11793     //   If at least one operand is a pointer [...] bring them to their
11794     //   composite pointer type.
11795     // C++ [expr.spaceship]p6
11796     //  If at least one of the operands is of pointer type, [...] bring them
11797     //  to their composite pointer type.
11798     // C++ [expr.rel]p2:
11799     //   If both operands are pointers, [...] bring them to their composite
11800     //   pointer type.
11801     // For <=>, the only valid non-pointer types are arrays and functions, and
11802     // we already decayed those, so this is really the same as the relational
11803     // comparison rule.
11804     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11805             (IsOrdered ? 2 : 1) &&
11806         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11807                                          RHSType->isObjCObjectPointerType()))) {
11808       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11809         return QualType();
11810       return computeResultTy();
11811     }
11812   } else if (LHSType->isPointerType() &&
11813              RHSType->isPointerType()) { // C99 6.5.8p2
11814     // All of the following pointer-related warnings are GCC extensions, except
11815     // when handling null pointer constants.
11816     QualType LCanPointeeTy =
11817       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11818     QualType RCanPointeeTy =
11819       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11820 
11821     // C99 6.5.9p2 and C99 6.5.8p2
11822     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11823                                    RCanPointeeTy.getUnqualifiedType())) {
11824       if (IsRelational) {
11825         // Pointers both need to point to complete or incomplete types
11826         if ((LCanPointeeTy->isIncompleteType() !=
11827              RCanPointeeTy->isIncompleteType()) &&
11828             !getLangOpts().C11) {
11829           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11830               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11831               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11832               << RCanPointeeTy->isIncompleteType();
11833         }
11834         if (LCanPointeeTy->isFunctionType()) {
11835           // Valid unless a relational comparison of function pointers
11836           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11837               << LHSType << RHSType << LHS.get()->getSourceRange()
11838               << RHS.get()->getSourceRange();
11839         }
11840       }
11841     } else if (!IsRelational &&
11842                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11843       // Valid unless comparison between non-null pointer and function pointer
11844       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11845           && !LHSIsNull && !RHSIsNull)
11846         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11847                                                 /*isError*/false);
11848     } else {
11849       // Invalid
11850       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11851     }
11852     if (LCanPointeeTy != RCanPointeeTy) {
11853       // Treat NULL constant as a special case in OpenCL.
11854       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11855         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11856           Diag(Loc,
11857                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11858               << LHSType << RHSType << 0 /* comparison */
11859               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11860         }
11861       }
11862       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11863       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11864       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11865                                                : CK_BitCast;
11866       if (LHSIsNull && !RHSIsNull)
11867         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11868       else
11869         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11870     }
11871     return computeResultTy();
11872   }
11873 
11874   if (getLangOpts().CPlusPlus) {
11875     // C++ [expr.eq]p4:
11876     //   Two operands of type std::nullptr_t or one operand of type
11877     //   std::nullptr_t and the other a null pointer constant compare equal.
11878     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11879       if (LHSType->isNullPtrType()) {
11880         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11881         return computeResultTy();
11882       }
11883       if (RHSType->isNullPtrType()) {
11884         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11885         return computeResultTy();
11886       }
11887     }
11888 
11889     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11890     // These aren't covered by the composite pointer type rules.
11891     if (!IsOrdered && RHSType->isNullPtrType() &&
11892         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11893       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11894       return computeResultTy();
11895     }
11896     if (!IsOrdered && LHSType->isNullPtrType() &&
11897         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11898       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11899       return computeResultTy();
11900     }
11901 
11902     if (IsRelational &&
11903         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11904          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11905       // HACK: Relational comparison of nullptr_t against a pointer type is
11906       // invalid per DR583, but we allow it within std::less<> and friends,
11907       // since otherwise common uses of it break.
11908       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11909       // friends to have std::nullptr_t overload candidates.
11910       DeclContext *DC = CurContext;
11911       if (isa<FunctionDecl>(DC))
11912         DC = DC->getParent();
11913       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11914         if (CTSD->isInStdNamespace() &&
11915             llvm::StringSwitch<bool>(CTSD->getName())
11916                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11917                 .Default(false)) {
11918           if (RHSType->isNullPtrType())
11919             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11920           else
11921             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11922           return computeResultTy();
11923         }
11924       }
11925     }
11926 
11927     // C++ [expr.eq]p2:
11928     //   If at least one operand is a pointer to member, [...] bring them to
11929     //   their composite pointer type.
11930     if (!IsOrdered &&
11931         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11932       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11933         return QualType();
11934       else
11935         return computeResultTy();
11936     }
11937   }
11938 
11939   // Handle block pointer types.
11940   if (!IsOrdered && LHSType->isBlockPointerType() &&
11941       RHSType->isBlockPointerType()) {
11942     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11943     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11944 
11945     if (!LHSIsNull && !RHSIsNull &&
11946         !Context.typesAreCompatible(lpointee, rpointee)) {
11947       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11948         << LHSType << RHSType << LHS.get()->getSourceRange()
11949         << RHS.get()->getSourceRange();
11950     }
11951     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11952     return computeResultTy();
11953   }
11954 
11955   // Allow block pointers to be compared with null pointer constants.
11956   if (!IsOrdered
11957       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11958           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11959     if (!LHSIsNull && !RHSIsNull) {
11960       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11961              ->getPointeeType()->isVoidType())
11962             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11963                 ->getPointeeType()->isVoidType())))
11964         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11965           << LHSType << RHSType << LHS.get()->getSourceRange()
11966           << RHS.get()->getSourceRange();
11967     }
11968     if (LHSIsNull && !RHSIsNull)
11969       LHS = ImpCastExprToType(LHS.get(), RHSType,
11970                               RHSType->isPointerType() ? CK_BitCast
11971                                 : CK_AnyPointerToBlockPointerCast);
11972     else
11973       RHS = ImpCastExprToType(RHS.get(), LHSType,
11974                               LHSType->isPointerType() ? CK_BitCast
11975                                 : CK_AnyPointerToBlockPointerCast);
11976     return computeResultTy();
11977   }
11978 
11979   if (LHSType->isObjCObjectPointerType() ||
11980       RHSType->isObjCObjectPointerType()) {
11981     const PointerType *LPT = LHSType->getAs<PointerType>();
11982     const PointerType *RPT = RHSType->getAs<PointerType>();
11983     if (LPT || RPT) {
11984       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11985       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11986 
11987       if (!LPtrToVoid && !RPtrToVoid &&
11988           !Context.typesAreCompatible(LHSType, RHSType)) {
11989         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11990                                           /*isError*/false);
11991       }
11992       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11993       // the RHS, but we have test coverage for this behavior.
11994       // FIXME: Consider using convertPointersToCompositeType in C++.
11995       if (LHSIsNull && !RHSIsNull) {
11996         Expr *E = LHS.get();
11997         if (getLangOpts().ObjCAutoRefCount)
11998           CheckObjCConversion(SourceRange(), RHSType, E,
11999                               CCK_ImplicitConversion);
12000         LHS = ImpCastExprToType(E, RHSType,
12001                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12002       }
12003       else {
12004         Expr *E = RHS.get();
12005         if (getLangOpts().ObjCAutoRefCount)
12006           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12007                               /*Diagnose=*/true,
12008                               /*DiagnoseCFAudited=*/false, Opc);
12009         RHS = ImpCastExprToType(E, LHSType,
12010                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12011       }
12012       return computeResultTy();
12013     }
12014     if (LHSType->isObjCObjectPointerType() &&
12015         RHSType->isObjCObjectPointerType()) {
12016       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12017         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12018                                           /*isError*/false);
12019       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12020         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12021 
12022       if (LHSIsNull && !RHSIsNull)
12023         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12024       else
12025         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12026       return computeResultTy();
12027     }
12028 
12029     if (!IsOrdered && LHSType->isBlockPointerType() &&
12030         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12031       LHS = ImpCastExprToType(LHS.get(), RHSType,
12032                               CK_BlockPointerToObjCPointerCast);
12033       return computeResultTy();
12034     } else if (!IsOrdered &&
12035                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12036                RHSType->isBlockPointerType()) {
12037       RHS = ImpCastExprToType(RHS.get(), LHSType,
12038                               CK_BlockPointerToObjCPointerCast);
12039       return computeResultTy();
12040     }
12041   }
12042   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12043       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12044     unsigned DiagID = 0;
12045     bool isError = false;
12046     if (LangOpts.DebuggerSupport) {
12047       // Under a debugger, allow the comparison of pointers to integers,
12048       // since users tend to want to compare addresses.
12049     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12050                (RHSIsNull && RHSType->isIntegerType())) {
12051       if (IsOrdered) {
12052         isError = getLangOpts().CPlusPlus;
12053         DiagID =
12054           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12055                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12056       }
12057     } else if (getLangOpts().CPlusPlus) {
12058       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12059       isError = true;
12060     } else if (IsOrdered)
12061       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12062     else
12063       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12064 
12065     if (DiagID) {
12066       Diag(Loc, DiagID)
12067         << LHSType << RHSType << LHS.get()->getSourceRange()
12068         << RHS.get()->getSourceRange();
12069       if (isError)
12070         return QualType();
12071     }
12072 
12073     if (LHSType->isIntegerType())
12074       LHS = ImpCastExprToType(LHS.get(), RHSType,
12075                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12076     else
12077       RHS = ImpCastExprToType(RHS.get(), LHSType,
12078                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12079     return computeResultTy();
12080   }
12081 
12082   // Handle block pointers.
12083   if (!IsOrdered && RHSIsNull
12084       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12085     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12086     return computeResultTy();
12087   }
12088   if (!IsOrdered && LHSIsNull
12089       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12090     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12091     return computeResultTy();
12092   }
12093 
12094   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12095     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12096       return computeResultTy();
12097     }
12098 
12099     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12100       return computeResultTy();
12101     }
12102 
12103     if (LHSIsNull && RHSType->isQueueT()) {
12104       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12105       return computeResultTy();
12106     }
12107 
12108     if (LHSType->isQueueT() && RHSIsNull) {
12109       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12110       return computeResultTy();
12111     }
12112   }
12113 
12114   return InvalidOperands(Loc, LHS, RHS);
12115 }
12116 
12117 // Return a signed ext_vector_type that is of identical size and number of
12118 // elements. For floating point vectors, return an integer type of identical
12119 // size and number of elements. In the non ext_vector_type case, search from
12120 // the largest type to the smallest type to avoid cases where long long == long,
12121 // where long gets picked over long long.
12122 QualType Sema::GetSignedVectorType(QualType V) {
12123   const VectorType *VTy = V->castAs<VectorType>();
12124   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12125 
12126   if (isa<ExtVectorType>(VTy)) {
12127     if (TypeSize == Context.getTypeSize(Context.CharTy))
12128       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12129     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12130       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12131     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12132       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12133     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12134       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12135     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12136            "Unhandled vector element size in vector compare");
12137     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12138   }
12139 
12140   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12141     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12142                                  VectorType::GenericVector);
12143   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12144     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12145                                  VectorType::GenericVector);
12146   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12147     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12148                                  VectorType::GenericVector);
12149   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12150     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12151                                  VectorType::GenericVector);
12152   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12153          "Unhandled vector element size in vector compare");
12154   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12155                                VectorType::GenericVector);
12156 }
12157 
12158 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12159 /// operates on extended vector types.  Instead of producing an IntTy result,
12160 /// like a scalar comparison, a vector comparison produces a vector of integer
12161 /// types.
12162 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12163                                           SourceLocation Loc,
12164                                           BinaryOperatorKind Opc) {
12165   if (Opc == BO_Cmp) {
12166     Diag(Loc, diag::err_three_way_vector_comparison);
12167     return QualType();
12168   }
12169 
12170   // Check to make sure we're operating on vectors of the same type and width,
12171   // Allowing one side to be a scalar of element type.
12172   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12173                               /*AllowBothBool*/true,
12174                               /*AllowBoolConversions*/getLangOpts().ZVector);
12175   if (vType.isNull())
12176     return vType;
12177 
12178   QualType LHSType = LHS.get()->getType();
12179 
12180   // If AltiVec, the comparison results in a numeric type, i.e.
12181   // bool for C++, int for C
12182   if (getLangOpts().AltiVec &&
12183       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12184     return Context.getLogicalOperationType();
12185 
12186   // For non-floating point types, check for self-comparisons of the form
12187   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12188   // often indicate logic errors in the program.
12189   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12190 
12191   // Check for comparisons of floating point operands using != and ==.
12192   if (BinaryOperator::isEqualityOp(Opc) &&
12193       LHSType->hasFloatingRepresentation()) {
12194     assert(RHS.get()->getType()->hasFloatingRepresentation());
12195     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12196   }
12197 
12198   // Return a signed type for the vector.
12199   return GetSignedVectorType(vType);
12200 }
12201 
12202 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12203                                     const ExprResult &XorRHS,
12204                                     const SourceLocation Loc) {
12205   // Do not diagnose macros.
12206   if (Loc.isMacroID())
12207     return;
12208 
12209   // Do not diagnose if both LHS and RHS are macros.
12210   if (XorLHS.get()->getExprLoc().isMacroID() &&
12211       XorRHS.get()->getExprLoc().isMacroID())
12212     return;
12213 
12214   bool Negative = false;
12215   bool ExplicitPlus = false;
12216   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12217   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12218 
12219   if (!LHSInt)
12220     return;
12221   if (!RHSInt) {
12222     // Check negative literals.
12223     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12224       UnaryOperatorKind Opc = UO->getOpcode();
12225       if (Opc != UO_Minus && Opc != UO_Plus)
12226         return;
12227       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12228       if (!RHSInt)
12229         return;
12230       Negative = (Opc == UO_Minus);
12231       ExplicitPlus = !Negative;
12232     } else {
12233       return;
12234     }
12235   }
12236 
12237   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12238   llvm::APInt RightSideValue = RHSInt->getValue();
12239   if (LeftSideValue != 2 && LeftSideValue != 10)
12240     return;
12241 
12242   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12243     return;
12244 
12245   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12246       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12247   llvm::StringRef ExprStr =
12248       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12249 
12250   CharSourceRange XorRange =
12251       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12252   llvm::StringRef XorStr =
12253       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12254   // Do not diagnose if xor keyword/macro is used.
12255   if (XorStr == "xor")
12256     return;
12257 
12258   std::string LHSStr = std::string(Lexer::getSourceText(
12259       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12260       S.getSourceManager(), S.getLangOpts()));
12261   std::string RHSStr = std::string(Lexer::getSourceText(
12262       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12263       S.getSourceManager(), S.getLangOpts()));
12264 
12265   if (Negative) {
12266     RightSideValue = -RightSideValue;
12267     RHSStr = "-" + RHSStr;
12268   } else if (ExplicitPlus) {
12269     RHSStr = "+" + RHSStr;
12270   }
12271 
12272   StringRef LHSStrRef = LHSStr;
12273   StringRef RHSStrRef = RHSStr;
12274   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12275   // literals.
12276   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12277       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12278       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12279       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12280       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12281       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12282       LHSStrRef.find('\'') != StringRef::npos ||
12283       RHSStrRef.find('\'') != StringRef::npos)
12284     return;
12285 
12286   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12287   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12288   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12289   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12290     std::string SuggestedExpr = "1 << " + RHSStr;
12291     bool Overflow = false;
12292     llvm::APInt One = (LeftSideValue - 1);
12293     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12294     if (Overflow) {
12295       if (RightSideIntValue < 64)
12296         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12297             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12298             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12299       else if (RightSideIntValue == 64)
12300         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12301       else
12302         return;
12303     } else {
12304       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12305           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12306           << PowValue.toString(10, true)
12307           << FixItHint::CreateReplacement(
12308                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12309     }
12310 
12311     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12312   } else if (LeftSideValue == 10) {
12313     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12314     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12315         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12316         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12317     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12318   }
12319 }
12320 
12321 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12322                                           SourceLocation Loc) {
12323   // Ensure that either both operands are of the same vector type, or
12324   // one operand is of a vector type and the other is of its element type.
12325   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12326                                        /*AllowBothBool*/true,
12327                                        /*AllowBoolConversions*/false);
12328   if (vType.isNull())
12329     return InvalidOperands(Loc, LHS, RHS);
12330   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12331       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12332     return InvalidOperands(Loc, LHS, RHS);
12333   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12334   //        usage of the logical operators && and || with vectors in C. This
12335   //        check could be notionally dropped.
12336   if (!getLangOpts().CPlusPlus &&
12337       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12338     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12339 
12340   return GetSignedVectorType(LHS.get()->getType());
12341 }
12342 
12343 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12344                                               SourceLocation Loc,
12345                                               bool IsCompAssign) {
12346   if (!IsCompAssign) {
12347     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12348     if (LHS.isInvalid())
12349       return QualType();
12350   }
12351   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12352   if (RHS.isInvalid())
12353     return QualType();
12354 
12355   // For conversion purposes, we ignore any qualifiers.
12356   // For example, "const float" and "float" are equivalent.
12357   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12358   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12359 
12360   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12361   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12362   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12363 
12364   if (Context.hasSameType(LHSType, RHSType))
12365     return LHSType;
12366 
12367   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12368   // case we have to return InvalidOperands.
12369   ExprResult OriginalLHS = LHS;
12370   ExprResult OriginalRHS = RHS;
12371   if (LHSMatType && !RHSMatType) {
12372     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12373     if (!RHS.isInvalid())
12374       return LHSType;
12375 
12376     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12377   }
12378 
12379   if (!LHSMatType && RHSMatType) {
12380     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12381     if (!LHS.isInvalid())
12382       return RHSType;
12383     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12384   }
12385 
12386   return InvalidOperands(Loc, LHS, RHS);
12387 }
12388 
12389 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12390                                            SourceLocation Loc,
12391                                            bool IsCompAssign) {
12392   if (!IsCompAssign) {
12393     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12394     if (LHS.isInvalid())
12395       return QualType();
12396   }
12397   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12398   if (RHS.isInvalid())
12399     return QualType();
12400 
12401   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12402   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12403   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12404 
12405   if (LHSMatType && RHSMatType) {
12406     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12407       return InvalidOperands(Loc, LHS, RHS);
12408 
12409     if (!Context.hasSameType(LHSMatType->getElementType(),
12410                              RHSMatType->getElementType()))
12411       return InvalidOperands(Loc, LHS, RHS);
12412 
12413     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12414                                          LHSMatType->getNumRows(),
12415                                          RHSMatType->getNumColumns());
12416   }
12417   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12418 }
12419 
12420 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12421                                            SourceLocation Loc,
12422                                            BinaryOperatorKind Opc) {
12423   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12424 
12425   bool IsCompAssign =
12426       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12427 
12428   if (LHS.get()->getType()->isVectorType() ||
12429       RHS.get()->getType()->isVectorType()) {
12430     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12431         RHS.get()->getType()->hasIntegerRepresentation())
12432       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12433                         /*AllowBothBool*/true,
12434                         /*AllowBoolConversions*/getLangOpts().ZVector);
12435     return InvalidOperands(Loc, LHS, RHS);
12436   }
12437 
12438   if (Opc == BO_And)
12439     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12440 
12441   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12442       RHS.get()->getType()->hasFloatingRepresentation())
12443     return InvalidOperands(Loc, LHS, RHS);
12444 
12445   ExprResult LHSResult = LHS, RHSResult = RHS;
12446   QualType compType = UsualArithmeticConversions(
12447       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12448   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12449     return QualType();
12450   LHS = LHSResult.get();
12451   RHS = RHSResult.get();
12452 
12453   if (Opc == BO_Xor)
12454     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12455 
12456   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12457     return compType;
12458   return InvalidOperands(Loc, LHS, RHS);
12459 }
12460 
12461 // C99 6.5.[13,14]
12462 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12463                                            SourceLocation Loc,
12464                                            BinaryOperatorKind Opc) {
12465   // Check vector operands differently.
12466   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12467     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12468 
12469   bool EnumConstantInBoolContext = false;
12470   for (const ExprResult &HS : {LHS, RHS}) {
12471     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12472       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12473       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12474         EnumConstantInBoolContext = true;
12475     }
12476   }
12477 
12478   if (EnumConstantInBoolContext)
12479     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12480 
12481   // Diagnose cases where the user write a logical and/or but probably meant a
12482   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12483   // is a constant.
12484   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12485       !LHS.get()->getType()->isBooleanType() &&
12486       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12487       // Don't warn in macros or template instantiations.
12488       !Loc.isMacroID() && !inTemplateInstantiation()) {
12489     // If the RHS can be constant folded, and if it constant folds to something
12490     // that isn't 0 or 1 (which indicate a potential logical operation that
12491     // happened to fold to true/false) then warn.
12492     // Parens on the RHS are ignored.
12493     Expr::EvalResult EVResult;
12494     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12495       llvm::APSInt Result = EVResult.Val.getInt();
12496       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12497            !RHS.get()->getExprLoc().isMacroID()) ||
12498           (Result != 0 && Result != 1)) {
12499         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12500           << RHS.get()->getSourceRange()
12501           << (Opc == BO_LAnd ? "&&" : "||");
12502         // Suggest replacing the logical operator with the bitwise version
12503         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12504             << (Opc == BO_LAnd ? "&" : "|")
12505             << FixItHint::CreateReplacement(SourceRange(
12506                                                  Loc, getLocForEndOfToken(Loc)),
12507                                             Opc == BO_LAnd ? "&" : "|");
12508         if (Opc == BO_LAnd)
12509           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12510           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12511               << FixItHint::CreateRemoval(
12512                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12513                                  RHS.get()->getEndLoc()));
12514       }
12515     }
12516   }
12517 
12518   if (!Context.getLangOpts().CPlusPlus) {
12519     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12520     // not operate on the built-in scalar and vector float types.
12521     if (Context.getLangOpts().OpenCL &&
12522         Context.getLangOpts().OpenCLVersion < 120) {
12523       if (LHS.get()->getType()->isFloatingType() ||
12524           RHS.get()->getType()->isFloatingType())
12525         return InvalidOperands(Loc, LHS, RHS);
12526     }
12527 
12528     LHS = UsualUnaryConversions(LHS.get());
12529     if (LHS.isInvalid())
12530       return QualType();
12531 
12532     RHS = UsualUnaryConversions(RHS.get());
12533     if (RHS.isInvalid())
12534       return QualType();
12535 
12536     if (!LHS.get()->getType()->isScalarType() ||
12537         !RHS.get()->getType()->isScalarType())
12538       return InvalidOperands(Loc, LHS, RHS);
12539 
12540     return Context.IntTy;
12541   }
12542 
12543   // The following is safe because we only use this method for
12544   // non-overloadable operands.
12545 
12546   // C++ [expr.log.and]p1
12547   // C++ [expr.log.or]p1
12548   // The operands are both contextually converted to type bool.
12549   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12550   if (LHSRes.isInvalid())
12551     return InvalidOperands(Loc, LHS, RHS);
12552   LHS = LHSRes;
12553 
12554   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12555   if (RHSRes.isInvalid())
12556     return InvalidOperands(Loc, LHS, RHS);
12557   RHS = RHSRes;
12558 
12559   // C++ [expr.log.and]p2
12560   // C++ [expr.log.or]p2
12561   // The result is a bool.
12562   return Context.BoolTy;
12563 }
12564 
12565 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12566   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12567   if (!ME) return false;
12568   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12569   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12570       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12571   if (!Base) return false;
12572   return Base->getMethodDecl() != nullptr;
12573 }
12574 
12575 /// Is the given expression (which must be 'const') a reference to a
12576 /// variable which was originally non-const, but which has become
12577 /// 'const' due to being captured within a block?
12578 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12579 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12580   assert(E->isLValue() && E->getType().isConstQualified());
12581   E = E->IgnoreParens();
12582 
12583   // Must be a reference to a declaration from an enclosing scope.
12584   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12585   if (!DRE) return NCCK_None;
12586   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12587 
12588   // The declaration must be a variable which is not declared 'const'.
12589   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12590   if (!var) return NCCK_None;
12591   if (var->getType().isConstQualified()) return NCCK_None;
12592   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12593 
12594   // Decide whether the first capture was for a block or a lambda.
12595   DeclContext *DC = S.CurContext, *Prev = nullptr;
12596   // Decide whether the first capture was for a block or a lambda.
12597   while (DC) {
12598     // For init-capture, it is possible that the variable belongs to the
12599     // template pattern of the current context.
12600     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12601       if (var->isInitCapture() &&
12602           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12603         break;
12604     if (DC == var->getDeclContext())
12605       break;
12606     Prev = DC;
12607     DC = DC->getParent();
12608   }
12609   // Unless we have an init-capture, we've gone one step too far.
12610   if (!var->isInitCapture())
12611     DC = Prev;
12612   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12613 }
12614 
12615 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12616   Ty = Ty.getNonReferenceType();
12617   if (IsDereference && Ty->isPointerType())
12618     Ty = Ty->getPointeeType();
12619   return !Ty.isConstQualified();
12620 }
12621 
12622 // Update err_typecheck_assign_const and note_typecheck_assign_const
12623 // when this enum is changed.
12624 enum {
12625   ConstFunction,
12626   ConstVariable,
12627   ConstMember,
12628   ConstMethod,
12629   NestedConstMember,
12630   ConstUnknown,  // Keep as last element
12631 };
12632 
12633 /// Emit the "read-only variable not assignable" error and print notes to give
12634 /// more information about why the variable is not assignable, such as pointing
12635 /// to the declaration of a const variable, showing that a method is const, or
12636 /// that the function is returning a const reference.
12637 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12638                                     SourceLocation Loc) {
12639   SourceRange ExprRange = E->getSourceRange();
12640 
12641   // Only emit one error on the first const found.  All other consts will emit
12642   // a note to the error.
12643   bool DiagnosticEmitted = false;
12644 
12645   // Track if the current expression is the result of a dereference, and if the
12646   // next checked expression is the result of a dereference.
12647   bool IsDereference = false;
12648   bool NextIsDereference = false;
12649 
12650   // Loop to process MemberExpr chains.
12651   while (true) {
12652     IsDereference = NextIsDereference;
12653 
12654     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12655     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12656       NextIsDereference = ME->isArrow();
12657       const ValueDecl *VD = ME->getMemberDecl();
12658       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12659         // Mutable fields can be modified even if the class is const.
12660         if (Field->isMutable()) {
12661           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12662           break;
12663         }
12664 
12665         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12666           if (!DiagnosticEmitted) {
12667             S.Diag(Loc, diag::err_typecheck_assign_const)
12668                 << ExprRange << ConstMember << false /*static*/ << Field
12669                 << Field->getType();
12670             DiagnosticEmitted = true;
12671           }
12672           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12673               << ConstMember << false /*static*/ << Field << Field->getType()
12674               << Field->getSourceRange();
12675         }
12676         E = ME->getBase();
12677         continue;
12678       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12679         if (VDecl->getType().isConstQualified()) {
12680           if (!DiagnosticEmitted) {
12681             S.Diag(Loc, diag::err_typecheck_assign_const)
12682                 << ExprRange << ConstMember << true /*static*/ << VDecl
12683                 << VDecl->getType();
12684             DiagnosticEmitted = true;
12685           }
12686           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12687               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12688               << VDecl->getSourceRange();
12689         }
12690         // Static fields do not inherit constness from parents.
12691         break;
12692       }
12693       break; // End MemberExpr
12694     } else if (const ArraySubscriptExpr *ASE =
12695                    dyn_cast<ArraySubscriptExpr>(E)) {
12696       E = ASE->getBase()->IgnoreParenImpCasts();
12697       continue;
12698     } else if (const ExtVectorElementExpr *EVE =
12699                    dyn_cast<ExtVectorElementExpr>(E)) {
12700       E = EVE->getBase()->IgnoreParenImpCasts();
12701       continue;
12702     }
12703     break;
12704   }
12705 
12706   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12707     // Function calls
12708     const FunctionDecl *FD = CE->getDirectCallee();
12709     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12710       if (!DiagnosticEmitted) {
12711         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12712                                                       << ConstFunction << FD;
12713         DiagnosticEmitted = true;
12714       }
12715       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12716              diag::note_typecheck_assign_const)
12717           << ConstFunction << FD << FD->getReturnType()
12718           << FD->getReturnTypeSourceRange();
12719     }
12720   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12721     // Point to variable declaration.
12722     if (const ValueDecl *VD = DRE->getDecl()) {
12723       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12724         if (!DiagnosticEmitted) {
12725           S.Diag(Loc, diag::err_typecheck_assign_const)
12726               << ExprRange << ConstVariable << VD << VD->getType();
12727           DiagnosticEmitted = true;
12728         }
12729         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12730             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12731       }
12732     }
12733   } else if (isa<CXXThisExpr>(E)) {
12734     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12735       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12736         if (MD->isConst()) {
12737           if (!DiagnosticEmitted) {
12738             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12739                                                           << ConstMethod << MD;
12740             DiagnosticEmitted = true;
12741           }
12742           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12743               << ConstMethod << MD << MD->getSourceRange();
12744         }
12745       }
12746     }
12747   }
12748 
12749   if (DiagnosticEmitted)
12750     return;
12751 
12752   // Can't determine a more specific message, so display the generic error.
12753   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12754 }
12755 
12756 enum OriginalExprKind {
12757   OEK_Variable,
12758   OEK_Member,
12759   OEK_LValue
12760 };
12761 
12762 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12763                                          const RecordType *Ty,
12764                                          SourceLocation Loc, SourceRange Range,
12765                                          OriginalExprKind OEK,
12766                                          bool &DiagnosticEmitted) {
12767   std::vector<const RecordType *> RecordTypeList;
12768   RecordTypeList.push_back(Ty);
12769   unsigned NextToCheckIndex = 0;
12770   // We walk the record hierarchy breadth-first to ensure that we print
12771   // diagnostics in field nesting order.
12772   while (RecordTypeList.size() > NextToCheckIndex) {
12773     bool IsNested = NextToCheckIndex > 0;
12774     for (const FieldDecl *Field :
12775          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12776       // First, check every field for constness.
12777       QualType FieldTy = Field->getType();
12778       if (FieldTy.isConstQualified()) {
12779         if (!DiagnosticEmitted) {
12780           S.Diag(Loc, diag::err_typecheck_assign_const)
12781               << Range << NestedConstMember << OEK << VD
12782               << IsNested << Field;
12783           DiagnosticEmitted = true;
12784         }
12785         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12786             << NestedConstMember << IsNested << Field
12787             << FieldTy << Field->getSourceRange();
12788       }
12789 
12790       // Then we append it to the list to check next in order.
12791       FieldTy = FieldTy.getCanonicalType();
12792       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12793         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12794           RecordTypeList.push_back(FieldRecTy);
12795       }
12796     }
12797     ++NextToCheckIndex;
12798   }
12799 }
12800 
12801 /// Emit an error for the case where a record we are trying to assign to has a
12802 /// const-qualified field somewhere in its hierarchy.
12803 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12804                                          SourceLocation Loc) {
12805   QualType Ty = E->getType();
12806   assert(Ty->isRecordType() && "lvalue was not record?");
12807   SourceRange Range = E->getSourceRange();
12808   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12809   bool DiagEmitted = false;
12810 
12811   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12812     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12813             Range, OEK_Member, DiagEmitted);
12814   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12815     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12816             Range, OEK_Variable, DiagEmitted);
12817   else
12818     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12819             Range, OEK_LValue, DiagEmitted);
12820   if (!DiagEmitted)
12821     DiagnoseConstAssignment(S, E, Loc);
12822 }
12823 
12824 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12825 /// emit an error and return true.  If so, return false.
12826 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12827   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12828 
12829   S.CheckShadowingDeclModification(E, Loc);
12830 
12831   SourceLocation OrigLoc = Loc;
12832   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12833                                                               &Loc);
12834   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12835     IsLV = Expr::MLV_InvalidMessageExpression;
12836   if (IsLV == Expr::MLV_Valid)
12837     return false;
12838 
12839   unsigned DiagID = 0;
12840   bool NeedType = false;
12841   switch (IsLV) { // C99 6.5.16p2
12842   case Expr::MLV_ConstQualified:
12843     // Use a specialized diagnostic when we're assigning to an object
12844     // from an enclosing function or block.
12845     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12846       if (NCCK == NCCK_Block)
12847         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12848       else
12849         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12850       break;
12851     }
12852 
12853     // In ARC, use some specialized diagnostics for occasions where we
12854     // infer 'const'.  These are always pseudo-strong variables.
12855     if (S.getLangOpts().ObjCAutoRefCount) {
12856       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12857       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12858         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12859 
12860         // Use the normal diagnostic if it's pseudo-__strong but the
12861         // user actually wrote 'const'.
12862         if (var->isARCPseudoStrong() &&
12863             (!var->getTypeSourceInfo() ||
12864              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12865           // There are three pseudo-strong cases:
12866           //  - self
12867           ObjCMethodDecl *method = S.getCurMethodDecl();
12868           if (method && var == method->getSelfDecl()) {
12869             DiagID = method->isClassMethod()
12870               ? diag::err_typecheck_arc_assign_self_class_method
12871               : diag::err_typecheck_arc_assign_self;
12872 
12873           //  - Objective-C externally_retained attribute.
12874           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12875                      isa<ParmVarDecl>(var)) {
12876             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12877 
12878           //  - fast enumeration variables
12879           } else {
12880             DiagID = diag::err_typecheck_arr_assign_enumeration;
12881           }
12882 
12883           SourceRange Assign;
12884           if (Loc != OrigLoc)
12885             Assign = SourceRange(OrigLoc, OrigLoc);
12886           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12887           // We need to preserve the AST regardless, so migration tool
12888           // can do its job.
12889           return false;
12890         }
12891       }
12892     }
12893 
12894     // If none of the special cases above are triggered, then this is a
12895     // simple const assignment.
12896     if (DiagID == 0) {
12897       DiagnoseConstAssignment(S, E, Loc);
12898       return true;
12899     }
12900 
12901     break;
12902   case Expr::MLV_ConstAddrSpace:
12903     DiagnoseConstAssignment(S, E, Loc);
12904     return true;
12905   case Expr::MLV_ConstQualifiedField:
12906     DiagnoseRecursiveConstFields(S, E, Loc);
12907     return true;
12908   case Expr::MLV_ArrayType:
12909   case Expr::MLV_ArrayTemporary:
12910     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12911     NeedType = true;
12912     break;
12913   case Expr::MLV_NotObjectType:
12914     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12915     NeedType = true;
12916     break;
12917   case Expr::MLV_LValueCast:
12918     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12919     break;
12920   case Expr::MLV_Valid:
12921     llvm_unreachable("did not take early return for MLV_Valid");
12922   case Expr::MLV_InvalidExpression:
12923   case Expr::MLV_MemberFunction:
12924   case Expr::MLV_ClassTemporary:
12925     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12926     break;
12927   case Expr::MLV_IncompleteType:
12928   case Expr::MLV_IncompleteVoidType:
12929     return S.RequireCompleteType(Loc, E->getType(),
12930              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12931   case Expr::MLV_DuplicateVectorComponents:
12932     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12933     break;
12934   case Expr::MLV_NoSetterProperty:
12935     llvm_unreachable("readonly properties should be processed differently");
12936   case Expr::MLV_InvalidMessageExpression:
12937     DiagID = diag::err_readonly_message_assignment;
12938     break;
12939   case Expr::MLV_SubObjCPropertySetting:
12940     DiagID = diag::err_no_subobject_property_setting;
12941     break;
12942   }
12943 
12944   SourceRange Assign;
12945   if (Loc != OrigLoc)
12946     Assign = SourceRange(OrigLoc, OrigLoc);
12947   if (NeedType)
12948     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12949   else
12950     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12951   return true;
12952 }
12953 
12954 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12955                                          SourceLocation Loc,
12956                                          Sema &Sema) {
12957   if (Sema.inTemplateInstantiation())
12958     return;
12959   if (Sema.isUnevaluatedContext())
12960     return;
12961   if (Loc.isInvalid() || Loc.isMacroID())
12962     return;
12963   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12964     return;
12965 
12966   // C / C++ fields
12967   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12968   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12969   if (ML && MR) {
12970     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12971       return;
12972     const ValueDecl *LHSDecl =
12973         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12974     const ValueDecl *RHSDecl =
12975         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12976     if (LHSDecl != RHSDecl)
12977       return;
12978     if (LHSDecl->getType().isVolatileQualified())
12979       return;
12980     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12981       if (RefTy->getPointeeType().isVolatileQualified())
12982         return;
12983 
12984     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12985   }
12986 
12987   // Objective-C instance variables
12988   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12989   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12990   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12991     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12992     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12993     if (RL && RR && RL->getDecl() == RR->getDecl())
12994       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12995   }
12996 }
12997 
12998 // C99 6.5.16.1
12999 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13000                                        SourceLocation Loc,
13001                                        QualType CompoundType) {
13002   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13003 
13004   // Verify that LHS is a modifiable lvalue, and emit error if not.
13005   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13006     return QualType();
13007 
13008   QualType LHSType = LHSExpr->getType();
13009   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13010                                              CompoundType;
13011   // OpenCL v1.2 s6.1.1.1 p2:
13012   // The half data type can only be used to declare a pointer to a buffer that
13013   // contains half values
13014   if (getLangOpts().OpenCL &&
13015       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13016       LHSType->isHalfType()) {
13017     Diag(Loc, diag::err_opencl_half_load_store) << 1
13018         << LHSType.getUnqualifiedType();
13019     return QualType();
13020   }
13021 
13022   AssignConvertType ConvTy;
13023   if (CompoundType.isNull()) {
13024     Expr *RHSCheck = RHS.get();
13025 
13026     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13027 
13028     QualType LHSTy(LHSType);
13029     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13030     if (RHS.isInvalid())
13031       return QualType();
13032     // Special case of NSObject attributes on c-style pointer types.
13033     if (ConvTy == IncompatiblePointer &&
13034         ((Context.isObjCNSObjectType(LHSType) &&
13035           RHSType->isObjCObjectPointerType()) ||
13036          (Context.isObjCNSObjectType(RHSType) &&
13037           LHSType->isObjCObjectPointerType())))
13038       ConvTy = Compatible;
13039 
13040     if (ConvTy == Compatible &&
13041         LHSType->isObjCObjectType())
13042         Diag(Loc, diag::err_objc_object_assignment)
13043           << LHSType;
13044 
13045     // If the RHS is a unary plus or minus, check to see if they = and + are
13046     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13047     // instead of "x += 4".
13048     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13049       RHSCheck = ICE->getSubExpr();
13050     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13051       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13052           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13053           // Only if the two operators are exactly adjacent.
13054           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13055           // And there is a space or other character before the subexpr of the
13056           // unary +/-.  We don't want to warn on "x=-1".
13057           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13058           UO->getSubExpr()->getBeginLoc().isFileID()) {
13059         Diag(Loc, diag::warn_not_compound_assign)
13060           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13061           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13062       }
13063     }
13064 
13065     if (ConvTy == Compatible) {
13066       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13067         // Warn about retain cycles where a block captures the LHS, but
13068         // not if the LHS is a simple variable into which the block is
13069         // being stored...unless that variable can be captured by reference!
13070         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13071         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13072         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13073           checkRetainCycles(LHSExpr, RHS.get());
13074       }
13075 
13076       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13077           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13078         // It is safe to assign a weak reference into a strong variable.
13079         // Although this code can still have problems:
13080         //   id x = self.weakProp;
13081         //   id y = self.weakProp;
13082         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13083         // paths through the function. This should be revisited if
13084         // -Wrepeated-use-of-weak is made flow-sensitive.
13085         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13086         // variable, which will be valid for the current autorelease scope.
13087         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13088                              RHS.get()->getBeginLoc()))
13089           getCurFunction()->markSafeWeakUse(RHS.get());
13090 
13091       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13092         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13093       }
13094     }
13095   } else {
13096     // Compound assignment "x += y"
13097     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13098   }
13099 
13100   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13101                                RHS.get(), AA_Assigning))
13102     return QualType();
13103 
13104   CheckForNullPointerDereference(*this, LHSExpr);
13105 
13106   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13107     if (CompoundType.isNull()) {
13108       // C++2a [expr.ass]p5:
13109       //   A simple-assignment whose left operand is of a volatile-qualified
13110       //   type is deprecated unless the assignment is either a discarded-value
13111       //   expression or an unevaluated operand
13112       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13113     } else {
13114       // C++2a [expr.ass]p6:
13115       //   [Compound-assignment] expressions are deprecated if E1 has
13116       //   volatile-qualified type
13117       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13118     }
13119   }
13120 
13121   // C99 6.5.16p3: The type of an assignment expression is the type of the
13122   // left operand unless the left operand has qualified type, in which case
13123   // it is the unqualified version of the type of the left operand.
13124   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13125   // is converted to the type of the assignment expression (above).
13126   // C++ 5.17p1: the type of the assignment expression is that of its left
13127   // operand.
13128   return (getLangOpts().CPlusPlus
13129           ? LHSType : LHSType.getUnqualifiedType());
13130 }
13131 
13132 // Only ignore explicit casts to void.
13133 static bool IgnoreCommaOperand(const Expr *E) {
13134   E = E->IgnoreParens();
13135 
13136   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13137     if (CE->getCastKind() == CK_ToVoid) {
13138       return true;
13139     }
13140 
13141     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13142     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13143         CE->getSubExpr()->getType()->isDependentType()) {
13144       return true;
13145     }
13146   }
13147 
13148   return false;
13149 }
13150 
13151 // Look for instances where it is likely the comma operator is confused with
13152 // another operator.  There is an explicit list of acceptable expressions for
13153 // the left hand side of the comma operator, otherwise emit a warning.
13154 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13155   // No warnings in macros
13156   if (Loc.isMacroID())
13157     return;
13158 
13159   // Don't warn in template instantiations.
13160   if (inTemplateInstantiation())
13161     return;
13162 
13163   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13164   // instead, skip more than needed, then call back into here with the
13165   // CommaVisitor in SemaStmt.cpp.
13166   // The listed locations are the initialization and increment portions
13167   // of a for loop.  The additional checks are on the condition of
13168   // if statements, do/while loops, and for loops.
13169   // Differences in scope flags for C89 mode requires the extra logic.
13170   const unsigned ForIncrementFlags =
13171       getLangOpts().C99 || getLangOpts().CPlusPlus
13172           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13173           : Scope::ContinueScope | Scope::BreakScope;
13174   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13175   const unsigned ScopeFlags = getCurScope()->getFlags();
13176   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13177       (ScopeFlags & ForInitFlags) == ForInitFlags)
13178     return;
13179 
13180   // If there are multiple comma operators used together, get the RHS of the
13181   // of the comma operator as the LHS.
13182   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13183     if (BO->getOpcode() != BO_Comma)
13184       break;
13185     LHS = BO->getRHS();
13186   }
13187 
13188   // Only allow some expressions on LHS to not warn.
13189   if (IgnoreCommaOperand(LHS))
13190     return;
13191 
13192   Diag(Loc, diag::warn_comma_operator);
13193   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13194       << LHS->getSourceRange()
13195       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13196                                     LangOpts.CPlusPlus ? "static_cast<void>("
13197                                                        : "(void)(")
13198       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13199                                     ")");
13200 }
13201 
13202 // C99 6.5.17
13203 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13204                                    SourceLocation Loc) {
13205   LHS = S.CheckPlaceholderExpr(LHS.get());
13206   RHS = S.CheckPlaceholderExpr(RHS.get());
13207   if (LHS.isInvalid() || RHS.isInvalid())
13208     return QualType();
13209 
13210   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13211   // operands, but not unary promotions.
13212   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13213 
13214   // So we treat the LHS as a ignored value, and in C++ we allow the
13215   // containing site to determine what should be done with the RHS.
13216   LHS = S.IgnoredValueConversions(LHS.get());
13217   if (LHS.isInvalid())
13218     return QualType();
13219 
13220   S.DiagnoseUnusedExprResult(LHS.get());
13221 
13222   if (!S.getLangOpts().CPlusPlus) {
13223     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13224     if (RHS.isInvalid())
13225       return QualType();
13226     if (!RHS.get()->getType()->isVoidType())
13227       S.RequireCompleteType(Loc, RHS.get()->getType(),
13228                             diag::err_incomplete_type);
13229   }
13230 
13231   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13232     S.DiagnoseCommaOperator(LHS.get(), Loc);
13233 
13234   return RHS.get()->getType();
13235 }
13236 
13237 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13238 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13239 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13240                                                ExprValueKind &VK,
13241                                                ExprObjectKind &OK,
13242                                                SourceLocation OpLoc,
13243                                                bool IsInc, bool IsPrefix) {
13244   if (Op->isTypeDependent())
13245     return S.Context.DependentTy;
13246 
13247   QualType ResType = Op->getType();
13248   // Atomic types can be used for increment / decrement where the non-atomic
13249   // versions can, so ignore the _Atomic() specifier for the purpose of
13250   // checking.
13251   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13252     ResType = ResAtomicType->getValueType();
13253 
13254   assert(!ResType.isNull() && "no type for increment/decrement expression");
13255 
13256   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13257     // Decrement of bool is not allowed.
13258     if (!IsInc) {
13259       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13260       return QualType();
13261     }
13262     // Increment of bool sets it to true, but is deprecated.
13263     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13264                                               : diag::warn_increment_bool)
13265       << Op->getSourceRange();
13266   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13267     // Error on enum increments and decrements in C++ mode
13268     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13269     return QualType();
13270   } else if (ResType->isRealType()) {
13271     // OK!
13272   } else if (ResType->isPointerType()) {
13273     // C99 6.5.2.4p2, 6.5.6p2
13274     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13275       return QualType();
13276   } else if (ResType->isObjCObjectPointerType()) {
13277     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13278     // Otherwise, we just need a complete type.
13279     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13280         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13281       return QualType();
13282   } else if (ResType->isAnyComplexType()) {
13283     // C99 does not support ++/-- on complex types, we allow as an extension.
13284     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13285       << ResType << Op->getSourceRange();
13286   } else if (ResType->isPlaceholderType()) {
13287     ExprResult PR = S.CheckPlaceholderExpr(Op);
13288     if (PR.isInvalid()) return QualType();
13289     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13290                                           IsInc, IsPrefix);
13291   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13292     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13293   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13294              (ResType->castAs<VectorType>()->getVectorKind() !=
13295               VectorType::AltiVecBool)) {
13296     // The z vector extensions allow ++ and -- for non-bool vectors.
13297   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13298             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13299     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13300   } else {
13301     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13302       << ResType << int(IsInc) << Op->getSourceRange();
13303     return QualType();
13304   }
13305   // At this point, we know we have a real, complex or pointer type.
13306   // Now make sure the operand is a modifiable lvalue.
13307   if (CheckForModifiableLvalue(Op, OpLoc, S))
13308     return QualType();
13309   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13310     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13311     //   An operand with volatile-qualified type is deprecated
13312     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13313         << IsInc << ResType;
13314   }
13315   // In C++, a prefix increment is the same type as the operand. Otherwise
13316   // (in C or with postfix), the increment is the unqualified type of the
13317   // operand.
13318   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13319     VK = VK_LValue;
13320     OK = Op->getObjectKind();
13321     return ResType;
13322   } else {
13323     VK = VK_RValue;
13324     return ResType.getUnqualifiedType();
13325   }
13326 }
13327 
13328 
13329 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13330 /// This routine allows us to typecheck complex/recursive expressions
13331 /// where the declaration is needed for type checking. We only need to
13332 /// handle cases when the expression references a function designator
13333 /// or is an lvalue. Here are some examples:
13334 ///  - &(x) => x
13335 ///  - &*****f => f for f a function designator.
13336 ///  - &s.xx => s
13337 ///  - &s.zz[1].yy -> s, if zz is an array
13338 ///  - *(x + 1) -> x, if x is an array
13339 ///  - &"123"[2] -> 0
13340 ///  - & __real__ x -> x
13341 ///
13342 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13343 /// members.
13344 static ValueDecl *getPrimaryDecl(Expr *E) {
13345   switch (E->getStmtClass()) {
13346   case Stmt::DeclRefExprClass:
13347     return cast<DeclRefExpr>(E)->getDecl();
13348   case Stmt::MemberExprClass:
13349     // If this is an arrow operator, the address is an offset from
13350     // the base's value, so the object the base refers to is
13351     // irrelevant.
13352     if (cast<MemberExpr>(E)->isArrow())
13353       return nullptr;
13354     // Otherwise, the expression refers to a part of the base
13355     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13356   case Stmt::ArraySubscriptExprClass: {
13357     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13358     // promotion of register arrays earlier.
13359     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13360     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13361       if (ICE->getSubExpr()->getType()->isArrayType())
13362         return getPrimaryDecl(ICE->getSubExpr());
13363     }
13364     return nullptr;
13365   }
13366   case Stmt::UnaryOperatorClass: {
13367     UnaryOperator *UO = cast<UnaryOperator>(E);
13368 
13369     switch(UO->getOpcode()) {
13370     case UO_Real:
13371     case UO_Imag:
13372     case UO_Extension:
13373       return getPrimaryDecl(UO->getSubExpr());
13374     default:
13375       return nullptr;
13376     }
13377   }
13378   case Stmt::ParenExprClass:
13379     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13380   case Stmt::ImplicitCastExprClass:
13381     // If the result of an implicit cast is an l-value, we care about
13382     // the sub-expression; otherwise, the result here doesn't matter.
13383     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13384   case Stmt::CXXUuidofExprClass:
13385     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13386   default:
13387     return nullptr;
13388   }
13389 }
13390 
13391 namespace {
13392 enum {
13393   AO_Bit_Field = 0,
13394   AO_Vector_Element = 1,
13395   AO_Property_Expansion = 2,
13396   AO_Register_Variable = 3,
13397   AO_Matrix_Element = 4,
13398   AO_No_Error = 5
13399 };
13400 }
13401 /// Diagnose invalid operand for address of operations.
13402 ///
13403 /// \param Type The type of operand which cannot have its address taken.
13404 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13405                                          Expr *E, unsigned Type) {
13406   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13407 }
13408 
13409 /// CheckAddressOfOperand - The operand of & must be either a function
13410 /// designator or an lvalue designating an object. If it is an lvalue, the
13411 /// object cannot be declared with storage class register or be a bit field.
13412 /// Note: The usual conversions are *not* applied to the operand of the &
13413 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13414 /// In C++, the operand might be an overloaded function name, in which case
13415 /// we allow the '&' but retain the overloaded-function type.
13416 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13417   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13418     if (PTy->getKind() == BuiltinType::Overload) {
13419       Expr *E = OrigOp.get()->IgnoreParens();
13420       if (!isa<OverloadExpr>(E)) {
13421         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13422         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13423           << OrigOp.get()->getSourceRange();
13424         return QualType();
13425       }
13426 
13427       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13428       if (isa<UnresolvedMemberExpr>(Ovl))
13429         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13430           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13431             << OrigOp.get()->getSourceRange();
13432           return QualType();
13433         }
13434 
13435       return Context.OverloadTy;
13436     }
13437 
13438     if (PTy->getKind() == BuiltinType::UnknownAny)
13439       return Context.UnknownAnyTy;
13440 
13441     if (PTy->getKind() == BuiltinType::BoundMember) {
13442       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13443         << OrigOp.get()->getSourceRange();
13444       return QualType();
13445     }
13446 
13447     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13448     if (OrigOp.isInvalid()) return QualType();
13449   }
13450 
13451   if (OrigOp.get()->isTypeDependent())
13452     return Context.DependentTy;
13453 
13454   assert(!OrigOp.get()->getType()->isPlaceholderType());
13455 
13456   // Make sure to ignore parentheses in subsequent checks
13457   Expr *op = OrigOp.get()->IgnoreParens();
13458 
13459   // In OpenCL captures for blocks called as lambda functions
13460   // are located in the private address space. Blocks used in
13461   // enqueue_kernel can be located in a different address space
13462   // depending on a vendor implementation. Thus preventing
13463   // taking an address of the capture to avoid invalid AS casts.
13464   if (LangOpts.OpenCL) {
13465     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13466     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13467       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13468       return QualType();
13469     }
13470   }
13471 
13472   if (getLangOpts().C99) {
13473     // Implement C99-only parts of addressof rules.
13474     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13475       if (uOp->getOpcode() == UO_Deref)
13476         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13477         // (assuming the deref expression is valid).
13478         return uOp->getSubExpr()->getType();
13479     }
13480     // Technically, there should be a check for array subscript
13481     // expressions here, but the result of one is always an lvalue anyway.
13482   }
13483   ValueDecl *dcl = getPrimaryDecl(op);
13484 
13485   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13486     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13487                                            op->getBeginLoc()))
13488       return QualType();
13489 
13490   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13491   unsigned AddressOfError = AO_No_Error;
13492 
13493   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13494     bool sfinae = (bool)isSFINAEContext();
13495     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13496                                   : diag::ext_typecheck_addrof_temporary)
13497       << op->getType() << op->getSourceRange();
13498     if (sfinae)
13499       return QualType();
13500     // Materialize the temporary as an lvalue so that we can take its address.
13501     OrigOp = op =
13502         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13503   } else if (isa<ObjCSelectorExpr>(op)) {
13504     return Context.getPointerType(op->getType());
13505   } else if (lval == Expr::LV_MemberFunction) {
13506     // If it's an instance method, make a member pointer.
13507     // The expression must have exactly the form &A::foo.
13508 
13509     // If the underlying expression isn't a decl ref, give up.
13510     if (!isa<DeclRefExpr>(op)) {
13511       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13512         << OrigOp.get()->getSourceRange();
13513       return QualType();
13514     }
13515     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13516     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13517 
13518     // The id-expression was parenthesized.
13519     if (OrigOp.get() != DRE) {
13520       Diag(OpLoc, diag::err_parens_pointer_member_function)
13521         << OrigOp.get()->getSourceRange();
13522 
13523     // The method was named without a qualifier.
13524     } else if (!DRE->getQualifier()) {
13525       if (MD->getParent()->getName().empty())
13526         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13527           << op->getSourceRange();
13528       else {
13529         SmallString<32> Str;
13530         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13531         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13532           << op->getSourceRange()
13533           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13534       }
13535     }
13536 
13537     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13538     if (isa<CXXDestructorDecl>(MD))
13539       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13540 
13541     QualType MPTy = Context.getMemberPointerType(
13542         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13543     // Under the MS ABI, lock down the inheritance model now.
13544     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13545       (void)isCompleteType(OpLoc, MPTy);
13546     return MPTy;
13547   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13548     // C99 6.5.3.2p1
13549     // The operand must be either an l-value or a function designator
13550     if (!op->getType()->isFunctionType()) {
13551       // Use a special diagnostic for loads from property references.
13552       if (isa<PseudoObjectExpr>(op)) {
13553         AddressOfError = AO_Property_Expansion;
13554       } else {
13555         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13556           << op->getType() << op->getSourceRange();
13557         return QualType();
13558       }
13559     }
13560   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13561     // The operand cannot be a bit-field
13562     AddressOfError = AO_Bit_Field;
13563   } else if (op->getObjectKind() == OK_VectorComponent) {
13564     // The operand cannot be an element of a vector
13565     AddressOfError = AO_Vector_Element;
13566   } else if (op->getObjectKind() == OK_MatrixComponent) {
13567     // The operand cannot be an element of a matrix.
13568     AddressOfError = AO_Matrix_Element;
13569   } else if (dcl) { // C99 6.5.3.2p1
13570     // We have an lvalue with a decl. Make sure the decl is not declared
13571     // with the register storage-class specifier.
13572     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13573       // in C++ it is not error to take address of a register
13574       // variable (c++03 7.1.1P3)
13575       if (vd->getStorageClass() == SC_Register &&
13576           !getLangOpts().CPlusPlus) {
13577         AddressOfError = AO_Register_Variable;
13578       }
13579     } else if (isa<MSPropertyDecl>(dcl)) {
13580       AddressOfError = AO_Property_Expansion;
13581     } else if (isa<FunctionTemplateDecl>(dcl)) {
13582       return Context.OverloadTy;
13583     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13584       // Okay: we can take the address of a field.
13585       // Could be a pointer to member, though, if there is an explicit
13586       // scope qualifier for the class.
13587       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13588         DeclContext *Ctx = dcl->getDeclContext();
13589         if (Ctx && Ctx->isRecord()) {
13590           if (dcl->getType()->isReferenceType()) {
13591             Diag(OpLoc,
13592                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13593               << dcl->getDeclName() << dcl->getType();
13594             return QualType();
13595           }
13596 
13597           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13598             Ctx = Ctx->getParent();
13599 
13600           QualType MPTy = Context.getMemberPointerType(
13601               op->getType(),
13602               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13603           // Under the MS ABI, lock down the inheritance model now.
13604           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13605             (void)isCompleteType(OpLoc, MPTy);
13606           return MPTy;
13607         }
13608       }
13609     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13610                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13611       llvm_unreachable("Unknown/unexpected decl type");
13612   }
13613 
13614   if (AddressOfError != AO_No_Error) {
13615     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13616     return QualType();
13617   }
13618 
13619   if (lval == Expr::LV_IncompleteVoidType) {
13620     // Taking the address of a void variable is technically illegal, but we
13621     // allow it in cases which are otherwise valid.
13622     // Example: "extern void x; void* y = &x;".
13623     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13624   }
13625 
13626   // If the operand has type "type", the result has type "pointer to type".
13627   if (op->getType()->isObjCObjectType())
13628     return Context.getObjCObjectPointerType(op->getType());
13629 
13630   CheckAddressOfPackedMember(op);
13631 
13632   return Context.getPointerType(op->getType());
13633 }
13634 
13635 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13636   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13637   if (!DRE)
13638     return;
13639   const Decl *D = DRE->getDecl();
13640   if (!D)
13641     return;
13642   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13643   if (!Param)
13644     return;
13645   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13646     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13647       return;
13648   if (FunctionScopeInfo *FD = S.getCurFunction())
13649     if (!FD->ModifiedNonNullParams.count(Param))
13650       FD->ModifiedNonNullParams.insert(Param);
13651 }
13652 
13653 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13654 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13655                                         SourceLocation OpLoc) {
13656   if (Op->isTypeDependent())
13657     return S.Context.DependentTy;
13658 
13659   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13660   if (ConvResult.isInvalid())
13661     return QualType();
13662   Op = ConvResult.get();
13663   QualType OpTy = Op->getType();
13664   QualType Result;
13665 
13666   if (isa<CXXReinterpretCastExpr>(Op)) {
13667     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13668     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13669                                      Op->getSourceRange());
13670   }
13671 
13672   if (const PointerType *PT = OpTy->getAs<PointerType>())
13673   {
13674     Result = PT->getPointeeType();
13675   }
13676   else if (const ObjCObjectPointerType *OPT =
13677              OpTy->getAs<ObjCObjectPointerType>())
13678     Result = OPT->getPointeeType();
13679   else {
13680     ExprResult PR = S.CheckPlaceholderExpr(Op);
13681     if (PR.isInvalid()) return QualType();
13682     if (PR.get() != Op)
13683       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13684   }
13685 
13686   if (Result.isNull()) {
13687     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13688       << OpTy << Op->getSourceRange();
13689     return QualType();
13690   }
13691 
13692   // Note that per both C89 and C99, indirection is always legal, even if Result
13693   // is an incomplete type or void.  It would be possible to warn about
13694   // dereferencing a void pointer, but it's completely well-defined, and such a
13695   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13696   // for pointers to 'void' but is fine for any other pointer type:
13697   //
13698   // C++ [expr.unary.op]p1:
13699   //   [...] the expression to which [the unary * operator] is applied shall
13700   //   be a pointer to an object type, or a pointer to a function type
13701   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13702     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13703       << OpTy << Op->getSourceRange();
13704 
13705   // Dereferences are usually l-values...
13706   VK = VK_LValue;
13707 
13708   // ...except that certain expressions are never l-values in C.
13709   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13710     VK = VK_RValue;
13711 
13712   return Result;
13713 }
13714 
13715 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13716   BinaryOperatorKind Opc;
13717   switch (Kind) {
13718   default: llvm_unreachable("Unknown binop!");
13719   case tok::periodstar:           Opc = BO_PtrMemD; break;
13720   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13721   case tok::star:                 Opc = BO_Mul; break;
13722   case tok::slash:                Opc = BO_Div; break;
13723   case tok::percent:              Opc = BO_Rem; break;
13724   case tok::plus:                 Opc = BO_Add; break;
13725   case tok::minus:                Opc = BO_Sub; break;
13726   case tok::lessless:             Opc = BO_Shl; break;
13727   case tok::greatergreater:       Opc = BO_Shr; break;
13728   case tok::lessequal:            Opc = BO_LE; break;
13729   case tok::less:                 Opc = BO_LT; break;
13730   case tok::greaterequal:         Opc = BO_GE; break;
13731   case tok::greater:              Opc = BO_GT; break;
13732   case tok::exclaimequal:         Opc = BO_NE; break;
13733   case tok::equalequal:           Opc = BO_EQ; break;
13734   case tok::spaceship:            Opc = BO_Cmp; break;
13735   case tok::amp:                  Opc = BO_And; break;
13736   case tok::caret:                Opc = BO_Xor; break;
13737   case tok::pipe:                 Opc = BO_Or; break;
13738   case tok::ampamp:               Opc = BO_LAnd; break;
13739   case tok::pipepipe:             Opc = BO_LOr; break;
13740   case tok::equal:                Opc = BO_Assign; break;
13741   case tok::starequal:            Opc = BO_MulAssign; break;
13742   case tok::slashequal:           Opc = BO_DivAssign; break;
13743   case tok::percentequal:         Opc = BO_RemAssign; break;
13744   case tok::plusequal:            Opc = BO_AddAssign; break;
13745   case tok::minusequal:           Opc = BO_SubAssign; break;
13746   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13747   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13748   case tok::ampequal:             Opc = BO_AndAssign; break;
13749   case tok::caretequal:           Opc = BO_XorAssign; break;
13750   case tok::pipeequal:            Opc = BO_OrAssign; break;
13751   case tok::comma:                Opc = BO_Comma; break;
13752   }
13753   return Opc;
13754 }
13755 
13756 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13757   tok::TokenKind Kind) {
13758   UnaryOperatorKind Opc;
13759   switch (Kind) {
13760   default: llvm_unreachable("Unknown unary op!");
13761   case tok::plusplus:     Opc = UO_PreInc; break;
13762   case tok::minusminus:   Opc = UO_PreDec; break;
13763   case tok::amp:          Opc = UO_AddrOf; break;
13764   case tok::star:         Opc = UO_Deref; break;
13765   case tok::plus:         Opc = UO_Plus; break;
13766   case tok::minus:        Opc = UO_Minus; break;
13767   case tok::tilde:        Opc = UO_Not; break;
13768   case tok::exclaim:      Opc = UO_LNot; break;
13769   case tok::kw___real:    Opc = UO_Real; break;
13770   case tok::kw___imag:    Opc = UO_Imag; break;
13771   case tok::kw___extension__: Opc = UO_Extension; break;
13772   }
13773   return Opc;
13774 }
13775 
13776 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13777 /// This warning suppressed in the event of macro expansions.
13778 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13779                                    SourceLocation OpLoc, bool IsBuiltin) {
13780   if (S.inTemplateInstantiation())
13781     return;
13782   if (S.isUnevaluatedContext())
13783     return;
13784   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13785     return;
13786   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13787   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13788   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13789   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13790   if (!LHSDeclRef || !RHSDeclRef ||
13791       LHSDeclRef->getLocation().isMacroID() ||
13792       RHSDeclRef->getLocation().isMacroID())
13793     return;
13794   const ValueDecl *LHSDecl =
13795     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13796   const ValueDecl *RHSDecl =
13797     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13798   if (LHSDecl != RHSDecl)
13799     return;
13800   if (LHSDecl->getType().isVolatileQualified())
13801     return;
13802   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13803     if (RefTy->getPointeeType().isVolatileQualified())
13804       return;
13805 
13806   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13807                           : diag::warn_self_assignment_overloaded)
13808       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13809       << RHSExpr->getSourceRange();
13810 }
13811 
13812 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13813 /// is usually indicative of introspection within the Objective-C pointer.
13814 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13815                                           SourceLocation OpLoc) {
13816   if (!S.getLangOpts().ObjC)
13817     return;
13818 
13819   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13820   const Expr *LHS = L.get();
13821   const Expr *RHS = R.get();
13822 
13823   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13824     ObjCPointerExpr = LHS;
13825     OtherExpr = RHS;
13826   }
13827   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13828     ObjCPointerExpr = RHS;
13829     OtherExpr = LHS;
13830   }
13831 
13832   // This warning is deliberately made very specific to reduce false
13833   // positives with logic that uses '&' for hashing.  This logic mainly
13834   // looks for code trying to introspect into tagged pointers, which
13835   // code should generally never do.
13836   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13837     unsigned Diag = diag::warn_objc_pointer_masking;
13838     // Determine if we are introspecting the result of performSelectorXXX.
13839     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13840     // Special case messages to -performSelector and friends, which
13841     // can return non-pointer values boxed in a pointer value.
13842     // Some clients may wish to silence warnings in this subcase.
13843     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13844       Selector S = ME->getSelector();
13845       StringRef SelArg0 = S.getNameForSlot(0);
13846       if (SelArg0.startswith("performSelector"))
13847         Diag = diag::warn_objc_pointer_masking_performSelector;
13848     }
13849 
13850     S.Diag(OpLoc, Diag)
13851       << ObjCPointerExpr->getSourceRange();
13852   }
13853 }
13854 
13855 static NamedDecl *getDeclFromExpr(Expr *E) {
13856   if (!E)
13857     return nullptr;
13858   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13859     return DRE->getDecl();
13860   if (auto *ME = dyn_cast<MemberExpr>(E))
13861     return ME->getMemberDecl();
13862   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13863     return IRE->getDecl();
13864   return nullptr;
13865 }
13866 
13867 // This helper function promotes a binary operator's operands (which are of a
13868 // half vector type) to a vector of floats and then truncates the result to
13869 // a vector of either half or short.
13870 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13871                                       BinaryOperatorKind Opc, QualType ResultTy,
13872                                       ExprValueKind VK, ExprObjectKind OK,
13873                                       bool IsCompAssign, SourceLocation OpLoc,
13874                                       FPOptionsOverride FPFeatures) {
13875   auto &Context = S.getASTContext();
13876   assert((isVector(ResultTy, Context.HalfTy) ||
13877           isVector(ResultTy, Context.ShortTy)) &&
13878          "Result must be a vector of half or short");
13879   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13880          isVector(RHS.get()->getType(), Context.HalfTy) &&
13881          "both operands expected to be a half vector");
13882 
13883   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13884   QualType BinOpResTy = RHS.get()->getType();
13885 
13886   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13887   // change BinOpResTy to a vector of ints.
13888   if (isVector(ResultTy, Context.ShortTy))
13889     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13890 
13891   if (IsCompAssign)
13892     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13893                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13894                                           BinOpResTy, BinOpResTy);
13895 
13896   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13897   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13898                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13899   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13900 }
13901 
13902 static std::pair<ExprResult, ExprResult>
13903 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13904                            Expr *RHSExpr) {
13905   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13906   if (!S.Context.isDependenceAllowed()) {
13907     // C cannot handle TypoExpr nodes on either side of a binop because it
13908     // doesn't handle dependent types properly, so make sure any TypoExprs have
13909     // been dealt with before checking the operands.
13910     LHS = S.CorrectDelayedTyposInExpr(LHS);
13911     RHS = S.CorrectDelayedTyposInExpr(
13912         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13913         [Opc, LHS](Expr *E) {
13914           if (Opc != BO_Assign)
13915             return ExprResult(E);
13916           // Avoid correcting the RHS to the same Expr as the LHS.
13917           Decl *D = getDeclFromExpr(E);
13918           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13919         });
13920   }
13921   return std::make_pair(LHS, RHS);
13922 }
13923 
13924 /// Returns true if conversion between vectors of halfs and vectors of floats
13925 /// is needed.
13926 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13927                                      Expr *E0, Expr *E1 = nullptr) {
13928   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13929       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13930     return false;
13931 
13932   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13933     QualType Ty = E->IgnoreImplicit()->getType();
13934 
13935     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13936     // to vectors of floats. Although the element type of the vectors is __fp16,
13937     // the vectors shouldn't be treated as storage-only types. See the
13938     // discussion here: https://reviews.llvm.org/rG825235c140e7
13939     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13940       if (VT->getVectorKind() == VectorType::NeonVector)
13941         return false;
13942       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13943     }
13944     return false;
13945   };
13946 
13947   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13948 }
13949 
13950 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13951 /// operator @p Opc at location @c TokLoc. This routine only supports
13952 /// built-in operations; ActOnBinOp handles overloaded operators.
13953 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13954                                     BinaryOperatorKind Opc,
13955                                     Expr *LHSExpr, Expr *RHSExpr) {
13956   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13957     // The syntax only allows initializer lists on the RHS of assignment,
13958     // so we don't need to worry about accepting invalid code for
13959     // non-assignment operators.
13960     // C++11 5.17p9:
13961     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13962     //   of x = {} is x = T().
13963     InitializationKind Kind = InitializationKind::CreateDirectList(
13964         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13965     InitializedEntity Entity =
13966         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13967     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13968     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13969     if (Init.isInvalid())
13970       return Init;
13971     RHSExpr = Init.get();
13972   }
13973 
13974   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13975   QualType ResultTy;     // Result type of the binary operator.
13976   // The following two variables are used for compound assignment operators
13977   QualType CompLHSTy;    // Type of LHS after promotions for computation
13978   QualType CompResultTy; // Type of computation result
13979   ExprValueKind VK = VK_RValue;
13980   ExprObjectKind OK = OK_Ordinary;
13981   bool ConvertHalfVec = false;
13982 
13983   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13984   if (!LHS.isUsable() || !RHS.isUsable())
13985     return ExprError();
13986 
13987   if (getLangOpts().OpenCL) {
13988     QualType LHSTy = LHSExpr->getType();
13989     QualType RHSTy = RHSExpr->getType();
13990     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13991     // the ATOMIC_VAR_INIT macro.
13992     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13993       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13994       if (BO_Assign == Opc)
13995         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13996       else
13997         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13998       return ExprError();
13999     }
14000 
14001     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14002     // only with a builtin functions and therefore should be disallowed here.
14003     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14004         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14005         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14006         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14007       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14008       return ExprError();
14009     }
14010   }
14011 
14012   switch (Opc) {
14013   case BO_Assign:
14014     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14015     if (getLangOpts().CPlusPlus &&
14016         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14017       VK = LHS.get()->getValueKind();
14018       OK = LHS.get()->getObjectKind();
14019     }
14020     if (!ResultTy.isNull()) {
14021       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14022       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14023 
14024       // Avoid copying a block to the heap if the block is assigned to a local
14025       // auto variable that is declared in the same scope as the block. This
14026       // optimization is unsafe if the local variable is declared in an outer
14027       // scope. For example:
14028       //
14029       // BlockTy b;
14030       // {
14031       //   b = ^{...};
14032       // }
14033       // // It is unsafe to invoke the block here if it wasn't copied to the
14034       // // heap.
14035       // b();
14036 
14037       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14038         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14039           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14040             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14041               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14042 
14043       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14044         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14045                               NTCUC_Assignment, NTCUK_Copy);
14046     }
14047     RecordModifiableNonNullParam(*this, LHS.get());
14048     break;
14049   case BO_PtrMemD:
14050   case BO_PtrMemI:
14051     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14052                                             Opc == BO_PtrMemI);
14053     break;
14054   case BO_Mul:
14055   case BO_Div:
14056     ConvertHalfVec = true;
14057     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14058                                            Opc == BO_Div);
14059     break;
14060   case BO_Rem:
14061     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14062     break;
14063   case BO_Add:
14064     ConvertHalfVec = true;
14065     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14066     break;
14067   case BO_Sub:
14068     ConvertHalfVec = true;
14069     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14070     break;
14071   case BO_Shl:
14072   case BO_Shr:
14073     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14074     break;
14075   case BO_LE:
14076   case BO_LT:
14077   case BO_GE:
14078   case BO_GT:
14079     ConvertHalfVec = true;
14080     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14081     break;
14082   case BO_EQ:
14083   case BO_NE:
14084     ConvertHalfVec = true;
14085     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14086     break;
14087   case BO_Cmp:
14088     ConvertHalfVec = true;
14089     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14090     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14091     break;
14092   case BO_And:
14093     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14094     LLVM_FALLTHROUGH;
14095   case BO_Xor:
14096   case BO_Or:
14097     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14098     break;
14099   case BO_LAnd:
14100   case BO_LOr:
14101     ConvertHalfVec = true;
14102     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14103     break;
14104   case BO_MulAssign:
14105   case BO_DivAssign:
14106     ConvertHalfVec = true;
14107     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14108                                                Opc == BO_DivAssign);
14109     CompLHSTy = CompResultTy;
14110     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14111       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14112     break;
14113   case BO_RemAssign:
14114     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14115     CompLHSTy = CompResultTy;
14116     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14117       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14118     break;
14119   case BO_AddAssign:
14120     ConvertHalfVec = true;
14121     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14122     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14123       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14124     break;
14125   case BO_SubAssign:
14126     ConvertHalfVec = true;
14127     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14128     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14129       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14130     break;
14131   case BO_ShlAssign:
14132   case BO_ShrAssign:
14133     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14134     CompLHSTy = CompResultTy;
14135     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14136       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14137     break;
14138   case BO_AndAssign:
14139   case BO_OrAssign: // fallthrough
14140     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14141     LLVM_FALLTHROUGH;
14142   case BO_XorAssign:
14143     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14144     CompLHSTy = CompResultTy;
14145     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14146       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14147     break;
14148   case BO_Comma:
14149     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14150     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14151       VK = RHS.get()->getValueKind();
14152       OK = RHS.get()->getObjectKind();
14153     }
14154     break;
14155   }
14156   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14157     return ExprError();
14158 
14159   // Some of the binary operations require promoting operands of half vector to
14160   // float vectors and truncating the result back to half vector. For now, we do
14161   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14162   // arm64).
14163   assert(
14164       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14165                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14166       "both sides are half vectors or neither sides are");
14167   ConvertHalfVec =
14168       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14169 
14170   // Check for array bounds violations for both sides of the BinaryOperator
14171   CheckArrayAccess(LHS.get());
14172   CheckArrayAccess(RHS.get());
14173 
14174   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14175     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14176                                                  &Context.Idents.get("object_setClass"),
14177                                                  SourceLocation(), LookupOrdinaryName);
14178     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14179       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14180       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14181           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14182                                         "object_setClass(")
14183           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14184                                           ",")
14185           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14186     }
14187     else
14188       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14189   }
14190   else if (const ObjCIvarRefExpr *OIRE =
14191            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14192     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14193 
14194   // Opc is not a compound assignment if CompResultTy is null.
14195   if (CompResultTy.isNull()) {
14196     if (ConvertHalfVec)
14197       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14198                                  OpLoc, CurFPFeatureOverrides());
14199     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14200                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14201   }
14202 
14203   // Handle compound assignments.
14204   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14205       OK_ObjCProperty) {
14206     VK = VK_LValue;
14207     OK = LHS.get()->getObjectKind();
14208   }
14209 
14210   // The LHS is not converted to the result type for fixed-point compound
14211   // assignment as the common type is computed on demand. Reset the CompLHSTy
14212   // to the LHS type we would have gotten after unary conversions.
14213   if (CompResultTy->isFixedPointType())
14214     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14215 
14216   if (ConvertHalfVec)
14217     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14218                                OpLoc, CurFPFeatureOverrides());
14219 
14220   return CompoundAssignOperator::Create(
14221       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14222       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14223 }
14224 
14225 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14226 /// operators are mixed in a way that suggests that the programmer forgot that
14227 /// comparison operators have higher precedence. The most typical example of
14228 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14229 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14230                                       SourceLocation OpLoc, Expr *LHSExpr,
14231                                       Expr *RHSExpr) {
14232   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14233   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14234 
14235   // Check that one of the sides is a comparison operator and the other isn't.
14236   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14237   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14238   if (isLeftComp == isRightComp)
14239     return;
14240 
14241   // Bitwise operations are sometimes used as eager logical ops.
14242   // Don't diagnose this.
14243   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14244   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14245   if (isLeftBitwise || isRightBitwise)
14246     return;
14247 
14248   SourceRange DiagRange = isLeftComp
14249                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14250                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14251   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14252   SourceRange ParensRange =
14253       isLeftComp
14254           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14255           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14256 
14257   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14258     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14259   SuggestParentheses(Self, OpLoc,
14260     Self.PDiag(diag::note_precedence_silence) << OpStr,
14261     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14262   SuggestParentheses(Self, OpLoc,
14263     Self.PDiag(diag::note_precedence_bitwise_first)
14264       << BinaryOperator::getOpcodeStr(Opc),
14265     ParensRange);
14266 }
14267 
14268 /// It accepts a '&&' expr that is inside a '||' one.
14269 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14270 /// in parentheses.
14271 static void
14272 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14273                                        BinaryOperator *Bop) {
14274   assert(Bop->getOpcode() == BO_LAnd);
14275   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14276       << Bop->getSourceRange() << OpLoc;
14277   SuggestParentheses(Self, Bop->getOperatorLoc(),
14278     Self.PDiag(diag::note_precedence_silence)
14279       << Bop->getOpcodeStr(),
14280     Bop->getSourceRange());
14281 }
14282 
14283 /// Returns true if the given expression can be evaluated as a constant
14284 /// 'true'.
14285 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14286   bool Res;
14287   return !E->isValueDependent() &&
14288          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14289 }
14290 
14291 /// Returns true if the given expression can be evaluated as a constant
14292 /// 'false'.
14293 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14294   bool Res;
14295   return !E->isValueDependent() &&
14296          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14297 }
14298 
14299 /// Look for '&&' in the left hand of a '||' expr.
14300 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14301                                              Expr *LHSExpr, Expr *RHSExpr) {
14302   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14303     if (Bop->getOpcode() == BO_LAnd) {
14304       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14305       if (EvaluatesAsFalse(S, RHSExpr))
14306         return;
14307       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14308       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14309         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14310     } else if (Bop->getOpcode() == BO_LOr) {
14311       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14312         // If it's "a || b && 1 || c" we didn't warn earlier for
14313         // "a || b && 1", but warn now.
14314         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14315           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14316       }
14317     }
14318   }
14319 }
14320 
14321 /// Look for '&&' in the right hand of a '||' expr.
14322 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14323                                              Expr *LHSExpr, Expr *RHSExpr) {
14324   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14325     if (Bop->getOpcode() == BO_LAnd) {
14326       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14327       if (EvaluatesAsFalse(S, LHSExpr))
14328         return;
14329       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14330       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14331         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14332     }
14333   }
14334 }
14335 
14336 /// Look for bitwise op in the left or right hand of a bitwise op with
14337 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14338 /// the '&' expression in parentheses.
14339 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14340                                          SourceLocation OpLoc, Expr *SubExpr) {
14341   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14342     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14343       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14344         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14345         << Bop->getSourceRange() << OpLoc;
14346       SuggestParentheses(S, Bop->getOperatorLoc(),
14347         S.PDiag(diag::note_precedence_silence)
14348           << Bop->getOpcodeStr(),
14349         Bop->getSourceRange());
14350     }
14351   }
14352 }
14353 
14354 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14355                                     Expr *SubExpr, StringRef Shift) {
14356   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14357     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14358       StringRef Op = Bop->getOpcodeStr();
14359       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14360           << Bop->getSourceRange() << OpLoc << Shift << Op;
14361       SuggestParentheses(S, Bop->getOperatorLoc(),
14362           S.PDiag(diag::note_precedence_silence) << Op,
14363           Bop->getSourceRange());
14364     }
14365   }
14366 }
14367 
14368 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14369                                  Expr *LHSExpr, Expr *RHSExpr) {
14370   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14371   if (!OCE)
14372     return;
14373 
14374   FunctionDecl *FD = OCE->getDirectCallee();
14375   if (!FD || !FD->isOverloadedOperator())
14376     return;
14377 
14378   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14379   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14380     return;
14381 
14382   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14383       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14384       << (Kind == OO_LessLess);
14385   SuggestParentheses(S, OCE->getOperatorLoc(),
14386                      S.PDiag(diag::note_precedence_silence)
14387                          << (Kind == OO_LessLess ? "<<" : ">>"),
14388                      OCE->getSourceRange());
14389   SuggestParentheses(
14390       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14391       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14392 }
14393 
14394 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14395 /// precedence.
14396 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14397                                     SourceLocation OpLoc, Expr *LHSExpr,
14398                                     Expr *RHSExpr){
14399   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14400   if (BinaryOperator::isBitwiseOp(Opc))
14401     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14402 
14403   // Diagnose "arg1 & arg2 | arg3"
14404   if ((Opc == BO_Or || Opc == BO_Xor) &&
14405       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14406     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14407     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14408   }
14409 
14410   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14411   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14412   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14413     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14414     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14415   }
14416 
14417   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14418       || Opc == BO_Shr) {
14419     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14420     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14421     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14422   }
14423 
14424   // Warn on overloaded shift operators and comparisons, such as:
14425   // cout << 5 == 4;
14426   if (BinaryOperator::isComparisonOp(Opc))
14427     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14428 }
14429 
14430 // Binary Operators.  'Tok' is the token for the operator.
14431 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14432                             tok::TokenKind Kind,
14433                             Expr *LHSExpr, Expr *RHSExpr) {
14434   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14435   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14436   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14437 
14438   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14439   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14440 
14441   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14442 }
14443 
14444 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14445                        UnresolvedSetImpl &Functions) {
14446   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14447   if (OverOp != OO_None && OverOp != OO_Equal)
14448     LookupOverloadedOperatorName(OverOp, S, Functions);
14449 
14450   // In C++20 onwards, we may have a second operator to look up.
14451   if (getLangOpts().CPlusPlus20) {
14452     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14453       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14454   }
14455 }
14456 
14457 /// Build an overloaded binary operator expression in the given scope.
14458 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14459                                        BinaryOperatorKind Opc,
14460                                        Expr *LHS, Expr *RHS) {
14461   switch (Opc) {
14462   case BO_Assign:
14463   case BO_DivAssign:
14464   case BO_RemAssign:
14465   case BO_SubAssign:
14466   case BO_AndAssign:
14467   case BO_OrAssign:
14468   case BO_XorAssign:
14469     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14470     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14471     break;
14472   default:
14473     break;
14474   }
14475 
14476   // Find all of the overloaded operators visible from this point.
14477   UnresolvedSet<16> Functions;
14478   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14479 
14480   // Build the (potentially-overloaded, potentially-dependent)
14481   // binary operation.
14482   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14483 }
14484 
14485 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14486                             BinaryOperatorKind Opc,
14487                             Expr *LHSExpr, Expr *RHSExpr) {
14488   ExprResult LHS, RHS;
14489   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14490   if (!LHS.isUsable() || !RHS.isUsable())
14491     return ExprError();
14492   LHSExpr = LHS.get();
14493   RHSExpr = RHS.get();
14494 
14495   // We want to end up calling one of checkPseudoObjectAssignment
14496   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14497   // both expressions are overloadable or either is type-dependent),
14498   // or CreateBuiltinBinOp (in any other case).  We also want to get
14499   // any placeholder types out of the way.
14500 
14501   // Handle pseudo-objects in the LHS.
14502   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14503     // Assignments with a pseudo-object l-value need special analysis.
14504     if (pty->getKind() == BuiltinType::PseudoObject &&
14505         BinaryOperator::isAssignmentOp(Opc))
14506       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14507 
14508     // Don't resolve overloads if the other type is overloadable.
14509     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14510       // We can't actually test that if we still have a placeholder,
14511       // though.  Fortunately, none of the exceptions we see in that
14512       // code below are valid when the LHS is an overload set.  Note
14513       // that an overload set can be dependently-typed, but it never
14514       // instantiates to having an overloadable type.
14515       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14516       if (resolvedRHS.isInvalid()) return ExprError();
14517       RHSExpr = resolvedRHS.get();
14518 
14519       if (RHSExpr->isTypeDependent() ||
14520           RHSExpr->getType()->isOverloadableType())
14521         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14522     }
14523 
14524     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14525     // template, diagnose the missing 'template' keyword instead of diagnosing
14526     // an invalid use of a bound member function.
14527     //
14528     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14529     // to C++1z [over.over]/1.4, but we already checked for that case above.
14530     if (Opc == BO_LT && inTemplateInstantiation() &&
14531         (pty->getKind() == BuiltinType::BoundMember ||
14532          pty->getKind() == BuiltinType::Overload)) {
14533       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14534       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14535           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14536             return isa<FunctionTemplateDecl>(ND);
14537           })) {
14538         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14539                                 : OE->getNameLoc(),
14540              diag::err_template_kw_missing)
14541           << OE->getName().getAsString() << "";
14542         return ExprError();
14543       }
14544     }
14545 
14546     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14547     if (LHS.isInvalid()) return ExprError();
14548     LHSExpr = LHS.get();
14549   }
14550 
14551   // Handle pseudo-objects in the RHS.
14552   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14553     // An overload in the RHS can potentially be resolved by the type
14554     // being assigned to.
14555     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14556       if (getLangOpts().CPlusPlus &&
14557           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14558            LHSExpr->getType()->isOverloadableType()))
14559         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14560 
14561       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14562     }
14563 
14564     // Don't resolve overloads if the other type is overloadable.
14565     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14566         LHSExpr->getType()->isOverloadableType())
14567       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14568 
14569     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14570     if (!resolvedRHS.isUsable()) return ExprError();
14571     RHSExpr = resolvedRHS.get();
14572   }
14573 
14574   if (getLangOpts().CPlusPlus) {
14575     // If either expression is type-dependent, always build an
14576     // overloaded op.
14577     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14578       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14579 
14580     // Otherwise, build an overloaded op if either expression has an
14581     // overloadable type.
14582     if (LHSExpr->getType()->isOverloadableType() ||
14583         RHSExpr->getType()->isOverloadableType())
14584       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14585   }
14586 
14587   if (getLangOpts().RecoveryAST &&
14588       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14589     assert(!getLangOpts().CPlusPlus);
14590     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14591            "Should only occur in error-recovery path.");
14592     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14593       // C [6.15.16] p3:
14594       // An assignment expression has the value of the left operand after the
14595       // assignment, but is not an lvalue.
14596       return CompoundAssignOperator::Create(
14597           Context, LHSExpr, RHSExpr, Opc,
14598           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14599           OpLoc, CurFPFeatureOverrides());
14600     QualType ResultType;
14601     switch (Opc) {
14602     case BO_Assign:
14603       ResultType = LHSExpr->getType().getUnqualifiedType();
14604       break;
14605     case BO_LT:
14606     case BO_GT:
14607     case BO_LE:
14608     case BO_GE:
14609     case BO_EQ:
14610     case BO_NE:
14611     case BO_LAnd:
14612     case BO_LOr:
14613       // These operators have a fixed result type regardless of operands.
14614       ResultType = Context.IntTy;
14615       break;
14616     case BO_Comma:
14617       ResultType = RHSExpr->getType();
14618       break;
14619     default:
14620       ResultType = Context.DependentTy;
14621       break;
14622     }
14623     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14624                                   VK_RValue, OK_Ordinary, OpLoc,
14625                                   CurFPFeatureOverrides());
14626   }
14627 
14628   // Build a built-in binary operation.
14629   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14630 }
14631 
14632 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14633   if (T.isNull() || T->isDependentType())
14634     return false;
14635 
14636   if (!T->isPromotableIntegerType())
14637     return true;
14638 
14639   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14640 }
14641 
14642 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14643                                       UnaryOperatorKind Opc,
14644                                       Expr *InputExpr) {
14645   ExprResult Input = InputExpr;
14646   ExprValueKind VK = VK_RValue;
14647   ExprObjectKind OK = OK_Ordinary;
14648   QualType resultType;
14649   bool CanOverflow = false;
14650 
14651   bool ConvertHalfVec = false;
14652   if (getLangOpts().OpenCL) {
14653     QualType Ty = InputExpr->getType();
14654     // The only legal unary operation for atomics is '&'.
14655     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14656     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14657     // only with a builtin functions and therefore should be disallowed here.
14658         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14659         || Ty->isBlockPointerType())) {
14660       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14661                        << InputExpr->getType()
14662                        << Input.get()->getSourceRange());
14663     }
14664   }
14665 
14666   switch (Opc) {
14667   case UO_PreInc:
14668   case UO_PreDec:
14669   case UO_PostInc:
14670   case UO_PostDec:
14671     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14672                                                 OpLoc,
14673                                                 Opc == UO_PreInc ||
14674                                                 Opc == UO_PostInc,
14675                                                 Opc == UO_PreInc ||
14676                                                 Opc == UO_PreDec);
14677     CanOverflow = isOverflowingIntegerType(Context, resultType);
14678     break;
14679   case UO_AddrOf:
14680     resultType = CheckAddressOfOperand(Input, OpLoc);
14681     CheckAddressOfNoDeref(InputExpr);
14682     RecordModifiableNonNullParam(*this, InputExpr);
14683     break;
14684   case UO_Deref: {
14685     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14686     if (Input.isInvalid()) return ExprError();
14687     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14688     break;
14689   }
14690   case UO_Plus:
14691   case UO_Minus:
14692     CanOverflow = Opc == UO_Minus &&
14693                   isOverflowingIntegerType(Context, Input.get()->getType());
14694     Input = UsualUnaryConversions(Input.get());
14695     if (Input.isInvalid()) return ExprError();
14696     // Unary plus and minus require promoting an operand of half vector to a
14697     // float vector and truncating the result back to a half vector. For now, we
14698     // do this only when HalfArgsAndReturns is set (that is, when the target is
14699     // arm or arm64).
14700     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14701 
14702     // If the operand is a half vector, promote it to a float vector.
14703     if (ConvertHalfVec)
14704       Input = convertVector(Input.get(), Context.FloatTy, *this);
14705     resultType = Input.get()->getType();
14706     if (resultType->isDependentType())
14707       break;
14708     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14709       break;
14710     else if (resultType->isVectorType() &&
14711              // The z vector extensions don't allow + or - with bool vectors.
14712              (!Context.getLangOpts().ZVector ||
14713               resultType->castAs<VectorType>()->getVectorKind() !=
14714               VectorType::AltiVecBool))
14715       break;
14716     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14717              Opc == UO_Plus &&
14718              resultType->isPointerType())
14719       break;
14720 
14721     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14722       << resultType << Input.get()->getSourceRange());
14723 
14724   case UO_Not: // bitwise complement
14725     Input = UsualUnaryConversions(Input.get());
14726     if (Input.isInvalid())
14727       return ExprError();
14728     resultType = Input.get()->getType();
14729     if (resultType->isDependentType())
14730       break;
14731     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14732     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14733       // C99 does not support '~' for complex conjugation.
14734       Diag(OpLoc, diag::ext_integer_complement_complex)
14735           << resultType << Input.get()->getSourceRange();
14736     else if (resultType->hasIntegerRepresentation())
14737       break;
14738     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14739       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14740       // on vector float types.
14741       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14742       if (!T->isIntegerType())
14743         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14744                           << resultType << Input.get()->getSourceRange());
14745     } else {
14746       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14747                        << resultType << Input.get()->getSourceRange());
14748     }
14749     break;
14750 
14751   case UO_LNot: // logical negation
14752     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14753     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14754     if (Input.isInvalid()) return ExprError();
14755     resultType = Input.get()->getType();
14756 
14757     // Though we still have to promote half FP to float...
14758     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14759       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14760       resultType = Context.FloatTy;
14761     }
14762 
14763     if (resultType->isDependentType())
14764       break;
14765     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14766       // C99 6.5.3.3p1: ok, fallthrough;
14767       if (Context.getLangOpts().CPlusPlus) {
14768         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14769         // operand contextually converted to bool.
14770         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14771                                   ScalarTypeToBooleanCastKind(resultType));
14772       } else if (Context.getLangOpts().OpenCL &&
14773                  Context.getLangOpts().OpenCLVersion < 120) {
14774         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14775         // operate on scalar float types.
14776         if (!resultType->isIntegerType() && !resultType->isPointerType())
14777           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14778                            << resultType << Input.get()->getSourceRange());
14779       }
14780     } else if (resultType->isExtVectorType()) {
14781       if (Context.getLangOpts().OpenCL &&
14782           Context.getLangOpts().OpenCLVersion < 120 &&
14783           !Context.getLangOpts().OpenCLCPlusPlus) {
14784         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14785         // operate on vector float types.
14786         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14787         if (!T->isIntegerType())
14788           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14789                            << resultType << Input.get()->getSourceRange());
14790       }
14791       // Vector logical not returns the signed variant of the operand type.
14792       resultType = GetSignedVectorType(resultType);
14793       break;
14794     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14795       const VectorType *VTy = resultType->castAs<VectorType>();
14796       if (VTy->getVectorKind() != VectorType::GenericVector)
14797         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14798                          << resultType << Input.get()->getSourceRange());
14799 
14800       // Vector logical not returns the signed variant of the operand type.
14801       resultType = GetSignedVectorType(resultType);
14802       break;
14803     } else {
14804       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14805         << resultType << Input.get()->getSourceRange());
14806     }
14807 
14808     // LNot always has type int. C99 6.5.3.3p5.
14809     // In C++, it's bool. C++ 5.3.1p8
14810     resultType = Context.getLogicalOperationType();
14811     break;
14812   case UO_Real:
14813   case UO_Imag:
14814     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14815     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14816     // complex l-values to ordinary l-values and all other values to r-values.
14817     if (Input.isInvalid()) return ExprError();
14818     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14819       if (Input.get()->getValueKind() != VK_RValue &&
14820           Input.get()->getObjectKind() == OK_Ordinary)
14821         VK = Input.get()->getValueKind();
14822     } else if (!getLangOpts().CPlusPlus) {
14823       // In C, a volatile scalar is read by __imag. In C++, it is not.
14824       Input = DefaultLvalueConversion(Input.get());
14825     }
14826     break;
14827   case UO_Extension:
14828     resultType = Input.get()->getType();
14829     VK = Input.get()->getValueKind();
14830     OK = Input.get()->getObjectKind();
14831     break;
14832   case UO_Coawait:
14833     // It's unnecessary to represent the pass-through operator co_await in the
14834     // AST; just return the input expression instead.
14835     assert(!Input.get()->getType()->isDependentType() &&
14836                    "the co_await expression must be non-dependant before "
14837                    "building operator co_await");
14838     return Input;
14839   }
14840   if (resultType.isNull() || Input.isInvalid())
14841     return ExprError();
14842 
14843   // Check for array bounds violations in the operand of the UnaryOperator,
14844   // except for the '*' and '&' operators that have to be handled specially
14845   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14846   // that are explicitly defined as valid by the standard).
14847   if (Opc != UO_AddrOf && Opc != UO_Deref)
14848     CheckArrayAccess(Input.get());
14849 
14850   auto *UO =
14851       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14852                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14853 
14854   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14855       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14856       !isUnevaluatedContext())
14857     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14858 
14859   // Convert the result back to a half vector.
14860   if (ConvertHalfVec)
14861     return convertVector(UO, Context.HalfTy, *this);
14862   return UO;
14863 }
14864 
14865 /// Determine whether the given expression is a qualified member
14866 /// access expression, of a form that could be turned into a pointer to member
14867 /// with the address-of operator.
14868 bool Sema::isQualifiedMemberAccess(Expr *E) {
14869   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14870     if (!DRE->getQualifier())
14871       return false;
14872 
14873     ValueDecl *VD = DRE->getDecl();
14874     if (!VD->isCXXClassMember())
14875       return false;
14876 
14877     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14878       return true;
14879     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14880       return Method->isInstance();
14881 
14882     return false;
14883   }
14884 
14885   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14886     if (!ULE->getQualifier())
14887       return false;
14888 
14889     for (NamedDecl *D : ULE->decls()) {
14890       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14891         if (Method->isInstance())
14892           return true;
14893       } else {
14894         // Overload set does not contain methods.
14895         break;
14896       }
14897     }
14898 
14899     return false;
14900   }
14901 
14902   return false;
14903 }
14904 
14905 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14906                               UnaryOperatorKind Opc, Expr *Input) {
14907   // First things first: handle placeholders so that the
14908   // overloaded-operator check considers the right type.
14909   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14910     // Increment and decrement of pseudo-object references.
14911     if (pty->getKind() == BuiltinType::PseudoObject &&
14912         UnaryOperator::isIncrementDecrementOp(Opc))
14913       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14914 
14915     // extension is always a builtin operator.
14916     if (Opc == UO_Extension)
14917       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14918 
14919     // & gets special logic for several kinds of placeholder.
14920     // The builtin code knows what to do.
14921     if (Opc == UO_AddrOf &&
14922         (pty->getKind() == BuiltinType::Overload ||
14923          pty->getKind() == BuiltinType::UnknownAny ||
14924          pty->getKind() == BuiltinType::BoundMember))
14925       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14926 
14927     // Anything else needs to be handled now.
14928     ExprResult Result = CheckPlaceholderExpr(Input);
14929     if (Result.isInvalid()) return ExprError();
14930     Input = Result.get();
14931   }
14932 
14933   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14934       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14935       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14936     // Find all of the overloaded operators visible from this point.
14937     UnresolvedSet<16> Functions;
14938     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14939     if (S && OverOp != OO_None)
14940       LookupOverloadedOperatorName(OverOp, S, Functions);
14941 
14942     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14943   }
14944 
14945   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14946 }
14947 
14948 // Unary Operators.  'Tok' is the token for the operator.
14949 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14950                               tok::TokenKind Op, Expr *Input) {
14951   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14952 }
14953 
14954 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14955 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14956                                 LabelDecl *TheDecl) {
14957   TheDecl->markUsed(Context);
14958   // Create the AST node.  The address of a label always has type 'void*'.
14959   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14960                                      Context.getPointerType(Context.VoidTy));
14961 }
14962 
14963 void Sema::ActOnStartStmtExpr() {
14964   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14965 }
14966 
14967 void Sema::ActOnStmtExprError() {
14968   // Note that function is also called by TreeTransform when leaving a
14969   // StmtExpr scope without rebuilding anything.
14970 
14971   DiscardCleanupsInEvaluationContext();
14972   PopExpressionEvaluationContext();
14973 }
14974 
14975 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14976                                SourceLocation RPLoc) {
14977   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14978 }
14979 
14980 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14981                                SourceLocation RPLoc, unsigned TemplateDepth) {
14982   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14983   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14984 
14985   if (hasAnyUnrecoverableErrorsInThisFunction())
14986     DiscardCleanupsInEvaluationContext();
14987   assert(!Cleanup.exprNeedsCleanups() &&
14988          "cleanups within StmtExpr not correctly bound!");
14989   PopExpressionEvaluationContext();
14990 
14991   // FIXME: there are a variety of strange constraints to enforce here, for
14992   // example, it is not possible to goto into a stmt expression apparently.
14993   // More semantic analysis is needed.
14994 
14995   // If there are sub-stmts in the compound stmt, take the type of the last one
14996   // as the type of the stmtexpr.
14997   QualType Ty = Context.VoidTy;
14998   bool StmtExprMayBindToTemp = false;
14999   if (!Compound->body_empty()) {
15000     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15001     if (const auto *LastStmt =
15002             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15003       if (const Expr *Value = LastStmt->getExprStmt()) {
15004         StmtExprMayBindToTemp = true;
15005         Ty = Value->getType();
15006       }
15007     }
15008   }
15009 
15010   // FIXME: Check that expression type is complete/non-abstract; statement
15011   // expressions are not lvalues.
15012   Expr *ResStmtExpr =
15013       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15014   if (StmtExprMayBindToTemp)
15015     return MaybeBindToTemporary(ResStmtExpr);
15016   return ResStmtExpr;
15017 }
15018 
15019 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15020   if (ER.isInvalid())
15021     return ExprError();
15022 
15023   // Do function/array conversion on the last expression, but not
15024   // lvalue-to-rvalue.  However, initialize an unqualified type.
15025   ER = DefaultFunctionArrayConversion(ER.get());
15026   if (ER.isInvalid())
15027     return ExprError();
15028   Expr *E = ER.get();
15029 
15030   if (E->isTypeDependent())
15031     return E;
15032 
15033   // In ARC, if the final expression ends in a consume, splice
15034   // the consume out and bind it later.  In the alternate case
15035   // (when dealing with a retainable type), the result
15036   // initialization will create a produce.  In both cases the
15037   // result will be +1, and we'll need to balance that out with
15038   // a bind.
15039   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15040   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15041     return Cast->getSubExpr();
15042 
15043   // FIXME: Provide a better location for the initialization.
15044   return PerformCopyInitialization(
15045       InitializedEntity::InitializeStmtExprResult(
15046           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15047       SourceLocation(), E);
15048 }
15049 
15050 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15051                                       TypeSourceInfo *TInfo,
15052                                       ArrayRef<OffsetOfComponent> Components,
15053                                       SourceLocation RParenLoc) {
15054   QualType ArgTy = TInfo->getType();
15055   bool Dependent = ArgTy->isDependentType();
15056   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15057 
15058   // We must have at least one component that refers to the type, and the first
15059   // one is known to be a field designator.  Verify that the ArgTy represents
15060   // a struct/union/class.
15061   if (!Dependent && !ArgTy->isRecordType())
15062     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15063                        << ArgTy << TypeRange);
15064 
15065   // Type must be complete per C99 7.17p3 because a declaring a variable
15066   // with an incomplete type would be ill-formed.
15067   if (!Dependent
15068       && RequireCompleteType(BuiltinLoc, ArgTy,
15069                              diag::err_offsetof_incomplete_type, TypeRange))
15070     return ExprError();
15071 
15072   bool DidWarnAboutNonPOD = false;
15073   QualType CurrentType = ArgTy;
15074   SmallVector<OffsetOfNode, 4> Comps;
15075   SmallVector<Expr*, 4> Exprs;
15076   for (const OffsetOfComponent &OC : Components) {
15077     if (OC.isBrackets) {
15078       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15079       if (!CurrentType->isDependentType()) {
15080         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15081         if(!AT)
15082           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15083                            << CurrentType);
15084         CurrentType = AT->getElementType();
15085       } else
15086         CurrentType = Context.DependentTy;
15087 
15088       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15089       if (IdxRval.isInvalid())
15090         return ExprError();
15091       Expr *Idx = IdxRval.get();
15092 
15093       // The expression must be an integral expression.
15094       // FIXME: An integral constant expression?
15095       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15096           !Idx->getType()->isIntegerType())
15097         return ExprError(
15098             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15099             << Idx->getSourceRange());
15100 
15101       // Record this array index.
15102       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15103       Exprs.push_back(Idx);
15104       continue;
15105     }
15106 
15107     // Offset of a field.
15108     if (CurrentType->isDependentType()) {
15109       // We have the offset of a field, but we can't look into the dependent
15110       // type. Just record the identifier of the field.
15111       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15112       CurrentType = Context.DependentTy;
15113       continue;
15114     }
15115 
15116     // We need to have a complete type to look into.
15117     if (RequireCompleteType(OC.LocStart, CurrentType,
15118                             diag::err_offsetof_incomplete_type))
15119       return ExprError();
15120 
15121     // Look for the designated field.
15122     const RecordType *RC = CurrentType->getAs<RecordType>();
15123     if (!RC)
15124       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15125                        << CurrentType);
15126     RecordDecl *RD = RC->getDecl();
15127 
15128     // C++ [lib.support.types]p5:
15129     //   The macro offsetof accepts a restricted set of type arguments in this
15130     //   International Standard. type shall be a POD structure or a POD union
15131     //   (clause 9).
15132     // C++11 [support.types]p4:
15133     //   If type is not a standard-layout class (Clause 9), the results are
15134     //   undefined.
15135     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15136       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15137       unsigned DiagID =
15138         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15139                             : diag::ext_offsetof_non_pod_type;
15140 
15141       if (!IsSafe && !DidWarnAboutNonPOD &&
15142           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15143                               PDiag(DiagID)
15144                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15145                               << CurrentType))
15146         DidWarnAboutNonPOD = true;
15147     }
15148 
15149     // Look for the field.
15150     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15151     LookupQualifiedName(R, RD);
15152     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15153     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15154     if (!MemberDecl) {
15155       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15156         MemberDecl = IndirectMemberDecl->getAnonField();
15157     }
15158 
15159     if (!MemberDecl)
15160       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15161                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15162                                                               OC.LocEnd));
15163 
15164     // C99 7.17p3:
15165     //   (If the specified member is a bit-field, the behavior is undefined.)
15166     //
15167     // We diagnose this as an error.
15168     if (MemberDecl->isBitField()) {
15169       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15170         << MemberDecl->getDeclName()
15171         << SourceRange(BuiltinLoc, RParenLoc);
15172       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15173       return ExprError();
15174     }
15175 
15176     RecordDecl *Parent = MemberDecl->getParent();
15177     if (IndirectMemberDecl)
15178       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15179 
15180     // If the member was found in a base class, introduce OffsetOfNodes for
15181     // the base class indirections.
15182     CXXBasePaths Paths;
15183     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15184                       Paths)) {
15185       if (Paths.getDetectedVirtual()) {
15186         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15187           << MemberDecl->getDeclName()
15188           << SourceRange(BuiltinLoc, RParenLoc);
15189         return ExprError();
15190       }
15191 
15192       CXXBasePath &Path = Paths.front();
15193       for (const CXXBasePathElement &B : Path)
15194         Comps.push_back(OffsetOfNode(B.Base));
15195     }
15196 
15197     if (IndirectMemberDecl) {
15198       for (auto *FI : IndirectMemberDecl->chain()) {
15199         assert(isa<FieldDecl>(FI));
15200         Comps.push_back(OffsetOfNode(OC.LocStart,
15201                                      cast<FieldDecl>(FI), OC.LocEnd));
15202       }
15203     } else
15204       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15205 
15206     CurrentType = MemberDecl->getType().getNonReferenceType();
15207   }
15208 
15209   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15210                               Comps, Exprs, RParenLoc);
15211 }
15212 
15213 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15214                                       SourceLocation BuiltinLoc,
15215                                       SourceLocation TypeLoc,
15216                                       ParsedType ParsedArgTy,
15217                                       ArrayRef<OffsetOfComponent> Components,
15218                                       SourceLocation RParenLoc) {
15219 
15220   TypeSourceInfo *ArgTInfo;
15221   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15222   if (ArgTy.isNull())
15223     return ExprError();
15224 
15225   if (!ArgTInfo)
15226     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15227 
15228   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15229 }
15230 
15231 
15232 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15233                                  Expr *CondExpr,
15234                                  Expr *LHSExpr, Expr *RHSExpr,
15235                                  SourceLocation RPLoc) {
15236   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15237 
15238   ExprValueKind VK = VK_RValue;
15239   ExprObjectKind OK = OK_Ordinary;
15240   QualType resType;
15241   bool CondIsTrue = false;
15242   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15243     resType = Context.DependentTy;
15244   } else {
15245     // The conditional expression is required to be a constant expression.
15246     llvm::APSInt condEval(32);
15247     ExprResult CondICE = VerifyIntegerConstantExpression(
15248         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15249     if (CondICE.isInvalid())
15250       return ExprError();
15251     CondExpr = CondICE.get();
15252     CondIsTrue = condEval.getZExtValue();
15253 
15254     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15255     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15256 
15257     resType = ActiveExpr->getType();
15258     VK = ActiveExpr->getValueKind();
15259     OK = ActiveExpr->getObjectKind();
15260   }
15261 
15262   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15263                                   resType, VK, OK, RPLoc, CondIsTrue);
15264 }
15265 
15266 //===----------------------------------------------------------------------===//
15267 // Clang Extensions.
15268 //===----------------------------------------------------------------------===//
15269 
15270 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15271 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15272   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15273 
15274   if (LangOpts.CPlusPlus) {
15275     MangleNumberingContext *MCtx;
15276     Decl *ManglingContextDecl;
15277     std::tie(MCtx, ManglingContextDecl) =
15278         getCurrentMangleNumberContext(Block->getDeclContext());
15279     if (MCtx) {
15280       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15281       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15282     }
15283   }
15284 
15285   PushBlockScope(CurScope, Block);
15286   CurContext->addDecl(Block);
15287   if (CurScope)
15288     PushDeclContext(CurScope, Block);
15289   else
15290     CurContext = Block;
15291 
15292   getCurBlock()->HasImplicitReturnType = true;
15293 
15294   // Enter a new evaluation context to insulate the block from any
15295   // cleanups from the enclosing full-expression.
15296   PushExpressionEvaluationContext(
15297       ExpressionEvaluationContext::PotentiallyEvaluated);
15298 }
15299 
15300 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15301                                Scope *CurScope) {
15302   assert(ParamInfo.getIdentifier() == nullptr &&
15303          "block-id should have no identifier!");
15304   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15305   BlockScopeInfo *CurBlock = getCurBlock();
15306 
15307   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15308   QualType T = Sig->getType();
15309 
15310   // FIXME: We should allow unexpanded parameter packs here, but that would,
15311   // in turn, make the block expression contain unexpanded parameter packs.
15312   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15313     // Drop the parameters.
15314     FunctionProtoType::ExtProtoInfo EPI;
15315     EPI.HasTrailingReturn = false;
15316     EPI.TypeQuals.addConst();
15317     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15318     Sig = Context.getTrivialTypeSourceInfo(T);
15319   }
15320 
15321   // GetTypeForDeclarator always produces a function type for a block
15322   // literal signature.  Furthermore, it is always a FunctionProtoType
15323   // unless the function was written with a typedef.
15324   assert(T->isFunctionType() &&
15325          "GetTypeForDeclarator made a non-function block signature");
15326 
15327   // Look for an explicit signature in that function type.
15328   FunctionProtoTypeLoc ExplicitSignature;
15329 
15330   if ((ExplicitSignature = Sig->getTypeLoc()
15331                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15332 
15333     // Check whether that explicit signature was synthesized by
15334     // GetTypeForDeclarator.  If so, don't save that as part of the
15335     // written signature.
15336     if (ExplicitSignature.getLocalRangeBegin() ==
15337         ExplicitSignature.getLocalRangeEnd()) {
15338       // This would be much cheaper if we stored TypeLocs instead of
15339       // TypeSourceInfos.
15340       TypeLoc Result = ExplicitSignature.getReturnLoc();
15341       unsigned Size = Result.getFullDataSize();
15342       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15343       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15344 
15345       ExplicitSignature = FunctionProtoTypeLoc();
15346     }
15347   }
15348 
15349   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15350   CurBlock->FunctionType = T;
15351 
15352   const auto *Fn = T->castAs<FunctionType>();
15353   QualType RetTy = Fn->getReturnType();
15354   bool isVariadic =
15355       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15356 
15357   CurBlock->TheDecl->setIsVariadic(isVariadic);
15358 
15359   // Context.DependentTy is used as a placeholder for a missing block
15360   // return type.  TODO:  what should we do with declarators like:
15361   //   ^ * { ... }
15362   // If the answer is "apply template argument deduction"....
15363   if (RetTy != Context.DependentTy) {
15364     CurBlock->ReturnType = RetTy;
15365     CurBlock->TheDecl->setBlockMissingReturnType(false);
15366     CurBlock->HasImplicitReturnType = false;
15367   }
15368 
15369   // Push block parameters from the declarator if we had them.
15370   SmallVector<ParmVarDecl*, 8> Params;
15371   if (ExplicitSignature) {
15372     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15373       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15374       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15375           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15376         // Diagnose this as an extension in C17 and earlier.
15377         if (!getLangOpts().C2x)
15378           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15379       }
15380       Params.push_back(Param);
15381     }
15382 
15383   // Fake up parameter variables if we have a typedef, like
15384   //   ^ fntype { ... }
15385   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15386     for (const auto &I : Fn->param_types()) {
15387       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15388           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15389       Params.push_back(Param);
15390     }
15391   }
15392 
15393   // Set the parameters on the block decl.
15394   if (!Params.empty()) {
15395     CurBlock->TheDecl->setParams(Params);
15396     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15397                              /*CheckParameterNames=*/false);
15398   }
15399 
15400   // Finally we can process decl attributes.
15401   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15402 
15403   // Put the parameter variables in scope.
15404   for (auto AI : CurBlock->TheDecl->parameters()) {
15405     AI->setOwningFunction(CurBlock->TheDecl);
15406 
15407     // If this has an identifier, add it to the scope stack.
15408     if (AI->getIdentifier()) {
15409       CheckShadow(CurBlock->TheScope, AI);
15410 
15411       PushOnScopeChains(AI, CurBlock->TheScope);
15412     }
15413   }
15414 }
15415 
15416 /// ActOnBlockError - If there is an error parsing a block, this callback
15417 /// is invoked to pop the information about the block from the action impl.
15418 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15419   // Leave the expression-evaluation context.
15420   DiscardCleanupsInEvaluationContext();
15421   PopExpressionEvaluationContext();
15422 
15423   // Pop off CurBlock, handle nested blocks.
15424   PopDeclContext();
15425   PopFunctionScopeInfo();
15426 }
15427 
15428 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15429 /// literal was successfully completed.  ^(int x){...}
15430 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15431                                     Stmt *Body, Scope *CurScope) {
15432   // If blocks are disabled, emit an error.
15433   if (!LangOpts.Blocks)
15434     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15435 
15436   // Leave the expression-evaluation context.
15437   if (hasAnyUnrecoverableErrorsInThisFunction())
15438     DiscardCleanupsInEvaluationContext();
15439   assert(!Cleanup.exprNeedsCleanups() &&
15440          "cleanups within block not correctly bound!");
15441   PopExpressionEvaluationContext();
15442 
15443   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15444   BlockDecl *BD = BSI->TheDecl;
15445 
15446   if (BSI->HasImplicitReturnType)
15447     deduceClosureReturnType(*BSI);
15448 
15449   QualType RetTy = Context.VoidTy;
15450   if (!BSI->ReturnType.isNull())
15451     RetTy = BSI->ReturnType;
15452 
15453   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15454   QualType BlockTy;
15455 
15456   // If the user wrote a function type in some form, try to use that.
15457   if (!BSI->FunctionType.isNull()) {
15458     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15459 
15460     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15461     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15462 
15463     // Turn protoless block types into nullary block types.
15464     if (isa<FunctionNoProtoType>(FTy)) {
15465       FunctionProtoType::ExtProtoInfo EPI;
15466       EPI.ExtInfo = Ext;
15467       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15468 
15469     // Otherwise, if we don't need to change anything about the function type,
15470     // preserve its sugar structure.
15471     } else if (FTy->getReturnType() == RetTy &&
15472                (!NoReturn || FTy->getNoReturnAttr())) {
15473       BlockTy = BSI->FunctionType;
15474 
15475     // Otherwise, make the minimal modifications to the function type.
15476     } else {
15477       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15478       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15479       EPI.TypeQuals = Qualifiers();
15480       EPI.ExtInfo = Ext;
15481       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15482     }
15483 
15484   // If we don't have a function type, just build one from nothing.
15485   } else {
15486     FunctionProtoType::ExtProtoInfo EPI;
15487     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15488     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15489   }
15490 
15491   DiagnoseUnusedParameters(BD->parameters());
15492   BlockTy = Context.getBlockPointerType(BlockTy);
15493 
15494   // If needed, diagnose invalid gotos and switches in the block.
15495   if (getCurFunction()->NeedsScopeChecking() &&
15496       !PP.isCodeCompletionEnabled())
15497     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15498 
15499   BD->setBody(cast<CompoundStmt>(Body));
15500 
15501   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15502     DiagnoseUnguardedAvailabilityViolations(BD);
15503 
15504   // Try to apply the named return value optimization. We have to check again
15505   // if we can do this, though, because blocks keep return statements around
15506   // to deduce an implicit return type.
15507   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15508       !BD->isDependentContext())
15509     computeNRVO(Body, BSI);
15510 
15511   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15512       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15513     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15514                           NTCUK_Destruct|NTCUK_Copy);
15515 
15516   PopDeclContext();
15517 
15518   // Set the captured variables on the block.
15519   SmallVector<BlockDecl::Capture, 4> Captures;
15520   for (Capture &Cap : BSI->Captures) {
15521     if (Cap.isInvalid() || Cap.isThisCapture())
15522       continue;
15523 
15524     VarDecl *Var = Cap.getVariable();
15525     Expr *CopyExpr = nullptr;
15526     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15527       if (const RecordType *Record =
15528               Cap.getCaptureType()->getAs<RecordType>()) {
15529         // The capture logic needs the destructor, so make sure we mark it.
15530         // Usually this is unnecessary because most local variables have
15531         // their destructors marked at declaration time, but parameters are
15532         // an exception because it's technically only the call site that
15533         // actually requires the destructor.
15534         if (isa<ParmVarDecl>(Var))
15535           FinalizeVarWithDestructor(Var, Record);
15536 
15537         // Enter a separate potentially-evaluated context while building block
15538         // initializers to isolate their cleanups from those of the block
15539         // itself.
15540         // FIXME: Is this appropriate even when the block itself occurs in an
15541         // unevaluated operand?
15542         EnterExpressionEvaluationContext EvalContext(
15543             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15544 
15545         SourceLocation Loc = Cap.getLocation();
15546 
15547         ExprResult Result = BuildDeclarationNameExpr(
15548             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15549 
15550         // According to the blocks spec, the capture of a variable from
15551         // the stack requires a const copy constructor.  This is not true
15552         // of the copy/move done to move a __block variable to the heap.
15553         if (!Result.isInvalid() &&
15554             !Result.get()->getType().isConstQualified()) {
15555           Result = ImpCastExprToType(Result.get(),
15556                                      Result.get()->getType().withConst(),
15557                                      CK_NoOp, VK_LValue);
15558         }
15559 
15560         if (!Result.isInvalid()) {
15561           Result = PerformCopyInitialization(
15562               InitializedEntity::InitializeBlock(Var->getLocation(),
15563                                                  Cap.getCaptureType(), false),
15564               Loc, Result.get());
15565         }
15566 
15567         // Build a full-expression copy expression if initialization
15568         // succeeded and used a non-trivial constructor.  Recover from
15569         // errors by pretending that the copy isn't necessary.
15570         if (!Result.isInvalid() &&
15571             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15572                 ->isTrivial()) {
15573           Result = MaybeCreateExprWithCleanups(Result);
15574           CopyExpr = Result.get();
15575         }
15576       }
15577     }
15578 
15579     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15580                               CopyExpr);
15581     Captures.push_back(NewCap);
15582   }
15583   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15584 
15585   // Pop the block scope now but keep it alive to the end of this function.
15586   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15587   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15588 
15589   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15590 
15591   // If the block isn't obviously global, i.e. it captures anything at
15592   // all, then we need to do a few things in the surrounding context:
15593   if (Result->getBlockDecl()->hasCaptures()) {
15594     // First, this expression has a new cleanup object.
15595     ExprCleanupObjects.push_back(Result->getBlockDecl());
15596     Cleanup.setExprNeedsCleanups(true);
15597 
15598     // It also gets a branch-protected scope if any of the captured
15599     // variables needs destruction.
15600     for (const auto &CI : Result->getBlockDecl()->captures()) {
15601       const VarDecl *var = CI.getVariable();
15602       if (var->getType().isDestructedType() != QualType::DK_none) {
15603         setFunctionHasBranchProtectedScope();
15604         break;
15605       }
15606     }
15607   }
15608 
15609   if (getCurFunction())
15610     getCurFunction()->addBlock(BD);
15611 
15612   return Result;
15613 }
15614 
15615 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15616                             SourceLocation RPLoc) {
15617   TypeSourceInfo *TInfo;
15618   GetTypeFromParser(Ty, &TInfo);
15619   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15620 }
15621 
15622 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15623                                 Expr *E, TypeSourceInfo *TInfo,
15624                                 SourceLocation RPLoc) {
15625   Expr *OrigExpr = E;
15626   bool IsMS = false;
15627 
15628   // CUDA device code does not support varargs.
15629   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15630     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15631       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15632       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15633         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15634     }
15635   }
15636 
15637   // NVPTX does not support va_arg expression.
15638   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15639       Context.getTargetInfo().getTriple().isNVPTX())
15640     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15641 
15642   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15643   // as Microsoft ABI on an actual Microsoft platform, where
15644   // __builtin_ms_va_list and __builtin_va_list are the same.)
15645   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15646       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15647     QualType MSVaListType = Context.getBuiltinMSVaListType();
15648     if (Context.hasSameType(MSVaListType, E->getType())) {
15649       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15650         return ExprError();
15651       IsMS = true;
15652     }
15653   }
15654 
15655   // Get the va_list type
15656   QualType VaListType = Context.getBuiltinVaListType();
15657   if (!IsMS) {
15658     if (VaListType->isArrayType()) {
15659       // Deal with implicit array decay; for example, on x86-64,
15660       // va_list is an array, but it's supposed to decay to
15661       // a pointer for va_arg.
15662       VaListType = Context.getArrayDecayedType(VaListType);
15663       // Make sure the input expression also decays appropriately.
15664       ExprResult Result = UsualUnaryConversions(E);
15665       if (Result.isInvalid())
15666         return ExprError();
15667       E = Result.get();
15668     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15669       // If va_list is a record type and we are compiling in C++ mode,
15670       // check the argument using reference binding.
15671       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15672           Context, Context.getLValueReferenceType(VaListType), false);
15673       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15674       if (Init.isInvalid())
15675         return ExprError();
15676       E = Init.getAs<Expr>();
15677     } else {
15678       // Otherwise, the va_list argument must be an l-value because
15679       // it is modified by va_arg.
15680       if (!E->isTypeDependent() &&
15681           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15682         return ExprError();
15683     }
15684   }
15685 
15686   if (!IsMS && !E->isTypeDependent() &&
15687       !Context.hasSameType(VaListType, E->getType()))
15688     return ExprError(
15689         Diag(E->getBeginLoc(),
15690              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15691         << OrigExpr->getType() << E->getSourceRange());
15692 
15693   if (!TInfo->getType()->isDependentType()) {
15694     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15695                             diag::err_second_parameter_to_va_arg_incomplete,
15696                             TInfo->getTypeLoc()))
15697       return ExprError();
15698 
15699     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15700                                TInfo->getType(),
15701                                diag::err_second_parameter_to_va_arg_abstract,
15702                                TInfo->getTypeLoc()))
15703       return ExprError();
15704 
15705     if (!TInfo->getType().isPODType(Context)) {
15706       Diag(TInfo->getTypeLoc().getBeginLoc(),
15707            TInfo->getType()->isObjCLifetimeType()
15708              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15709              : diag::warn_second_parameter_to_va_arg_not_pod)
15710         << TInfo->getType()
15711         << TInfo->getTypeLoc().getSourceRange();
15712     }
15713 
15714     // Check for va_arg where arguments of the given type will be promoted
15715     // (i.e. this va_arg is guaranteed to have undefined behavior).
15716     QualType PromoteType;
15717     if (TInfo->getType()->isPromotableIntegerType()) {
15718       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15719       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15720         PromoteType = QualType();
15721     }
15722     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15723       PromoteType = Context.DoubleTy;
15724     if (!PromoteType.isNull())
15725       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15726                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15727                           << TInfo->getType()
15728                           << PromoteType
15729                           << TInfo->getTypeLoc().getSourceRange());
15730   }
15731 
15732   QualType T = TInfo->getType().getNonLValueExprType(Context);
15733   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15734 }
15735 
15736 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15737   // The type of __null will be int or long, depending on the size of
15738   // pointers on the target.
15739   QualType Ty;
15740   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15741   if (pw == Context.getTargetInfo().getIntWidth())
15742     Ty = Context.IntTy;
15743   else if (pw == Context.getTargetInfo().getLongWidth())
15744     Ty = Context.LongTy;
15745   else if (pw == Context.getTargetInfo().getLongLongWidth())
15746     Ty = Context.LongLongTy;
15747   else {
15748     llvm_unreachable("I don't know size of pointer!");
15749   }
15750 
15751   return new (Context) GNUNullExpr(Ty, TokenLoc);
15752 }
15753 
15754 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15755                                     SourceLocation BuiltinLoc,
15756                                     SourceLocation RPLoc) {
15757   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15758 }
15759 
15760 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15761                                     SourceLocation BuiltinLoc,
15762                                     SourceLocation RPLoc,
15763                                     DeclContext *ParentContext) {
15764   return new (Context)
15765       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15766 }
15767 
15768 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15769                                         bool Diagnose) {
15770   if (!getLangOpts().ObjC)
15771     return false;
15772 
15773   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15774   if (!PT)
15775     return false;
15776   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15777 
15778   // Ignore any parens, implicit casts (should only be
15779   // array-to-pointer decays), and not-so-opaque values.  The last is
15780   // important for making this trigger for property assignments.
15781   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15782   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15783     if (OV->getSourceExpr())
15784       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15785 
15786   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15787     if (!PT->isObjCIdType() &&
15788         !(ID && ID->getIdentifier()->isStr("NSString")))
15789       return false;
15790     if (!SL->isAscii())
15791       return false;
15792 
15793     if (Diagnose) {
15794       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15795           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15796       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15797     }
15798     return true;
15799   }
15800 
15801   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15802       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15803       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15804       !SrcExpr->isNullPointerConstant(
15805           getASTContext(), Expr::NPC_NeverValueDependent)) {
15806     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15807       return false;
15808     if (Diagnose) {
15809       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15810           << /*number*/1
15811           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15812       Expr *NumLit =
15813           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15814       if (NumLit)
15815         Exp = NumLit;
15816     }
15817     return true;
15818   }
15819 
15820   return false;
15821 }
15822 
15823 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15824                                               const Expr *SrcExpr) {
15825   if (!DstType->isFunctionPointerType() ||
15826       !SrcExpr->getType()->isFunctionType())
15827     return false;
15828 
15829   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15830   if (!DRE)
15831     return false;
15832 
15833   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15834   if (!FD)
15835     return false;
15836 
15837   return !S.checkAddressOfFunctionIsAvailable(FD,
15838                                               /*Complain=*/true,
15839                                               SrcExpr->getBeginLoc());
15840 }
15841 
15842 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15843                                     SourceLocation Loc,
15844                                     QualType DstType, QualType SrcType,
15845                                     Expr *SrcExpr, AssignmentAction Action,
15846                                     bool *Complained) {
15847   if (Complained)
15848     *Complained = false;
15849 
15850   // Decode the result (notice that AST's are still created for extensions).
15851   bool CheckInferredResultType = false;
15852   bool isInvalid = false;
15853   unsigned DiagKind = 0;
15854   ConversionFixItGenerator ConvHints;
15855   bool MayHaveConvFixit = false;
15856   bool MayHaveFunctionDiff = false;
15857   const ObjCInterfaceDecl *IFace = nullptr;
15858   const ObjCProtocolDecl *PDecl = nullptr;
15859 
15860   switch (ConvTy) {
15861   case Compatible:
15862       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15863       return false;
15864 
15865   case PointerToInt:
15866     if (getLangOpts().CPlusPlus) {
15867       DiagKind = diag::err_typecheck_convert_pointer_int;
15868       isInvalid = true;
15869     } else {
15870       DiagKind = diag::ext_typecheck_convert_pointer_int;
15871     }
15872     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15873     MayHaveConvFixit = true;
15874     break;
15875   case IntToPointer:
15876     if (getLangOpts().CPlusPlus) {
15877       DiagKind = diag::err_typecheck_convert_int_pointer;
15878       isInvalid = true;
15879     } else {
15880       DiagKind = diag::ext_typecheck_convert_int_pointer;
15881     }
15882     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15883     MayHaveConvFixit = true;
15884     break;
15885   case IncompatibleFunctionPointer:
15886     if (getLangOpts().CPlusPlus) {
15887       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15888       isInvalid = true;
15889     } else {
15890       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15891     }
15892     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15893     MayHaveConvFixit = true;
15894     break;
15895   case IncompatiblePointer:
15896     if (Action == AA_Passing_CFAudited) {
15897       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15898     } else if (getLangOpts().CPlusPlus) {
15899       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15900       isInvalid = true;
15901     } else {
15902       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15903     }
15904     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15905       SrcType->isObjCObjectPointerType();
15906     if (!CheckInferredResultType) {
15907       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15908     } else if (CheckInferredResultType) {
15909       SrcType = SrcType.getUnqualifiedType();
15910       DstType = DstType.getUnqualifiedType();
15911     }
15912     MayHaveConvFixit = true;
15913     break;
15914   case IncompatiblePointerSign:
15915     if (getLangOpts().CPlusPlus) {
15916       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15917       isInvalid = true;
15918     } else {
15919       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15920     }
15921     break;
15922   case FunctionVoidPointer:
15923     if (getLangOpts().CPlusPlus) {
15924       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15925       isInvalid = true;
15926     } else {
15927       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15928     }
15929     break;
15930   case IncompatiblePointerDiscardsQualifiers: {
15931     // Perform array-to-pointer decay if necessary.
15932     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15933 
15934     isInvalid = true;
15935 
15936     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15937     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15938     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15939       DiagKind = diag::err_typecheck_incompatible_address_space;
15940       break;
15941 
15942     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15943       DiagKind = diag::err_typecheck_incompatible_ownership;
15944       break;
15945     }
15946 
15947     llvm_unreachable("unknown error case for discarding qualifiers!");
15948     // fallthrough
15949   }
15950   case CompatiblePointerDiscardsQualifiers:
15951     // If the qualifiers lost were because we were applying the
15952     // (deprecated) C++ conversion from a string literal to a char*
15953     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15954     // Ideally, this check would be performed in
15955     // checkPointerTypesForAssignment. However, that would require a
15956     // bit of refactoring (so that the second argument is an
15957     // expression, rather than a type), which should be done as part
15958     // of a larger effort to fix checkPointerTypesForAssignment for
15959     // C++ semantics.
15960     if (getLangOpts().CPlusPlus &&
15961         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15962       return false;
15963     if (getLangOpts().CPlusPlus) {
15964       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15965       isInvalid = true;
15966     } else {
15967       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15968     }
15969 
15970     break;
15971   case IncompatibleNestedPointerQualifiers:
15972     if (getLangOpts().CPlusPlus) {
15973       isInvalid = true;
15974       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15975     } else {
15976       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15977     }
15978     break;
15979   case IncompatibleNestedPointerAddressSpaceMismatch:
15980     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15981     isInvalid = true;
15982     break;
15983   case IntToBlockPointer:
15984     DiagKind = diag::err_int_to_block_pointer;
15985     isInvalid = true;
15986     break;
15987   case IncompatibleBlockPointer:
15988     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15989     isInvalid = true;
15990     break;
15991   case IncompatibleObjCQualifiedId: {
15992     if (SrcType->isObjCQualifiedIdType()) {
15993       const ObjCObjectPointerType *srcOPT =
15994                 SrcType->castAs<ObjCObjectPointerType>();
15995       for (auto *srcProto : srcOPT->quals()) {
15996         PDecl = srcProto;
15997         break;
15998       }
15999       if (const ObjCInterfaceType *IFaceT =
16000             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16001         IFace = IFaceT->getDecl();
16002     }
16003     else if (DstType->isObjCQualifiedIdType()) {
16004       const ObjCObjectPointerType *dstOPT =
16005         DstType->castAs<ObjCObjectPointerType>();
16006       for (auto *dstProto : dstOPT->quals()) {
16007         PDecl = dstProto;
16008         break;
16009       }
16010       if (const ObjCInterfaceType *IFaceT =
16011             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16012         IFace = IFaceT->getDecl();
16013     }
16014     if (getLangOpts().CPlusPlus) {
16015       DiagKind = diag::err_incompatible_qualified_id;
16016       isInvalid = true;
16017     } else {
16018       DiagKind = diag::warn_incompatible_qualified_id;
16019     }
16020     break;
16021   }
16022   case IncompatibleVectors:
16023     if (getLangOpts().CPlusPlus) {
16024       DiagKind = diag::err_incompatible_vectors;
16025       isInvalid = true;
16026     } else {
16027       DiagKind = diag::warn_incompatible_vectors;
16028     }
16029     break;
16030   case IncompatibleObjCWeakRef:
16031     DiagKind = diag::err_arc_weak_unavailable_assign;
16032     isInvalid = true;
16033     break;
16034   case Incompatible:
16035     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16036       if (Complained)
16037         *Complained = true;
16038       return true;
16039     }
16040 
16041     DiagKind = diag::err_typecheck_convert_incompatible;
16042     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16043     MayHaveConvFixit = true;
16044     isInvalid = true;
16045     MayHaveFunctionDiff = true;
16046     break;
16047   }
16048 
16049   QualType FirstType, SecondType;
16050   switch (Action) {
16051   case AA_Assigning:
16052   case AA_Initializing:
16053     // The destination type comes first.
16054     FirstType = DstType;
16055     SecondType = SrcType;
16056     break;
16057 
16058   case AA_Returning:
16059   case AA_Passing:
16060   case AA_Passing_CFAudited:
16061   case AA_Converting:
16062   case AA_Sending:
16063   case AA_Casting:
16064     // The source type comes first.
16065     FirstType = SrcType;
16066     SecondType = DstType;
16067     break;
16068   }
16069 
16070   PartialDiagnostic FDiag = PDiag(DiagKind);
16071   if (Action == AA_Passing_CFAudited)
16072     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16073   else
16074     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16075 
16076   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16077       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16078     auto isPlainChar = [](const clang::Type *Type) {
16079       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16080              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16081     };
16082     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16083               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16084   }
16085 
16086   // If we can fix the conversion, suggest the FixIts.
16087   if (!ConvHints.isNull()) {
16088     for (FixItHint &H : ConvHints.Hints)
16089       FDiag << H;
16090   }
16091 
16092   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16093 
16094   if (MayHaveFunctionDiff)
16095     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16096 
16097   Diag(Loc, FDiag);
16098   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16099        DiagKind == diag::err_incompatible_qualified_id) &&
16100       PDecl && IFace && !IFace->hasDefinition())
16101     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16102         << IFace << PDecl;
16103 
16104   if (SecondType == Context.OverloadTy)
16105     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16106                               FirstType, /*TakingAddress=*/true);
16107 
16108   if (CheckInferredResultType)
16109     EmitRelatedResultTypeNote(SrcExpr);
16110 
16111   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16112     EmitRelatedResultTypeNoteForReturn(DstType);
16113 
16114   if (Complained)
16115     *Complained = true;
16116   return isInvalid;
16117 }
16118 
16119 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16120                                                  llvm::APSInt *Result,
16121                                                  AllowFoldKind CanFold) {
16122   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16123   public:
16124     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16125                                              QualType T) override {
16126       return S.Diag(Loc, diag::err_ice_not_integral)
16127              << T << S.LangOpts.CPlusPlus;
16128     }
16129     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16130       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16131     }
16132   } Diagnoser;
16133 
16134   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16135 }
16136 
16137 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16138                                                  llvm::APSInt *Result,
16139                                                  unsigned DiagID,
16140                                                  AllowFoldKind CanFold) {
16141   class IDDiagnoser : public VerifyICEDiagnoser {
16142     unsigned DiagID;
16143 
16144   public:
16145     IDDiagnoser(unsigned DiagID)
16146       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16147 
16148     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16149       return S.Diag(Loc, DiagID);
16150     }
16151   } Diagnoser(DiagID);
16152 
16153   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16154 }
16155 
16156 Sema::SemaDiagnosticBuilder
16157 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16158                                              QualType T) {
16159   return diagnoseNotICE(S, Loc);
16160 }
16161 
16162 Sema::SemaDiagnosticBuilder
16163 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16164   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16165 }
16166 
16167 ExprResult
16168 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16169                                       VerifyICEDiagnoser &Diagnoser,
16170                                       AllowFoldKind CanFold) {
16171   SourceLocation DiagLoc = E->getBeginLoc();
16172 
16173   if (getLangOpts().CPlusPlus11) {
16174     // C++11 [expr.const]p5:
16175     //   If an expression of literal class type is used in a context where an
16176     //   integral constant expression is required, then that class type shall
16177     //   have a single non-explicit conversion function to an integral or
16178     //   unscoped enumeration type
16179     ExprResult Converted;
16180     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16181       VerifyICEDiagnoser &BaseDiagnoser;
16182     public:
16183       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16184           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16185                                 BaseDiagnoser.Suppress, true),
16186             BaseDiagnoser(BaseDiagnoser) {}
16187 
16188       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16189                                            QualType T) override {
16190         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16191       }
16192 
16193       SemaDiagnosticBuilder diagnoseIncomplete(
16194           Sema &S, SourceLocation Loc, QualType T) override {
16195         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16196       }
16197 
16198       SemaDiagnosticBuilder diagnoseExplicitConv(
16199           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16200         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16201       }
16202 
16203       SemaDiagnosticBuilder noteExplicitConv(
16204           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16205         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16206                  << ConvTy->isEnumeralType() << ConvTy;
16207       }
16208 
16209       SemaDiagnosticBuilder diagnoseAmbiguous(
16210           Sema &S, SourceLocation Loc, QualType T) override {
16211         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16212       }
16213 
16214       SemaDiagnosticBuilder noteAmbiguous(
16215           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16216         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16217                  << ConvTy->isEnumeralType() << ConvTy;
16218       }
16219 
16220       SemaDiagnosticBuilder diagnoseConversion(
16221           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16222         llvm_unreachable("conversion functions are permitted");
16223       }
16224     } ConvertDiagnoser(Diagnoser);
16225 
16226     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16227                                                     ConvertDiagnoser);
16228     if (Converted.isInvalid())
16229       return Converted;
16230     E = Converted.get();
16231     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16232       return ExprError();
16233   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16234     // An ICE must be of integral or unscoped enumeration type.
16235     if (!Diagnoser.Suppress)
16236       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16237           << E->getSourceRange();
16238     return ExprError();
16239   }
16240 
16241   ExprResult RValueExpr = DefaultLvalueConversion(E);
16242   if (RValueExpr.isInvalid())
16243     return ExprError();
16244 
16245   E = RValueExpr.get();
16246 
16247   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16248   // in the non-ICE case.
16249   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16250     if (Result)
16251       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16252     if (!isa<ConstantExpr>(E))
16253       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16254                  : ConstantExpr::Create(Context, E);
16255     return E;
16256   }
16257 
16258   Expr::EvalResult EvalResult;
16259   SmallVector<PartialDiagnosticAt, 8> Notes;
16260   EvalResult.Diag = &Notes;
16261 
16262   // Try to evaluate the expression, and produce diagnostics explaining why it's
16263   // not a constant expression as a side-effect.
16264   bool Folded =
16265       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16266       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16267 
16268   if (!isa<ConstantExpr>(E))
16269     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16270 
16271   // In C++11, we can rely on diagnostics being produced for any expression
16272   // which is not a constant expression. If no diagnostics were produced, then
16273   // this is a constant expression.
16274   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16275     if (Result)
16276       *Result = EvalResult.Val.getInt();
16277     return E;
16278   }
16279 
16280   // If our only note is the usual "invalid subexpression" note, just point
16281   // the caret at its location rather than producing an essentially
16282   // redundant note.
16283   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16284         diag::note_invalid_subexpr_in_const_expr) {
16285     DiagLoc = Notes[0].first;
16286     Notes.clear();
16287   }
16288 
16289   if (!Folded || !CanFold) {
16290     if (!Diagnoser.Suppress) {
16291       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16292       for (const PartialDiagnosticAt &Note : Notes)
16293         Diag(Note.first, Note.second);
16294     }
16295 
16296     return ExprError();
16297   }
16298 
16299   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16300   for (const PartialDiagnosticAt &Note : Notes)
16301     Diag(Note.first, Note.second);
16302 
16303   if (Result)
16304     *Result = EvalResult.Val.getInt();
16305   return E;
16306 }
16307 
16308 namespace {
16309   // Handle the case where we conclude a expression which we speculatively
16310   // considered to be unevaluated is actually evaluated.
16311   class TransformToPE : public TreeTransform<TransformToPE> {
16312     typedef TreeTransform<TransformToPE> BaseTransform;
16313 
16314   public:
16315     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16316 
16317     // Make sure we redo semantic analysis
16318     bool AlwaysRebuild() { return true; }
16319     bool ReplacingOriginal() { return true; }
16320 
16321     // We need to special-case DeclRefExprs referring to FieldDecls which
16322     // are not part of a member pointer formation; normal TreeTransforming
16323     // doesn't catch this case because of the way we represent them in the AST.
16324     // FIXME: This is a bit ugly; is it really the best way to handle this
16325     // case?
16326     //
16327     // Error on DeclRefExprs referring to FieldDecls.
16328     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16329       if (isa<FieldDecl>(E->getDecl()) &&
16330           !SemaRef.isUnevaluatedContext())
16331         return SemaRef.Diag(E->getLocation(),
16332                             diag::err_invalid_non_static_member_use)
16333             << E->getDecl() << E->getSourceRange();
16334 
16335       return BaseTransform::TransformDeclRefExpr(E);
16336     }
16337 
16338     // Exception: filter out member pointer formation
16339     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16340       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16341         return E;
16342 
16343       return BaseTransform::TransformUnaryOperator(E);
16344     }
16345 
16346     // The body of a lambda-expression is in a separate expression evaluation
16347     // context so never needs to be transformed.
16348     // FIXME: Ideally we wouldn't transform the closure type either, and would
16349     // just recreate the capture expressions and lambda expression.
16350     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16351       return SkipLambdaBody(E, Body);
16352     }
16353   };
16354 }
16355 
16356 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16357   assert(isUnevaluatedContext() &&
16358          "Should only transform unevaluated expressions");
16359   ExprEvalContexts.back().Context =
16360       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16361   if (isUnevaluatedContext())
16362     return E;
16363   return TransformToPE(*this).TransformExpr(E);
16364 }
16365 
16366 void
16367 Sema::PushExpressionEvaluationContext(
16368     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16369     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16370   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16371                                 LambdaContextDecl, ExprContext);
16372   Cleanup.reset();
16373   if (!MaybeODRUseExprs.empty())
16374     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16375 }
16376 
16377 void
16378 Sema::PushExpressionEvaluationContext(
16379     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16380     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16381   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16382   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16383 }
16384 
16385 namespace {
16386 
16387 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16388   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16389   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16390     if (E->getOpcode() == UO_Deref)
16391       return CheckPossibleDeref(S, E->getSubExpr());
16392   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16393     return CheckPossibleDeref(S, E->getBase());
16394   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16395     return CheckPossibleDeref(S, E->getBase());
16396   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16397     QualType Inner;
16398     QualType Ty = E->getType();
16399     if (const auto *Ptr = Ty->getAs<PointerType>())
16400       Inner = Ptr->getPointeeType();
16401     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16402       Inner = Arr->getElementType();
16403     else
16404       return nullptr;
16405 
16406     if (Inner->hasAttr(attr::NoDeref))
16407       return E;
16408   }
16409   return nullptr;
16410 }
16411 
16412 } // namespace
16413 
16414 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16415   for (const Expr *E : Rec.PossibleDerefs) {
16416     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16417     if (DeclRef) {
16418       const ValueDecl *Decl = DeclRef->getDecl();
16419       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16420           << Decl->getName() << E->getSourceRange();
16421       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16422     } else {
16423       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16424           << E->getSourceRange();
16425     }
16426   }
16427   Rec.PossibleDerefs.clear();
16428 }
16429 
16430 /// Check whether E, which is either a discarded-value expression or an
16431 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16432 /// and if so, remove it from the list of volatile-qualified assignments that
16433 /// we are going to warn are deprecated.
16434 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16435   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16436     return;
16437 
16438   // Note: ignoring parens here is not justified by the standard rules, but
16439   // ignoring parentheses seems like a more reasonable approach, and this only
16440   // drives a deprecation warning so doesn't affect conformance.
16441   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16442     if (BO->getOpcode() == BO_Assign) {
16443       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16444       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16445                  LHSs.end());
16446     }
16447   }
16448 }
16449 
16450 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16451   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16452       RebuildingImmediateInvocation)
16453     return E;
16454 
16455   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16456   /// It's OK if this fails; we'll also remove this in
16457   /// HandleImmediateInvocations, but catching it here allows us to avoid
16458   /// walking the AST looking for it in simple cases.
16459   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16460     if (auto *DeclRef =
16461             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16462       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16463 
16464   E = MaybeCreateExprWithCleanups(E);
16465 
16466   ConstantExpr *Res = ConstantExpr::Create(
16467       getASTContext(), E.get(),
16468       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16469                                    getASTContext()),
16470       /*IsImmediateInvocation*/ true);
16471   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16472   return Res;
16473 }
16474 
16475 static void EvaluateAndDiagnoseImmediateInvocation(
16476     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16477   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16478   Expr::EvalResult Eval;
16479   Eval.Diag = &Notes;
16480   ConstantExpr *CE = Candidate.getPointer();
16481   bool Result = CE->EvaluateAsConstantExpr(
16482       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16483   if (!Result || !Notes.empty()) {
16484     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16485     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16486       InnerExpr = FunctionalCast->getSubExpr();
16487     FunctionDecl *FD = nullptr;
16488     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16489       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16490     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16491       FD = Call->getConstructor();
16492     else
16493       llvm_unreachable("unhandled decl kind");
16494     assert(FD->isConsteval());
16495     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16496     for (auto &Note : Notes)
16497       SemaRef.Diag(Note.first, Note.second);
16498     return;
16499   }
16500   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16501 }
16502 
16503 static void RemoveNestedImmediateInvocation(
16504     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16505     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16506   struct ComplexRemove : TreeTransform<ComplexRemove> {
16507     using Base = TreeTransform<ComplexRemove>;
16508     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16509     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16510     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16511         CurrentII;
16512     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16513                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16514                   SmallVector<Sema::ImmediateInvocationCandidate,
16515                               4>::reverse_iterator Current)
16516         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16517     void RemoveImmediateInvocation(ConstantExpr* E) {
16518       auto It = std::find_if(CurrentII, IISet.rend(),
16519                              [E](Sema::ImmediateInvocationCandidate Elem) {
16520                                return Elem.getPointer() == E;
16521                              });
16522       assert(It != IISet.rend() &&
16523              "ConstantExpr marked IsImmediateInvocation should "
16524              "be present");
16525       It->setInt(1); // Mark as deleted
16526     }
16527     ExprResult TransformConstantExpr(ConstantExpr *E) {
16528       if (!E->isImmediateInvocation())
16529         return Base::TransformConstantExpr(E);
16530       RemoveImmediateInvocation(E);
16531       return Base::TransformExpr(E->getSubExpr());
16532     }
16533     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16534     /// we need to remove its DeclRefExpr from the DRSet.
16535     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16536       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16537       return Base::TransformCXXOperatorCallExpr(E);
16538     }
16539     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16540     /// here.
16541     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16542       if (!Init)
16543         return Init;
16544       /// ConstantExpr are the first layer of implicit node to be removed so if
16545       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16546       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16547         if (CE->isImmediateInvocation())
16548           RemoveImmediateInvocation(CE);
16549       return Base::TransformInitializer(Init, NotCopyInit);
16550     }
16551     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16552       DRSet.erase(E);
16553       return E;
16554     }
16555     bool AlwaysRebuild() { return false; }
16556     bool ReplacingOriginal() { return true; }
16557     bool AllowSkippingCXXConstructExpr() {
16558       bool Res = AllowSkippingFirstCXXConstructExpr;
16559       AllowSkippingFirstCXXConstructExpr = true;
16560       return Res;
16561     }
16562     bool AllowSkippingFirstCXXConstructExpr = true;
16563   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16564                 Rec.ImmediateInvocationCandidates, It);
16565 
16566   /// CXXConstructExpr with a single argument are getting skipped by
16567   /// TreeTransform in some situtation because they could be implicit. This
16568   /// can only occur for the top-level CXXConstructExpr because it is used
16569   /// nowhere in the expression being transformed therefore will not be rebuilt.
16570   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16571   /// skipping the first CXXConstructExpr.
16572   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16573     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16574 
16575   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16576   assert(Res.isUsable());
16577   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16578   It->getPointer()->setSubExpr(Res.get());
16579 }
16580 
16581 static void
16582 HandleImmediateInvocations(Sema &SemaRef,
16583                            Sema::ExpressionEvaluationContextRecord &Rec) {
16584   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16585        Rec.ReferenceToConsteval.size() == 0) ||
16586       SemaRef.RebuildingImmediateInvocation)
16587     return;
16588 
16589   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16590   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16591   /// need to remove ReferenceToConsteval in the immediate invocation.
16592   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16593 
16594     /// Prevent sema calls during the tree transform from adding pointers that
16595     /// are already in the sets.
16596     llvm::SaveAndRestore<bool> DisableIITracking(
16597         SemaRef.RebuildingImmediateInvocation, true);
16598 
16599     /// Prevent diagnostic during tree transfrom as they are duplicates
16600     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16601 
16602     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16603          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16604       if (!It->getInt())
16605         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16606   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16607              Rec.ReferenceToConsteval.size()) {
16608     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16609       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16610       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16611       bool VisitDeclRefExpr(DeclRefExpr *E) {
16612         DRSet.erase(E);
16613         return DRSet.size();
16614       }
16615     } Visitor(Rec.ReferenceToConsteval);
16616     Visitor.TraverseStmt(
16617         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16618   }
16619   for (auto CE : Rec.ImmediateInvocationCandidates)
16620     if (!CE.getInt())
16621       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16622   for (auto DR : Rec.ReferenceToConsteval) {
16623     auto *FD = cast<FunctionDecl>(DR->getDecl());
16624     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16625         << FD;
16626     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16627   }
16628 }
16629 
16630 void Sema::PopExpressionEvaluationContext() {
16631   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16632   unsigned NumTypos = Rec.NumTypos;
16633 
16634   if (!Rec.Lambdas.empty()) {
16635     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16636     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16637         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16638       unsigned D;
16639       if (Rec.isUnevaluated()) {
16640         // C++11 [expr.prim.lambda]p2:
16641         //   A lambda-expression shall not appear in an unevaluated operand
16642         //   (Clause 5).
16643         D = diag::err_lambda_unevaluated_operand;
16644       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16645         // C++1y [expr.const]p2:
16646         //   A conditional-expression e is a core constant expression unless the
16647         //   evaluation of e, following the rules of the abstract machine, would
16648         //   evaluate [...] a lambda-expression.
16649         D = diag::err_lambda_in_constant_expression;
16650       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16651         // C++17 [expr.prim.lamda]p2:
16652         // A lambda-expression shall not appear [...] in a template-argument.
16653         D = diag::err_lambda_in_invalid_context;
16654       } else
16655         llvm_unreachable("Couldn't infer lambda error message.");
16656 
16657       for (const auto *L : Rec.Lambdas)
16658         Diag(L->getBeginLoc(), D);
16659     }
16660   }
16661 
16662   WarnOnPendingNoDerefs(Rec);
16663   HandleImmediateInvocations(*this, Rec);
16664 
16665   // Warn on any volatile-qualified simple-assignments that are not discarded-
16666   // value expressions nor unevaluated operands (those cases get removed from
16667   // this list by CheckUnusedVolatileAssignment).
16668   for (auto *BO : Rec.VolatileAssignmentLHSs)
16669     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16670         << BO->getType();
16671 
16672   // When are coming out of an unevaluated context, clear out any
16673   // temporaries that we may have created as part of the evaluation of
16674   // the expression in that context: they aren't relevant because they
16675   // will never be constructed.
16676   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16677     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16678                              ExprCleanupObjects.end());
16679     Cleanup = Rec.ParentCleanup;
16680     CleanupVarDeclMarking();
16681     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16682   // Otherwise, merge the contexts together.
16683   } else {
16684     Cleanup.mergeFrom(Rec.ParentCleanup);
16685     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16686                             Rec.SavedMaybeODRUseExprs.end());
16687   }
16688 
16689   // Pop the current expression evaluation context off the stack.
16690   ExprEvalContexts.pop_back();
16691 
16692   // The global expression evaluation context record is never popped.
16693   ExprEvalContexts.back().NumTypos += NumTypos;
16694 }
16695 
16696 void Sema::DiscardCleanupsInEvaluationContext() {
16697   ExprCleanupObjects.erase(
16698          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16699          ExprCleanupObjects.end());
16700   Cleanup.reset();
16701   MaybeODRUseExprs.clear();
16702 }
16703 
16704 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16705   ExprResult Result = CheckPlaceholderExpr(E);
16706   if (Result.isInvalid())
16707     return ExprError();
16708   E = Result.get();
16709   if (!E->getType()->isVariablyModifiedType())
16710     return E;
16711   return TransformToPotentiallyEvaluated(E);
16712 }
16713 
16714 /// Are we in a context that is potentially constant evaluated per C++20
16715 /// [expr.const]p12?
16716 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16717   /// C++2a [expr.const]p12:
16718   //   An expression or conversion is potentially constant evaluated if it is
16719   switch (SemaRef.ExprEvalContexts.back().Context) {
16720     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16721       // -- a manifestly constant-evaluated expression,
16722     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16723     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16724     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16725       // -- a potentially-evaluated expression,
16726     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16727       // -- an immediate subexpression of a braced-init-list,
16728 
16729       // -- [FIXME] an expression of the form & cast-expression that occurs
16730       //    within a templated entity
16731       // -- a subexpression of one of the above that is not a subexpression of
16732       // a nested unevaluated operand.
16733       return true;
16734 
16735     case Sema::ExpressionEvaluationContext::Unevaluated:
16736     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16737       // Expressions in this context are never evaluated.
16738       return false;
16739   }
16740   llvm_unreachable("Invalid context");
16741 }
16742 
16743 /// Return true if this function has a calling convention that requires mangling
16744 /// in the size of the parameter pack.
16745 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16746   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16747   // we don't need parameter type sizes.
16748   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16749   if (!TT.isOSWindows() || !TT.isX86())
16750     return false;
16751 
16752   // If this is C++ and this isn't an extern "C" function, parameters do not
16753   // need to be complete. In this case, C++ mangling will apply, which doesn't
16754   // use the size of the parameters.
16755   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16756     return false;
16757 
16758   // Stdcall, fastcall, and vectorcall need this special treatment.
16759   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16760   switch (CC) {
16761   case CC_X86StdCall:
16762   case CC_X86FastCall:
16763   case CC_X86VectorCall:
16764     return true;
16765   default:
16766     break;
16767   }
16768   return false;
16769 }
16770 
16771 /// Require that all of the parameter types of function be complete. Normally,
16772 /// parameter types are only required to be complete when a function is called
16773 /// or defined, but to mangle functions with certain calling conventions, the
16774 /// mangler needs to know the size of the parameter list. In this situation,
16775 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16776 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16777 /// result in a linker error. Clang doesn't implement this behavior, and instead
16778 /// attempts to error at compile time.
16779 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16780                                                   SourceLocation Loc) {
16781   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16782     FunctionDecl *FD;
16783     ParmVarDecl *Param;
16784 
16785   public:
16786     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16787         : FD(FD), Param(Param) {}
16788 
16789     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16790       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16791       StringRef CCName;
16792       switch (CC) {
16793       case CC_X86StdCall:
16794         CCName = "stdcall";
16795         break;
16796       case CC_X86FastCall:
16797         CCName = "fastcall";
16798         break;
16799       case CC_X86VectorCall:
16800         CCName = "vectorcall";
16801         break;
16802       default:
16803         llvm_unreachable("CC does not need mangling");
16804       }
16805 
16806       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16807           << Param->getDeclName() << FD->getDeclName() << CCName;
16808     }
16809   };
16810 
16811   for (ParmVarDecl *Param : FD->parameters()) {
16812     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16813     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16814   }
16815 }
16816 
16817 namespace {
16818 enum class OdrUseContext {
16819   /// Declarations in this context are not odr-used.
16820   None,
16821   /// Declarations in this context are formally odr-used, but this is a
16822   /// dependent context.
16823   Dependent,
16824   /// Declarations in this context are odr-used but not actually used (yet).
16825   FormallyOdrUsed,
16826   /// Declarations in this context are used.
16827   Used
16828 };
16829 }
16830 
16831 /// Are we within a context in which references to resolved functions or to
16832 /// variables result in odr-use?
16833 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16834   OdrUseContext Result;
16835 
16836   switch (SemaRef.ExprEvalContexts.back().Context) {
16837     case Sema::ExpressionEvaluationContext::Unevaluated:
16838     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16839     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16840       return OdrUseContext::None;
16841 
16842     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16843     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16844       Result = OdrUseContext::Used;
16845       break;
16846 
16847     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16848       Result = OdrUseContext::FormallyOdrUsed;
16849       break;
16850 
16851     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16852       // A default argument formally results in odr-use, but doesn't actually
16853       // result in a use in any real sense until it itself is used.
16854       Result = OdrUseContext::FormallyOdrUsed;
16855       break;
16856   }
16857 
16858   if (SemaRef.CurContext->isDependentContext())
16859     return OdrUseContext::Dependent;
16860 
16861   return Result;
16862 }
16863 
16864 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16865   if (!Func->isConstexpr())
16866     return false;
16867 
16868   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16869     return true;
16870   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16871   return CCD && CCD->getInheritedConstructor();
16872 }
16873 
16874 /// Mark a function referenced, and check whether it is odr-used
16875 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16876 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16877                                   bool MightBeOdrUse) {
16878   assert(Func && "No function?");
16879 
16880   Func->setReferenced();
16881 
16882   // Recursive functions aren't really used until they're used from some other
16883   // context.
16884   bool IsRecursiveCall = CurContext == Func;
16885 
16886   // C++11 [basic.def.odr]p3:
16887   //   A function whose name appears as a potentially-evaluated expression is
16888   //   odr-used if it is the unique lookup result or the selected member of a
16889   //   set of overloaded functions [...].
16890   //
16891   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16892   // can just check that here.
16893   OdrUseContext OdrUse =
16894       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16895   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16896     OdrUse = OdrUseContext::FormallyOdrUsed;
16897 
16898   // Trivial default constructors and destructors are never actually used.
16899   // FIXME: What about other special members?
16900   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16901       OdrUse == OdrUseContext::Used) {
16902     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16903       if (Constructor->isDefaultConstructor())
16904         OdrUse = OdrUseContext::FormallyOdrUsed;
16905     if (isa<CXXDestructorDecl>(Func))
16906       OdrUse = OdrUseContext::FormallyOdrUsed;
16907   }
16908 
16909   // C++20 [expr.const]p12:
16910   //   A function [...] is needed for constant evaluation if it is [...] a
16911   //   constexpr function that is named by an expression that is potentially
16912   //   constant evaluated
16913   bool NeededForConstantEvaluation =
16914       isPotentiallyConstantEvaluatedContext(*this) &&
16915       isImplicitlyDefinableConstexprFunction(Func);
16916 
16917   // Determine whether we require a function definition to exist, per
16918   // C++11 [temp.inst]p3:
16919   //   Unless a function template specialization has been explicitly
16920   //   instantiated or explicitly specialized, the function template
16921   //   specialization is implicitly instantiated when the specialization is
16922   //   referenced in a context that requires a function definition to exist.
16923   // C++20 [temp.inst]p7:
16924   //   The existence of a definition of a [...] function is considered to
16925   //   affect the semantics of the program if the [...] function is needed for
16926   //   constant evaluation by an expression
16927   // C++20 [basic.def.odr]p10:
16928   //   Every program shall contain exactly one definition of every non-inline
16929   //   function or variable that is odr-used in that program outside of a
16930   //   discarded statement
16931   // C++20 [special]p1:
16932   //   The implementation will implicitly define [defaulted special members]
16933   //   if they are odr-used or needed for constant evaluation.
16934   //
16935   // Note that we skip the implicit instantiation of templates that are only
16936   // used in unused default arguments or by recursive calls to themselves.
16937   // This is formally non-conforming, but seems reasonable in practice.
16938   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16939                                              NeededForConstantEvaluation);
16940 
16941   // C++14 [temp.expl.spec]p6:
16942   //   If a template [...] is explicitly specialized then that specialization
16943   //   shall be declared before the first use of that specialization that would
16944   //   cause an implicit instantiation to take place, in every translation unit
16945   //   in which such a use occurs
16946   if (NeedDefinition &&
16947       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16948        Func->getMemberSpecializationInfo()))
16949     checkSpecializationVisibility(Loc, Func);
16950 
16951   if (getLangOpts().CUDA)
16952     CheckCUDACall(Loc, Func);
16953 
16954   if (getLangOpts().SYCLIsDevice)
16955     checkSYCLDeviceFunction(Loc, Func);
16956 
16957   // If we need a definition, try to create one.
16958   if (NeedDefinition && !Func->getBody()) {
16959     runWithSufficientStackSpace(Loc, [&] {
16960       if (CXXConstructorDecl *Constructor =
16961               dyn_cast<CXXConstructorDecl>(Func)) {
16962         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16963         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16964           if (Constructor->isDefaultConstructor()) {
16965             if (Constructor->isTrivial() &&
16966                 !Constructor->hasAttr<DLLExportAttr>())
16967               return;
16968             DefineImplicitDefaultConstructor(Loc, Constructor);
16969           } else if (Constructor->isCopyConstructor()) {
16970             DefineImplicitCopyConstructor(Loc, Constructor);
16971           } else if (Constructor->isMoveConstructor()) {
16972             DefineImplicitMoveConstructor(Loc, Constructor);
16973           }
16974         } else if (Constructor->getInheritedConstructor()) {
16975           DefineInheritingConstructor(Loc, Constructor);
16976         }
16977       } else if (CXXDestructorDecl *Destructor =
16978                      dyn_cast<CXXDestructorDecl>(Func)) {
16979         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16980         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16981           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16982             return;
16983           DefineImplicitDestructor(Loc, Destructor);
16984         }
16985         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16986           MarkVTableUsed(Loc, Destructor->getParent());
16987       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16988         if (MethodDecl->isOverloadedOperator() &&
16989             MethodDecl->getOverloadedOperator() == OO_Equal) {
16990           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16991           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16992             if (MethodDecl->isCopyAssignmentOperator())
16993               DefineImplicitCopyAssignment(Loc, MethodDecl);
16994             else if (MethodDecl->isMoveAssignmentOperator())
16995               DefineImplicitMoveAssignment(Loc, MethodDecl);
16996           }
16997         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16998                    MethodDecl->getParent()->isLambda()) {
16999           CXXConversionDecl *Conversion =
17000               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17001           if (Conversion->isLambdaToBlockPointerConversion())
17002             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17003           else
17004             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17005         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17006           MarkVTableUsed(Loc, MethodDecl->getParent());
17007       }
17008 
17009       if (Func->isDefaulted() && !Func->isDeleted()) {
17010         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17011         if (DCK != DefaultedComparisonKind::None)
17012           DefineDefaultedComparison(Loc, Func, DCK);
17013       }
17014 
17015       // Implicit instantiation of function templates and member functions of
17016       // class templates.
17017       if (Func->isImplicitlyInstantiable()) {
17018         TemplateSpecializationKind TSK =
17019             Func->getTemplateSpecializationKindForInstantiation();
17020         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17021         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17022         if (FirstInstantiation) {
17023           PointOfInstantiation = Loc;
17024           if (auto *MSI = Func->getMemberSpecializationInfo())
17025             MSI->setPointOfInstantiation(Loc);
17026             // FIXME: Notify listener.
17027           else
17028             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17029         } else if (TSK != TSK_ImplicitInstantiation) {
17030           // Use the point of use as the point of instantiation, instead of the
17031           // point of explicit instantiation (which we track as the actual point
17032           // of instantiation). This gives better backtraces in diagnostics.
17033           PointOfInstantiation = Loc;
17034         }
17035 
17036         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17037             Func->isConstexpr()) {
17038           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17039               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17040               CodeSynthesisContexts.size())
17041             PendingLocalImplicitInstantiations.push_back(
17042                 std::make_pair(Func, PointOfInstantiation));
17043           else if (Func->isConstexpr())
17044             // Do not defer instantiations of constexpr functions, to avoid the
17045             // expression evaluator needing to call back into Sema if it sees a
17046             // call to such a function.
17047             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17048           else {
17049             Func->setInstantiationIsPending(true);
17050             PendingInstantiations.push_back(
17051                 std::make_pair(Func, PointOfInstantiation));
17052             // Notify the consumer that a function was implicitly instantiated.
17053             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17054           }
17055         }
17056       } else {
17057         // Walk redefinitions, as some of them may be instantiable.
17058         for (auto i : Func->redecls()) {
17059           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17060             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17061         }
17062       }
17063     });
17064   }
17065 
17066   // C++14 [except.spec]p17:
17067   //   An exception-specification is considered to be needed when:
17068   //   - the function is odr-used or, if it appears in an unevaluated operand,
17069   //     would be odr-used if the expression were potentially-evaluated;
17070   //
17071   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17072   // function is a pure virtual function we're calling, and in that case the
17073   // function was selected by overload resolution and we need to resolve its
17074   // exception specification for a different reason.
17075   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17076   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17077     ResolveExceptionSpec(Loc, FPT);
17078 
17079   // If this is the first "real" use, act on that.
17080   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17081     // Keep track of used but undefined functions.
17082     if (!Func->isDefined()) {
17083       if (mightHaveNonExternalLinkage(Func))
17084         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17085       else if (Func->getMostRecentDecl()->isInlined() &&
17086                !LangOpts.GNUInline &&
17087                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17088         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17089       else if (isExternalWithNoLinkageType(Func))
17090         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17091     }
17092 
17093     // Some x86 Windows calling conventions mangle the size of the parameter
17094     // pack into the name. Computing the size of the parameters requires the
17095     // parameter types to be complete. Check that now.
17096     if (funcHasParameterSizeMangling(*this, Func))
17097       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17098 
17099     // In the MS C++ ABI, the compiler emits destructor variants where they are
17100     // used. If the destructor is used here but defined elsewhere, mark the
17101     // virtual base destructors referenced. If those virtual base destructors
17102     // are inline, this will ensure they are defined when emitting the complete
17103     // destructor variant. This checking may be redundant if the destructor is
17104     // provided later in this TU.
17105     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17106       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17107         CXXRecordDecl *Parent = Dtor->getParent();
17108         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17109           CheckCompleteDestructorVariant(Loc, Dtor);
17110       }
17111     }
17112 
17113     Func->markUsed(Context);
17114   }
17115 }
17116 
17117 /// Directly mark a variable odr-used. Given a choice, prefer to use
17118 /// MarkVariableReferenced since it does additional checks and then
17119 /// calls MarkVarDeclODRUsed.
17120 /// If the variable must be captured:
17121 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17122 ///  - else capture it in the DeclContext that maps to the
17123 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17124 static void
17125 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17126                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17127   // Keep track of used but undefined variables.
17128   // FIXME: We shouldn't suppress this warning for static data members.
17129   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17130       (!Var->isExternallyVisible() || Var->isInline() ||
17131        SemaRef.isExternalWithNoLinkageType(Var)) &&
17132       !(Var->isStaticDataMember() && Var->hasInit())) {
17133     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17134     if (old.isInvalid())
17135       old = Loc;
17136   }
17137   QualType CaptureType, DeclRefType;
17138   if (SemaRef.LangOpts.OpenMP)
17139     SemaRef.tryCaptureOpenMPLambdas(Var);
17140   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17141     /*EllipsisLoc*/ SourceLocation(),
17142     /*BuildAndDiagnose*/ true,
17143     CaptureType, DeclRefType,
17144     FunctionScopeIndexToStopAt);
17145 
17146   Var->markUsed(SemaRef.Context);
17147 }
17148 
17149 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17150                                              SourceLocation Loc,
17151                                              unsigned CapturingScopeIndex) {
17152   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17153 }
17154 
17155 static void
17156 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17157                                    ValueDecl *var, DeclContext *DC) {
17158   DeclContext *VarDC = var->getDeclContext();
17159 
17160   //  If the parameter still belongs to the translation unit, then
17161   //  we're actually just using one parameter in the declaration of
17162   //  the next.
17163   if (isa<ParmVarDecl>(var) &&
17164       isa<TranslationUnitDecl>(VarDC))
17165     return;
17166 
17167   // For C code, don't diagnose about capture if we're not actually in code
17168   // right now; it's impossible to write a non-constant expression outside of
17169   // function context, so we'll get other (more useful) diagnostics later.
17170   //
17171   // For C++, things get a bit more nasty... it would be nice to suppress this
17172   // diagnostic for certain cases like using a local variable in an array bound
17173   // for a member of a local class, but the correct predicate is not obvious.
17174   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17175     return;
17176 
17177   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17178   unsigned ContextKind = 3; // unknown
17179   if (isa<CXXMethodDecl>(VarDC) &&
17180       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17181     ContextKind = 2;
17182   } else if (isa<FunctionDecl>(VarDC)) {
17183     ContextKind = 0;
17184   } else if (isa<BlockDecl>(VarDC)) {
17185     ContextKind = 1;
17186   }
17187 
17188   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17189     << var << ValueKind << ContextKind << VarDC;
17190   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17191       << var;
17192 
17193   // FIXME: Add additional diagnostic info about class etc. which prevents
17194   // capture.
17195 }
17196 
17197 
17198 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17199                                       bool &SubCapturesAreNested,
17200                                       QualType &CaptureType,
17201                                       QualType &DeclRefType) {
17202    // Check whether we've already captured it.
17203   if (CSI->CaptureMap.count(Var)) {
17204     // If we found a capture, any subcaptures are nested.
17205     SubCapturesAreNested = true;
17206 
17207     // Retrieve the capture type for this variable.
17208     CaptureType = CSI->getCapture(Var).getCaptureType();
17209 
17210     // Compute the type of an expression that refers to this variable.
17211     DeclRefType = CaptureType.getNonReferenceType();
17212 
17213     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17214     // are mutable in the sense that user can change their value - they are
17215     // private instances of the captured declarations.
17216     const Capture &Cap = CSI->getCapture(Var);
17217     if (Cap.isCopyCapture() &&
17218         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17219         !(isa<CapturedRegionScopeInfo>(CSI) &&
17220           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17221       DeclRefType.addConst();
17222     return true;
17223   }
17224   return false;
17225 }
17226 
17227 // Only block literals, captured statements, and lambda expressions can
17228 // capture; other scopes don't work.
17229 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17230                                  SourceLocation Loc,
17231                                  const bool Diagnose, Sema &S) {
17232   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17233     return getLambdaAwareParentOfDeclContext(DC);
17234   else if (Var->hasLocalStorage()) {
17235     if (Diagnose)
17236        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17237   }
17238   return nullptr;
17239 }
17240 
17241 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17242 // certain types of variables (unnamed, variably modified types etc.)
17243 // so check for eligibility.
17244 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17245                                  SourceLocation Loc,
17246                                  const bool Diagnose, Sema &S) {
17247 
17248   bool IsBlock = isa<BlockScopeInfo>(CSI);
17249   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17250 
17251   // Lambdas are not allowed to capture unnamed variables
17252   // (e.g. anonymous unions).
17253   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17254   // assuming that's the intent.
17255   if (IsLambda && !Var->getDeclName()) {
17256     if (Diagnose) {
17257       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17258       S.Diag(Var->getLocation(), diag::note_declared_at);
17259     }
17260     return false;
17261   }
17262 
17263   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17264   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17265     if (Diagnose) {
17266       S.Diag(Loc, diag::err_ref_vm_type);
17267       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17268     }
17269     return false;
17270   }
17271   // Prohibit structs with flexible array members too.
17272   // We cannot capture what is in the tail end of the struct.
17273   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17274     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17275       if (Diagnose) {
17276         if (IsBlock)
17277           S.Diag(Loc, diag::err_ref_flexarray_type);
17278         else
17279           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17280         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17281       }
17282       return false;
17283     }
17284   }
17285   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17286   // Lambdas and captured statements are not allowed to capture __block
17287   // variables; they don't support the expected semantics.
17288   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17289     if (Diagnose) {
17290       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17291       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17292     }
17293     return false;
17294   }
17295   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17296   if (S.getLangOpts().OpenCL && IsBlock &&
17297       Var->getType()->isBlockPointerType()) {
17298     if (Diagnose)
17299       S.Diag(Loc, diag::err_opencl_block_ref_block);
17300     return false;
17301   }
17302 
17303   return true;
17304 }
17305 
17306 // Returns true if the capture by block was successful.
17307 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17308                                  SourceLocation Loc,
17309                                  const bool BuildAndDiagnose,
17310                                  QualType &CaptureType,
17311                                  QualType &DeclRefType,
17312                                  const bool Nested,
17313                                  Sema &S, bool Invalid) {
17314   bool ByRef = false;
17315 
17316   // Blocks are not allowed to capture arrays, excepting OpenCL.
17317   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17318   // (decayed to pointers).
17319   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17320     if (BuildAndDiagnose) {
17321       S.Diag(Loc, diag::err_ref_array_type);
17322       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17323       Invalid = true;
17324     } else {
17325       return false;
17326     }
17327   }
17328 
17329   // Forbid the block-capture of autoreleasing variables.
17330   if (!Invalid &&
17331       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17332     if (BuildAndDiagnose) {
17333       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17334         << /*block*/ 0;
17335       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17336       Invalid = true;
17337     } else {
17338       return false;
17339     }
17340   }
17341 
17342   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17343   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17344     QualType PointeeTy = PT->getPointeeType();
17345 
17346     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17347         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17348         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17349       if (BuildAndDiagnose) {
17350         SourceLocation VarLoc = Var->getLocation();
17351         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17352         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17353       }
17354     }
17355   }
17356 
17357   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17358   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17359       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17360     // Block capture by reference does not change the capture or
17361     // declaration reference types.
17362     ByRef = true;
17363   } else {
17364     // Block capture by copy introduces 'const'.
17365     CaptureType = CaptureType.getNonReferenceType().withConst();
17366     DeclRefType = CaptureType;
17367   }
17368 
17369   // Actually capture the variable.
17370   if (BuildAndDiagnose)
17371     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17372                     CaptureType, Invalid);
17373 
17374   return !Invalid;
17375 }
17376 
17377 
17378 /// Capture the given variable in the captured region.
17379 static bool captureInCapturedRegion(
17380     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17381     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17382     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17383     bool IsTopScope, Sema &S, bool Invalid) {
17384   // By default, capture variables by reference.
17385   bool ByRef = true;
17386   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17387     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17388   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17389     // Using an LValue reference type is consistent with Lambdas (see below).
17390     if (S.isOpenMPCapturedDecl(Var)) {
17391       bool HasConst = DeclRefType.isConstQualified();
17392       DeclRefType = DeclRefType.getUnqualifiedType();
17393       // Don't lose diagnostics about assignments to const.
17394       if (HasConst)
17395         DeclRefType.addConst();
17396     }
17397     // Do not capture firstprivates in tasks.
17398     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17399         OMPC_unknown)
17400       return true;
17401     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17402                                     RSI->OpenMPCaptureLevel);
17403   }
17404 
17405   if (ByRef)
17406     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17407   else
17408     CaptureType = DeclRefType;
17409 
17410   // Actually capture the variable.
17411   if (BuildAndDiagnose)
17412     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17413                     Loc, SourceLocation(), CaptureType, Invalid);
17414 
17415   return !Invalid;
17416 }
17417 
17418 /// Capture the given variable in the lambda.
17419 static bool captureInLambda(LambdaScopeInfo *LSI,
17420                             VarDecl *Var,
17421                             SourceLocation Loc,
17422                             const bool BuildAndDiagnose,
17423                             QualType &CaptureType,
17424                             QualType &DeclRefType,
17425                             const bool RefersToCapturedVariable,
17426                             const Sema::TryCaptureKind Kind,
17427                             SourceLocation EllipsisLoc,
17428                             const bool IsTopScope,
17429                             Sema &S, bool Invalid) {
17430   // Determine whether we are capturing by reference or by value.
17431   bool ByRef = false;
17432   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17433     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17434   } else {
17435     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17436   }
17437 
17438   // Compute the type of the field that will capture this variable.
17439   if (ByRef) {
17440     // C++11 [expr.prim.lambda]p15:
17441     //   An entity is captured by reference if it is implicitly or
17442     //   explicitly captured but not captured by copy. It is
17443     //   unspecified whether additional unnamed non-static data
17444     //   members are declared in the closure type for entities
17445     //   captured by reference.
17446     //
17447     // FIXME: It is not clear whether we want to build an lvalue reference
17448     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17449     // to do the former, while EDG does the latter. Core issue 1249 will
17450     // clarify, but for now we follow GCC because it's a more permissive and
17451     // easily defensible position.
17452     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17453   } else {
17454     // C++11 [expr.prim.lambda]p14:
17455     //   For each entity captured by copy, an unnamed non-static
17456     //   data member is declared in the closure type. The
17457     //   declaration order of these members is unspecified. The type
17458     //   of such a data member is the type of the corresponding
17459     //   captured entity if the entity is not a reference to an
17460     //   object, or the referenced type otherwise. [Note: If the
17461     //   captured entity is a reference to a function, the
17462     //   corresponding data member is also a reference to a
17463     //   function. - end note ]
17464     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17465       if (!RefType->getPointeeType()->isFunctionType())
17466         CaptureType = RefType->getPointeeType();
17467     }
17468 
17469     // Forbid the lambda copy-capture of autoreleasing variables.
17470     if (!Invalid &&
17471         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17472       if (BuildAndDiagnose) {
17473         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17474         S.Diag(Var->getLocation(), diag::note_previous_decl)
17475           << Var->getDeclName();
17476         Invalid = true;
17477       } else {
17478         return false;
17479       }
17480     }
17481 
17482     // Make sure that by-copy captures are of a complete and non-abstract type.
17483     if (!Invalid && BuildAndDiagnose) {
17484       if (!CaptureType->isDependentType() &&
17485           S.RequireCompleteSizedType(
17486               Loc, CaptureType,
17487               diag::err_capture_of_incomplete_or_sizeless_type,
17488               Var->getDeclName()))
17489         Invalid = true;
17490       else if (S.RequireNonAbstractType(Loc, CaptureType,
17491                                         diag::err_capture_of_abstract_type))
17492         Invalid = true;
17493     }
17494   }
17495 
17496   // Compute the type of a reference to this captured variable.
17497   if (ByRef)
17498     DeclRefType = CaptureType.getNonReferenceType();
17499   else {
17500     // C++ [expr.prim.lambda]p5:
17501     //   The closure type for a lambda-expression has a public inline
17502     //   function call operator [...]. This function call operator is
17503     //   declared const (9.3.1) if and only if the lambda-expression's
17504     //   parameter-declaration-clause is not followed by mutable.
17505     DeclRefType = CaptureType.getNonReferenceType();
17506     if (!LSI->Mutable && !CaptureType->isReferenceType())
17507       DeclRefType.addConst();
17508   }
17509 
17510   // Add the capture.
17511   if (BuildAndDiagnose)
17512     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17513                     Loc, EllipsisLoc, CaptureType, Invalid);
17514 
17515   return !Invalid;
17516 }
17517 
17518 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17519   // Offer a Copy fix even if the type is dependent.
17520   if (Var->getType()->isDependentType())
17521     return true;
17522   QualType T = Var->getType().getNonReferenceType();
17523   if (T.isTriviallyCopyableType(Context))
17524     return true;
17525   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17526 
17527     if (!(RD = RD->getDefinition()))
17528       return false;
17529     if (RD->hasSimpleCopyConstructor())
17530       return true;
17531     if (RD->hasUserDeclaredCopyConstructor())
17532       for (CXXConstructorDecl *Ctor : RD->ctors())
17533         if (Ctor->isCopyConstructor())
17534           return !Ctor->isDeleted();
17535   }
17536   return false;
17537 }
17538 
17539 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17540 /// default capture. Fixes may be omitted if they aren't allowed by the
17541 /// standard, for example we can't emit a default copy capture fix-it if we
17542 /// already explicitly copy capture capture another variable.
17543 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17544                                     VarDecl *Var) {
17545   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17546   // Don't offer Capture by copy of default capture by copy fixes if Var is
17547   // known not to be copy constructible.
17548   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17549 
17550   SmallString<32> FixBuffer;
17551   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17552   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17553     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17554     if (ShouldOfferCopyFix) {
17555       // Offer fixes to insert an explicit capture for the variable.
17556       // [] -> [VarName]
17557       // [OtherCapture] -> [OtherCapture, VarName]
17558       FixBuffer.assign({Separator, Var->getName()});
17559       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17560           << Var << /*value*/ 0
17561           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17562     }
17563     // As above but capture by reference.
17564     FixBuffer.assign({Separator, "&", Var->getName()});
17565     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17566         << Var << /*reference*/ 1
17567         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17568   }
17569 
17570   // Only try to offer default capture if there are no captures excluding this
17571   // and init captures.
17572   // [this]: OK.
17573   // [X = Y]: OK.
17574   // [&A, &B]: Don't offer.
17575   // [A, B]: Don't offer.
17576   if (llvm::any_of(LSI->Captures, [](Capture &C) {
17577         return !C.isThisCapture() && !C.isInitCapture();
17578       }))
17579     return;
17580 
17581   // The default capture specifiers, '=' or '&', must appear first in the
17582   // capture body.
17583   SourceLocation DefaultInsertLoc =
17584       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17585 
17586   if (ShouldOfferCopyFix) {
17587     bool CanDefaultCopyCapture = true;
17588     // [=, *this] OK since c++17
17589     // [=, this] OK since c++20
17590     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17591       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17592                                   ? LSI->getCXXThisCapture().isCopyCapture()
17593                                   : false;
17594     // We can't use default capture by copy if any captures already specified
17595     // capture by copy.
17596     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17597           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17598         })) {
17599       FixBuffer.assign({"=", Separator});
17600       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17601           << /*value*/ 0
17602           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17603     }
17604   }
17605 
17606   // We can't use default capture by reference if any captures already specified
17607   // capture by reference.
17608   if (llvm::none_of(LSI->Captures, [](Capture &C) {
17609         return !C.isInitCapture() && C.isReferenceCapture() &&
17610                !C.isThisCapture();
17611       })) {
17612     FixBuffer.assign({"&", Separator});
17613     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17614         << /*reference*/ 1
17615         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17616   }
17617 }
17618 
17619 bool Sema::tryCaptureVariable(
17620     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17621     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17622     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17623   // An init-capture is notionally from the context surrounding its
17624   // declaration, but its parent DC is the lambda class.
17625   DeclContext *VarDC = Var->getDeclContext();
17626   if (Var->isInitCapture())
17627     VarDC = VarDC->getParent();
17628 
17629   DeclContext *DC = CurContext;
17630   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17631       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17632   // We need to sync up the Declaration Context with the
17633   // FunctionScopeIndexToStopAt
17634   if (FunctionScopeIndexToStopAt) {
17635     unsigned FSIndex = FunctionScopes.size() - 1;
17636     while (FSIndex != MaxFunctionScopesIndex) {
17637       DC = getLambdaAwareParentOfDeclContext(DC);
17638       --FSIndex;
17639     }
17640   }
17641 
17642 
17643   // If the variable is declared in the current context, there is no need to
17644   // capture it.
17645   if (VarDC == DC) return true;
17646 
17647   // Capture global variables if it is required to use private copy of this
17648   // variable.
17649   bool IsGlobal = !Var->hasLocalStorage();
17650   if (IsGlobal &&
17651       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17652                                                 MaxFunctionScopesIndex)))
17653     return true;
17654   Var = Var->getCanonicalDecl();
17655 
17656   // Walk up the stack to determine whether we can capture the variable,
17657   // performing the "simple" checks that don't depend on type. We stop when
17658   // we've either hit the declared scope of the variable or find an existing
17659   // capture of that variable.  We start from the innermost capturing-entity
17660   // (the DC) and ensure that all intervening capturing-entities
17661   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17662   // declcontext can either capture the variable or have already captured
17663   // the variable.
17664   CaptureType = Var->getType();
17665   DeclRefType = CaptureType.getNonReferenceType();
17666   bool Nested = false;
17667   bool Explicit = (Kind != TryCapture_Implicit);
17668   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17669   do {
17670     // Only block literals, captured statements, and lambda expressions can
17671     // capture; other scopes don't work.
17672     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17673                                                               ExprLoc,
17674                                                               BuildAndDiagnose,
17675                                                               *this);
17676     // We need to check for the parent *first* because, if we *have*
17677     // private-captured a global variable, we need to recursively capture it in
17678     // intermediate blocks, lambdas, etc.
17679     if (!ParentDC) {
17680       if (IsGlobal) {
17681         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17682         break;
17683       }
17684       return true;
17685     }
17686 
17687     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17688     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17689 
17690 
17691     // Check whether we've already captured it.
17692     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17693                                              DeclRefType)) {
17694       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17695       break;
17696     }
17697     // If we are instantiating a generic lambda call operator body,
17698     // we do not want to capture new variables.  What was captured
17699     // during either a lambdas transformation or initial parsing
17700     // should be used.
17701     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17702       if (BuildAndDiagnose) {
17703         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17704         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17705           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17706           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17707           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17708           buildLambdaCaptureFixit(*this, LSI, Var);
17709         } else
17710           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17711       }
17712       return true;
17713     }
17714 
17715     // Try to capture variable-length arrays types.
17716     if (Var->getType()->isVariablyModifiedType()) {
17717       // We're going to walk down into the type and look for VLA
17718       // expressions.
17719       QualType QTy = Var->getType();
17720       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17721         QTy = PVD->getOriginalType();
17722       captureVariablyModifiedType(Context, QTy, CSI);
17723     }
17724 
17725     if (getLangOpts().OpenMP) {
17726       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17727         // OpenMP private variables should not be captured in outer scope, so
17728         // just break here. Similarly, global variables that are captured in a
17729         // target region should not be captured outside the scope of the region.
17730         if (RSI->CapRegionKind == CR_OpenMP) {
17731           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17732               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17733           // If the variable is private (i.e. not captured) and has variably
17734           // modified type, we still need to capture the type for correct
17735           // codegen in all regions, associated with the construct. Currently,
17736           // it is captured in the innermost captured region only.
17737           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17738               Var->getType()->isVariablyModifiedType()) {
17739             QualType QTy = Var->getType();
17740             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17741               QTy = PVD->getOriginalType();
17742             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17743                  I < E; ++I) {
17744               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17745                   FunctionScopes[FunctionScopesIndex - I]);
17746               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17747                      "Wrong number of captured regions associated with the "
17748                      "OpenMP construct.");
17749               captureVariablyModifiedType(Context, QTy, OuterRSI);
17750             }
17751           }
17752           bool IsTargetCap =
17753               IsOpenMPPrivateDecl != OMPC_private &&
17754               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17755                                          RSI->OpenMPCaptureLevel);
17756           // Do not capture global if it is not privatized in outer regions.
17757           bool IsGlobalCap =
17758               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17759                                                      RSI->OpenMPCaptureLevel);
17760 
17761           // When we detect target captures we are looking from inside the
17762           // target region, therefore we need to propagate the capture from the
17763           // enclosing region. Therefore, the capture is not initially nested.
17764           if (IsTargetCap)
17765             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17766 
17767           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17768               (IsGlobal && !IsGlobalCap)) {
17769             Nested = !IsTargetCap;
17770             bool HasConst = DeclRefType.isConstQualified();
17771             DeclRefType = DeclRefType.getUnqualifiedType();
17772             // Don't lose diagnostics about assignments to const.
17773             if (HasConst)
17774               DeclRefType.addConst();
17775             CaptureType = Context.getLValueReferenceType(DeclRefType);
17776             break;
17777           }
17778         }
17779       }
17780     }
17781     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17782       // No capture-default, and this is not an explicit capture
17783       // so cannot capture this variable.
17784       if (BuildAndDiagnose) {
17785         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17786         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17787         auto *LSI = cast<LambdaScopeInfo>(CSI);
17788         if (LSI->Lambda) {
17789           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17790           buildLambdaCaptureFixit(*this, LSI, Var);
17791         }
17792         // FIXME: If we error out because an outer lambda can not implicitly
17793         // capture a variable that an inner lambda explicitly captures, we
17794         // should have the inner lambda do the explicit capture - because
17795         // it makes for cleaner diagnostics later.  This would purely be done
17796         // so that the diagnostic does not misleadingly claim that a variable
17797         // can not be captured by a lambda implicitly even though it is captured
17798         // explicitly.  Suggestion:
17799         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17800         //    at the function head
17801         //  - cache the StartingDeclContext - this must be a lambda
17802         //  - captureInLambda in the innermost lambda the variable.
17803       }
17804       return true;
17805     }
17806 
17807     FunctionScopesIndex--;
17808     DC = ParentDC;
17809     Explicit = false;
17810   } while (!VarDC->Equals(DC));
17811 
17812   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17813   // computing the type of the capture at each step, checking type-specific
17814   // requirements, and adding captures if requested.
17815   // If the variable had already been captured previously, we start capturing
17816   // at the lambda nested within that one.
17817   bool Invalid = false;
17818   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17819        ++I) {
17820     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17821 
17822     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17823     // certain types of variables (unnamed, variably modified types etc.)
17824     // so check for eligibility.
17825     if (!Invalid)
17826       Invalid =
17827           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17828 
17829     // After encountering an error, if we're actually supposed to capture, keep
17830     // capturing in nested contexts to suppress any follow-on diagnostics.
17831     if (Invalid && !BuildAndDiagnose)
17832       return true;
17833 
17834     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17835       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17836                                DeclRefType, Nested, *this, Invalid);
17837       Nested = true;
17838     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17839       Invalid = !captureInCapturedRegion(
17840           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
17841           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
17842       Nested = true;
17843     } else {
17844       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17845       Invalid =
17846           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17847                            DeclRefType, Nested, Kind, EllipsisLoc,
17848                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17849       Nested = true;
17850     }
17851 
17852     if (Invalid && !BuildAndDiagnose)
17853       return true;
17854   }
17855   return Invalid;
17856 }
17857 
17858 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17859                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17860   QualType CaptureType;
17861   QualType DeclRefType;
17862   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17863                             /*BuildAndDiagnose=*/true, CaptureType,
17864                             DeclRefType, nullptr);
17865 }
17866 
17867 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17868   QualType CaptureType;
17869   QualType DeclRefType;
17870   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17871                              /*BuildAndDiagnose=*/false, CaptureType,
17872                              DeclRefType, nullptr);
17873 }
17874 
17875 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17876   QualType CaptureType;
17877   QualType DeclRefType;
17878 
17879   // Determine whether we can capture this variable.
17880   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17881                          /*BuildAndDiagnose=*/false, CaptureType,
17882                          DeclRefType, nullptr))
17883     return QualType();
17884 
17885   return DeclRefType;
17886 }
17887 
17888 namespace {
17889 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17890 // The produced TemplateArgumentListInfo* points to data stored within this
17891 // object, so should only be used in contexts where the pointer will not be
17892 // used after the CopiedTemplateArgs object is destroyed.
17893 class CopiedTemplateArgs {
17894   bool HasArgs;
17895   TemplateArgumentListInfo TemplateArgStorage;
17896 public:
17897   template<typename RefExpr>
17898   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17899     if (HasArgs)
17900       E->copyTemplateArgumentsInto(TemplateArgStorage);
17901   }
17902   operator TemplateArgumentListInfo*()
17903 #ifdef __has_cpp_attribute
17904 #if __has_cpp_attribute(clang::lifetimebound)
17905   [[clang::lifetimebound]]
17906 #endif
17907 #endif
17908   {
17909     return HasArgs ? &TemplateArgStorage : nullptr;
17910   }
17911 };
17912 }
17913 
17914 /// Walk the set of potential results of an expression and mark them all as
17915 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17916 ///
17917 /// \return A new expression if we found any potential results, ExprEmpty() if
17918 ///         not, and ExprError() if we diagnosed an error.
17919 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17920                                                       NonOdrUseReason NOUR) {
17921   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17922   // an object that satisfies the requirements for appearing in a
17923   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17924   // is immediately applied."  This function handles the lvalue-to-rvalue
17925   // conversion part.
17926   //
17927   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17928   // transform it into the relevant kind of non-odr-use node and rebuild the
17929   // tree of nodes leading to it.
17930   //
17931   // This is a mini-TreeTransform that only transforms a restricted subset of
17932   // nodes (and only certain operands of them).
17933 
17934   // Rebuild a subexpression.
17935   auto Rebuild = [&](Expr *Sub) {
17936     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17937   };
17938 
17939   // Check whether a potential result satisfies the requirements of NOUR.
17940   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17941     // Any entity other than a VarDecl is always odr-used whenever it's named
17942     // in a potentially-evaluated expression.
17943     auto *VD = dyn_cast<VarDecl>(D);
17944     if (!VD)
17945       return true;
17946 
17947     // C++2a [basic.def.odr]p4:
17948     //   A variable x whose name appears as a potentially-evalauted expression
17949     //   e is odr-used by e unless
17950     //   -- x is a reference that is usable in constant expressions, or
17951     //   -- x is a variable of non-reference type that is usable in constant
17952     //      expressions and has no mutable subobjects, and e is an element of
17953     //      the set of potential results of an expression of
17954     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17955     //      conversion is applied, or
17956     //   -- x is a variable of non-reference type, and e is an element of the
17957     //      set of potential results of a discarded-value expression to which
17958     //      the lvalue-to-rvalue conversion is not applied
17959     //
17960     // We check the first bullet and the "potentially-evaluated" condition in
17961     // BuildDeclRefExpr. We check the type requirements in the second bullet
17962     // in CheckLValueToRValueConversionOperand below.
17963     switch (NOUR) {
17964     case NOUR_None:
17965     case NOUR_Unevaluated:
17966       llvm_unreachable("unexpected non-odr-use-reason");
17967 
17968     case NOUR_Constant:
17969       // Constant references were handled when they were built.
17970       if (VD->getType()->isReferenceType())
17971         return true;
17972       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17973         if (RD->hasMutableFields())
17974           return true;
17975       if (!VD->isUsableInConstantExpressions(S.Context))
17976         return true;
17977       break;
17978 
17979     case NOUR_Discarded:
17980       if (VD->getType()->isReferenceType())
17981         return true;
17982       break;
17983     }
17984     return false;
17985   };
17986 
17987   // Mark that this expression does not constitute an odr-use.
17988   auto MarkNotOdrUsed = [&] {
17989     S.MaybeODRUseExprs.remove(E);
17990     if (LambdaScopeInfo *LSI = S.getCurLambda())
17991       LSI->markVariableExprAsNonODRUsed(E);
17992   };
17993 
17994   // C++2a [basic.def.odr]p2:
17995   //   The set of potential results of an expression e is defined as follows:
17996   switch (E->getStmtClass()) {
17997   //   -- If e is an id-expression, ...
17998   case Expr::DeclRefExprClass: {
17999     auto *DRE = cast<DeclRefExpr>(E);
18000     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18001       break;
18002 
18003     // Rebuild as a non-odr-use DeclRefExpr.
18004     MarkNotOdrUsed();
18005     return DeclRefExpr::Create(
18006         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18007         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18008         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18009         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18010   }
18011 
18012   case Expr::FunctionParmPackExprClass: {
18013     auto *FPPE = cast<FunctionParmPackExpr>(E);
18014     // If any of the declarations in the pack is odr-used, then the expression
18015     // as a whole constitutes an odr-use.
18016     for (VarDecl *D : *FPPE)
18017       if (IsPotentialResultOdrUsed(D))
18018         return ExprEmpty();
18019 
18020     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18021     // nothing cares about whether we marked this as an odr-use, but it might
18022     // be useful for non-compiler tools.
18023     MarkNotOdrUsed();
18024     break;
18025   }
18026 
18027   //   -- If e is a subscripting operation with an array operand...
18028   case Expr::ArraySubscriptExprClass: {
18029     auto *ASE = cast<ArraySubscriptExpr>(E);
18030     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18031     if (!OldBase->getType()->isArrayType())
18032       break;
18033     ExprResult Base = Rebuild(OldBase);
18034     if (!Base.isUsable())
18035       return Base;
18036     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18037     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18038     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18039     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18040                                      ASE->getRBracketLoc());
18041   }
18042 
18043   case Expr::MemberExprClass: {
18044     auto *ME = cast<MemberExpr>(E);
18045     // -- If e is a class member access expression [...] naming a non-static
18046     //    data member...
18047     if (isa<FieldDecl>(ME->getMemberDecl())) {
18048       ExprResult Base = Rebuild(ME->getBase());
18049       if (!Base.isUsable())
18050         return Base;
18051       return MemberExpr::Create(
18052           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18053           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18054           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18055           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18056           ME->getObjectKind(), ME->isNonOdrUse());
18057     }
18058 
18059     if (ME->getMemberDecl()->isCXXInstanceMember())
18060       break;
18061 
18062     // -- If e is a class member access expression naming a static data member,
18063     //    ...
18064     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18065       break;
18066 
18067     // Rebuild as a non-odr-use MemberExpr.
18068     MarkNotOdrUsed();
18069     return MemberExpr::Create(
18070         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18071         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18072         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18073         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18074     return ExprEmpty();
18075   }
18076 
18077   case Expr::BinaryOperatorClass: {
18078     auto *BO = cast<BinaryOperator>(E);
18079     Expr *LHS = BO->getLHS();
18080     Expr *RHS = BO->getRHS();
18081     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18082     if (BO->getOpcode() == BO_PtrMemD) {
18083       ExprResult Sub = Rebuild(LHS);
18084       if (!Sub.isUsable())
18085         return Sub;
18086       LHS = Sub.get();
18087     //   -- If e is a comma expression, ...
18088     } else if (BO->getOpcode() == BO_Comma) {
18089       ExprResult Sub = Rebuild(RHS);
18090       if (!Sub.isUsable())
18091         return Sub;
18092       RHS = Sub.get();
18093     } else {
18094       break;
18095     }
18096     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18097                         LHS, RHS);
18098   }
18099 
18100   //   -- If e has the form (e1)...
18101   case Expr::ParenExprClass: {
18102     auto *PE = cast<ParenExpr>(E);
18103     ExprResult Sub = Rebuild(PE->getSubExpr());
18104     if (!Sub.isUsable())
18105       return Sub;
18106     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18107   }
18108 
18109   //   -- If e is a glvalue conditional expression, ...
18110   // We don't apply this to a binary conditional operator. FIXME: Should we?
18111   case Expr::ConditionalOperatorClass: {
18112     auto *CO = cast<ConditionalOperator>(E);
18113     ExprResult LHS = Rebuild(CO->getLHS());
18114     if (LHS.isInvalid())
18115       return ExprError();
18116     ExprResult RHS = Rebuild(CO->getRHS());
18117     if (RHS.isInvalid())
18118       return ExprError();
18119     if (!LHS.isUsable() && !RHS.isUsable())
18120       return ExprEmpty();
18121     if (!LHS.isUsable())
18122       LHS = CO->getLHS();
18123     if (!RHS.isUsable())
18124       RHS = CO->getRHS();
18125     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18126                                 CO->getCond(), LHS.get(), RHS.get());
18127   }
18128 
18129   // [Clang extension]
18130   //   -- If e has the form __extension__ e1...
18131   case Expr::UnaryOperatorClass: {
18132     auto *UO = cast<UnaryOperator>(E);
18133     if (UO->getOpcode() != UO_Extension)
18134       break;
18135     ExprResult Sub = Rebuild(UO->getSubExpr());
18136     if (!Sub.isUsable())
18137       return Sub;
18138     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18139                           Sub.get());
18140   }
18141 
18142   // [Clang extension]
18143   //   -- If e has the form _Generic(...), the set of potential results is the
18144   //      union of the sets of potential results of the associated expressions.
18145   case Expr::GenericSelectionExprClass: {
18146     auto *GSE = cast<GenericSelectionExpr>(E);
18147 
18148     SmallVector<Expr *, 4> AssocExprs;
18149     bool AnyChanged = false;
18150     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18151       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18152       if (AssocExpr.isInvalid())
18153         return ExprError();
18154       if (AssocExpr.isUsable()) {
18155         AssocExprs.push_back(AssocExpr.get());
18156         AnyChanged = true;
18157       } else {
18158         AssocExprs.push_back(OrigAssocExpr);
18159       }
18160     }
18161 
18162     return AnyChanged ? S.CreateGenericSelectionExpr(
18163                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18164                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18165                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18166                       : ExprEmpty();
18167   }
18168 
18169   // [Clang extension]
18170   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18171   //      results is the union of the sets of potential results of the
18172   //      second and third subexpressions.
18173   case Expr::ChooseExprClass: {
18174     auto *CE = cast<ChooseExpr>(E);
18175 
18176     ExprResult LHS = Rebuild(CE->getLHS());
18177     if (LHS.isInvalid())
18178       return ExprError();
18179 
18180     ExprResult RHS = Rebuild(CE->getLHS());
18181     if (RHS.isInvalid())
18182       return ExprError();
18183 
18184     if (!LHS.get() && !RHS.get())
18185       return ExprEmpty();
18186     if (!LHS.isUsable())
18187       LHS = CE->getLHS();
18188     if (!RHS.isUsable())
18189       RHS = CE->getRHS();
18190 
18191     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18192                              RHS.get(), CE->getRParenLoc());
18193   }
18194 
18195   // Step through non-syntactic nodes.
18196   case Expr::ConstantExprClass: {
18197     auto *CE = cast<ConstantExpr>(E);
18198     ExprResult Sub = Rebuild(CE->getSubExpr());
18199     if (!Sub.isUsable())
18200       return Sub;
18201     return ConstantExpr::Create(S.Context, Sub.get());
18202   }
18203 
18204   // We could mostly rely on the recursive rebuilding to rebuild implicit
18205   // casts, but not at the top level, so rebuild them here.
18206   case Expr::ImplicitCastExprClass: {
18207     auto *ICE = cast<ImplicitCastExpr>(E);
18208     // Only step through the narrow set of cast kinds we expect to encounter.
18209     // Anything else suggests we've left the region in which potential results
18210     // can be found.
18211     switch (ICE->getCastKind()) {
18212     case CK_NoOp:
18213     case CK_DerivedToBase:
18214     case CK_UncheckedDerivedToBase: {
18215       ExprResult Sub = Rebuild(ICE->getSubExpr());
18216       if (!Sub.isUsable())
18217         return Sub;
18218       CXXCastPath Path(ICE->path());
18219       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18220                                  ICE->getValueKind(), &Path);
18221     }
18222 
18223     default:
18224       break;
18225     }
18226     break;
18227   }
18228 
18229   default:
18230     break;
18231   }
18232 
18233   // Can't traverse through this node. Nothing to do.
18234   return ExprEmpty();
18235 }
18236 
18237 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18238   // Check whether the operand is or contains an object of non-trivial C union
18239   // type.
18240   if (E->getType().isVolatileQualified() &&
18241       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18242        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18243     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18244                           Sema::NTCUC_LValueToRValueVolatile,
18245                           NTCUK_Destruct|NTCUK_Copy);
18246 
18247   // C++2a [basic.def.odr]p4:
18248   //   [...] an expression of non-volatile-qualified non-class type to which
18249   //   the lvalue-to-rvalue conversion is applied [...]
18250   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18251     return E;
18252 
18253   ExprResult Result =
18254       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18255   if (Result.isInvalid())
18256     return ExprError();
18257   return Result.get() ? Result : E;
18258 }
18259 
18260 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18261   Res = CorrectDelayedTyposInExpr(Res);
18262 
18263   if (!Res.isUsable())
18264     return Res;
18265 
18266   // If a constant-expression is a reference to a variable where we delay
18267   // deciding whether it is an odr-use, just assume we will apply the
18268   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18269   // (a non-type template argument), we have special handling anyway.
18270   return CheckLValueToRValueConversionOperand(Res.get());
18271 }
18272 
18273 void Sema::CleanupVarDeclMarking() {
18274   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18275   // call.
18276   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18277   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18278 
18279   for (Expr *E : LocalMaybeODRUseExprs) {
18280     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18281       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18282                          DRE->getLocation(), *this);
18283     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18284       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18285                          *this);
18286     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18287       for (VarDecl *VD : *FP)
18288         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18289     } else {
18290       llvm_unreachable("Unexpected expression");
18291     }
18292   }
18293 
18294   assert(MaybeODRUseExprs.empty() &&
18295          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18296 }
18297 
18298 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18299                                     VarDecl *Var, Expr *E) {
18300   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18301           isa<FunctionParmPackExpr>(E)) &&
18302          "Invalid Expr argument to DoMarkVarDeclReferenced");
18303   Var->setReferenced();
18304 
18305   if (Var->isInvalidDecl())
18306     return;
18307 
18308   // Record a CUDA/HIP static device/constant variable if it is referenced
18309   // by host code. This is done conservatively, when the variable is referenced
18310   // in any of the following contexts:
18311   //   - a non-function context
18312   //   - a host function
18313   //   - a host device function
18314   // This also requires the reference of the static device/constant variable by
18315   // host code to be visible in the device compilation for the compiler to be
18316   // able to externalize the static device/constant variable.
18317   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18318     auto *CurContext = SemaRef.CurContext;
18319     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18320         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18321         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18322          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18323       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18324   }
18325 
18326   auto *MSI = Var->getMemberSpecializationInfo();
18327   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18328                                        : Var->getTemplateSpecializationKind();
18329 
18330   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18331   bool UsableInConstantExpr =
18332       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18333 
18334   // C++20 [expr.const]p12:
18335   //   A variable [...] is needed for constant evaluation if it is [...] a
18336   //   variable whose name appears as a potentially constant evaluated
18337   //   expression that is either a contexpr variable or is of non-volatile
18338   //   const-qualified integral type or of reference type
18339   bool NeededForConstantEvaluation =
18340       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18341 
18342   bool NeedDefinition =
18343       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18344 
18345   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18346          "Can't instantiate a partial template specialization.");
18347 
18348   // If this might be a member specialization of a static data member, check
18349   // the specialization is visible. We already did the checks for variable
18350   // template specializations when we created them.
18351   if (NeedDefinition && TSK != TSK_Undeclared &&
18352       !isa<VarTemplateSpecializationDecl>(Var))
18353     SemaRef.checkSpecializationVisibility(Loc, Var);
18354 
18355   // Perform implicit instantiation of static data members, static data member
18356   // templates of class templates, and variable template specializations. Delay
18357   // instantiations of variable templates, except for those that could be used
18358   // in a constant expression.
18359   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18360     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18361     // instantiation declaration if a variable is usable in a constant
18362     // expression (among other cases).
18363     bool TryInstantiating =
18364         TSK == TSK_ImplicitInstantiation ||
18365         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18366 
18367     if (TryInstantiating) {
18368       SourceLocation PointOfInstantiation =
18369           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18370       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18371       if (FirstInstantiation) {
18372         PointOfInstantiation = Loc;
18373         if (MSI)
18374           MSI->setPointOfInstantiation(PointOfInstantiation);
18375           // FIXME: Notify listener.
18376         else
18377           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18378       }
18379 
18380       if (UsableInConstantExpr) {
18381         // Do not defer instantiations of variables that could be used in a
18382         // constant expression.
18383         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18384           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18385         });
18386 
18387         // Re-set the member to trigger a recomputation of the dependence bits
18388         // for the expression.
18389         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18390           DRE->setDecl(DRE->getDecl());
18391         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18392           ME->setMemberDecl(ME->getMemberDecl());
18393       } else if (FirstInstantiation ||
18394                  isa<VarTemplateSpecializationDecl>(Var)) {
18395         // FIXME: For a specialization of a variable template, we don't
18396         // distinguish between "declaration and type implicitly instantiated"
18397         // and "implicit instantiation of definition requested", so we have
18398         // no direct way to avoid enqueueing the pending instantiation
18399         // multiple times.
18400         SemaRef.PendingInstantiations
18401             .push_back(std::make_pair(Var, PointOfInstantiation));
18402       }
18403     }
18404   }
18405 
18406   // C++2a [basic.def.odr]p4:
18407   //   A variable x whose name appears as a potentially-evaluated expression e
18408   //   is odr-used by e unless
18409   //   -- x is a reference that is usable in constant expressions
18410   //   -- x is a variable of non-reference type that is usable in constant
18411   //      expressions and has no mutable subobjects [FIXME], and e is an
18412   //      element of the set of potential results of an expression of
18413   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18414   //      conversion is applied
18415   //   -- x is a variable of non-reference type, and e is an element of the set
18416   //      of potential results of a discarded-value expression to which the
18417   //      lvalue-to-rvalue conversion is not applied [FIXME]
18418   //
18419   // We check the first part of the second bullet here, and
18420   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18421   // FIXME: To get the third bullet right, we need to delay this even for
18422   // variables that are not usable in constant expressions.
18423 
18424   // If we already know this isn't an odr-use, there's nothing more to do.
18425   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18426     if (DRE->isNonOdrUse())
18427       return;
18428   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18429     if (ME->isNonOdrUse())
18430       return;
18431 
18432   switch (OdrUse) {
18433   case OdrUseContext::None:
18434     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18435            "missing non-odr-use marking for unevaluated decl ref");
18436     break;
18437 
18438   case OdrUseContext::FormallyOdrUsed:
18439     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18440     // behavior.
18441     break;
18442 
18443   case OdrUseContext::Used:
18444     // If we might later find that this expression isn't actually an odr-use,
18445     // delay the marking.
18446     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18447       SemaRef.MaybeODRUseExprs.insert(E);
18448     else
18449       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18450     break;
18451 
18452   case OdrUseContext::Dependent:
18453     // If this is a dependent context, we don't need to mark variables as
18454     // odr-used, but we may still need to track them for lambda capture.
18455     // FIXME: Do we also need to do this inside dependent typeid expressions
18456     // (which are modeled as unevaluated at this point)?
18457     const bool RefersToEnclosingScope =
18458         (SemaRef.CurContext != Var->getDeclContext() &&
18459          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18460     if (RefersToEnclosingScope) {
18461       LambdaScopeInfo *const LSI =
18462           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18463       if (LSI && (!LSI->CallOperator ||
18464                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18465         // If a variable could potentially be odr-used, defer marking it so
18466         // until we finish analyzing the full expression for any
18467         // lvalue-to-rvalue
18468         // or discarded value conversions that would obviate odr-use.
18469         // Add it to the list of potential captures that will be analyzed
18470         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18471         // unless the variable is a reference that was initialized by a constant
18472         // expression (this will never need to be captured or odr-used).
18473         //
18474         // FIXME: We can simplify this a lot after implementing P0588R1.
18475         assert(E && "Capture variable should be used in an expression.");
18476         if (!Var->getType()->isReferenceType() ||
18477             !Var->isUsableInConstantExpressions(SemaRef.Context))
18478           LSI->addPotentialCapture(E->IgnoreParens());
18479       }
18480     }
18481     break;
18482   }
18483 }
18484 
18485 /// Mark a variable referenced, and check whether it is odr-used
18486 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18487 /// used directly for normal expressions referring to VarDecl.
18488 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18489   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18490 }
18491 
18492 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18493                                Decl *D, Expr *E, bool MightBeOdrUse) {
18494   if (SemaRef.isInOpenMPDeclareTargetContext())
18495     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18496 
18497   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18498     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18499     return;
18500   }
18501 
18502   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18503 
18504   // If this is a call to a method via a cast, also mark the method in the
18505   // derived class used in case codegen can devirtualize the call.
18506   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18507   if (!ME)
18508     return;
18509   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18510   if (!MD)
18511     return;
18512   // Only attempt to devirtualize if this is truly a virtual call.
18513   bool IsVirtualCall = MD->isVirtual() &&
18514                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18515   if (!IsVirtualCall)
18516     return;
18517 
18518   // If it's possible to devirtualize the call, mark the called function
18519   // referenced.
18520   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18521       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18522   if (DM)
18523     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18524 }
18525 
18526 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18527 ///
18528 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18529 /// handled with care if the DeclRefExpr is not newly-created.
18530 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18531   // TODO: update this with DR# once a defect report is filed.
18532   // C++11 defect. The address of a pure member should not be an ODR use, even
18533   // if it's a qualified reference.
18534   bool OdrUse = true;
18535   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18536     if (Method->isVirtual() &&
18537         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18538       OdrUse = false;
18539 
18540   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18541     if (!isConstantEvaluated() && FD->isConsteval() &&
18542         !RebuildingImmediateInvocation)
18543       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18544   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18545 }
18546 
18547 /// Perform reference-marking and odr-use handling for a MemberExpr.
18548 void Sema::MarkMemberReferenced(MemberExpr *E) {
18549   // C++11 [basic.def.odr]p2:
18550   //   A non-overloaded function whose name appears as a potentially-evaluated
18551   //   expression or a member of a set of candidate functions, if selected by
18552   //   overload resolution when referred to from a potentially-evaluated
18553   //   expression, is odr-used, unless it is a pure virtual function and its
18554   //   name is not explicitly qualified.
18555   bool MightBeOdrUse = true;
18556   if (E->performsVirtualDispatch(getLangOpts())) {
18557     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18558       if (Method->isPure())
18559         MightBeOdrUse = false;
18560   }
18561   SourceLocation Loc =
18562       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18563   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18564 }
18565 
18566 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18567 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18568   for (VarDecl *VD : *E)
18569     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18570 }
18571 
18572 /// Perform marking for a reference to an arbitrary declaration.  It
18573 /// marks the declaration referenced, and performs odr-use checking for
18574 /// functions and variables. This method should not be used when building a
18575 /// normal expression which refers to a variable.
18576 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18577                                  bool MightBeOdrUse) {
18578   if (MightBeOdrUse) {
18579     if (auto *VD = dyn_cast<VarDecl>(D)) {
18580       MarkVariableReferenced(Loc, VD);
18581       return;
18582     }
18583   }
18584   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18585     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18586     return;
18587   }
18588   D->setReferenced();
18589 }
18590 
18591 namespace {
18592   // Mark all of the declarations used by a type as referenced.
18593   // FIXME: Not fully implemented yet! We need to have a better understanding
18594   // of when we're entering a context we should not recurse into.
18595   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18596   // TreeTransforms rebuilding the type in a new context. Rather than
18597   // duplicating the TreeTransform logic, we should consider reusing it here.
18598   // Currently that causes problems when rebuilding LambdaExprs.
18599   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18600     Sema &S;
18601     SourceLocation Loc;
18602 
18603   public:
18604     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18605 
18606     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18607 
18608     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18609   };
18610 }
18611 
18612 bool MarkReferencedDecls::TraverseTemplateArgument(
18613     const TemplateArgument &Arg) {
18614   {
18615     // A non-type template argument is a constant-evaluated context.
18616     EnterExpressionEvaluationContext Evaluated(
18617         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18618     if (Arg.getKind() == TemplateArgument::Declaration) {
18619       if (Decl *D = Arg.getAsDecl())
18620         S.MarkAnyDeclReferenced(Loc, D, true);
18621     } else if (Arg.getKind() == TemplateArgument::Expression) {
18622       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18623     }
18624   }
18625 
18626   return Inherited::TraverseTemplateArgument(Arg);
18627 }
18628 
18629 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18630   MarkReferencedDecls Marker(*this, Loc);
18631   Marker.TraverseType(T);
18632 }
18633 
18634 namespace {
18635 /// Helper class that marks all of the declarations referenced by
18636 /// potentially-evaluated subexpressions as "referenced".
18637 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18638 public:
18639   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18640   bool SkipLocalVariables;
18641 
18642   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18643       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18644 
18645   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18646     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18647   }
18648 
18649   void VisitDeclRefExpr(DeclRefExpr *E) {
18650     // If we were asked not to visit local variables, don't.
18651     if (SkipLocalVariables) {
18652       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18653         if (VD->hasLocalStorage())
18654           return;
18655     }
18656 
18657     // FIXME: This can trigger the instantiation of the initializer of a
18658     // variable, which can cause the expression to become value-dependent
18659     // or error-dependent. Do we need to propagate the new dependence bits?
18660     S.MarkDeclRefReferenced(E);
18661   }
18662 
18663   void VisitMemberExpr(MemberExpr *E) {
18664     S.MarkMemberReferenced(E);
18665     Visit(E->getBase());
18666   }
18667 };
18668 } // namespace
18669 
18670 /// Mark any declarations that appear within this expression or any
18671 /// potentially-evaluated subexpressions as "referenced".
18672 ///
18673 /// \param SkipLocalVariables If true, don't mark local variables as
18674 /// 'referenced'.
18675 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18676                                             bool SkipLocalVariables) {
18677   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18678 }
18679 
18680 /// Emit a diagnostic that describes an effect on the run-time behavior
18681 /// of the program being compiled.
18682 ///
18683 /// This routine emits the given diagnostic when the code currently being
18684 /// type-checked is "potentially evaluated", meaning that there is a
18685 /// possibility that the code will actually be executable. Code in sizeof()
18686 /// expressions, code used only during overload resolution, etc., are not
18687 /// potentially evaluated. This routine will suppress such diagnostics or,
18688 /// in the absolutely nutty case of potentially potentially evaluated
18689 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18690 /// later.
18691 ///
18692 /// This routine should be used for all diagnostics that describe the run-time
18693 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18694 /// Failure to do so will likely result in spurious diagnostics or failures
18695 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18696 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18697                                const PartialDiagnostic &PD) {
18698   switch (ExprEvalContexts.back().Context) {
18699   case ExpressionEvaluationContext::Unevaluated:
18700   case ExpressionEvaluationContext::UnevaluatedList:
18701   case ExpressionEvaluationContext::UnevaluatedAbstract:
18702   case ExpressionEvaluationContext::DiscardedStatement:
18703     // The argument will never be evaluated, so don't complain.
18704     break;
18705 
18706   case ExpressionEvaluationContext::ConstantEvaluated:
18707     // Relevant diagnostics should be produced by constant evaluation.
18708     break;
18709 
18710   case ExpressionEvaluationContext::PotentiallyEvaluated:
18711   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18712     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18713       FunctionScopes.back()->PossiblyUnreachableDiags.
18714         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18715       return true;
18716     }
18717 
18718     // The initializer of a constexpr variable or of the first declaration of a
18719     // static data member is not syntactically a constant evaluated constant,
18720     // but nonetheless is always required to be a constant expression, so we
18721     // can skip diagnosing.
18722     // FIXME: Using the mangling context here is a hack.
18723     if (auto *VD = dyn_cast_or_null<VarDecl>(
18724             ExprEvalContexts.back().ManglingContextDecl)) {
18725       if (VD->isConstexpr() ||
18726           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18727         break;
18728       // FIXME: For any other kind of variable, we should build a CFG for its
18729       // initializer and check whether the context in question is reachable.
18730     }
18731 
18732     Diag(Loc, PD);
18733     return true;
18734   }
18735 
18736   return false;
18737 }
18738 
18739 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18740                                const PartialDiagnostic &PD) {
18741   return DiagRuntimeBehavior(
18742       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18743 }
18744 
18745 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18746                                CallExpr *CE, FunctionDecl *FD) {
18747   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18748     return false;
18749 
18750   // If we're inside a decltype's expression, don't check for a valid return
18751   // type or construct temporaries until we know whether this is the last call.
18752   if (ExprEvalContexts.back().ExprContext ==
18753       ExpressionEvaluationContextRecord::EK_Decltype) {
18754     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18755     return false;
18756   }
18757 
18758   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18759     FunctionDecl *FD;
18760     CallExpr *CE;
18761 
18762   public:
18763     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18764       : FD(FD), CE(CE) { }
18765 
18766     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18767       if (!FD) {
18768         S.Diag(Loc, diag::err_call_incomplete_return)
18769           << T << CE->getSourceRange();
18770         return;
18771       }
18772 
18773       S.Diag(Loc, diag::err_call_function_incomplete_return)
18774           << CE->getSourceRange() << FD << T;
18775       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18776           << FD->getDeclName();
18777     }
18778   } Diagnoser(FD, CE);
18779 
18780   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18781     return true;
18782 
18783   return false;
18784 }
18785 
18786 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18787 // will prevent this condition from triggering, which is what we want.
18788 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18789   SourceLocation Loc;
18790 
18791   unsigned diagnostic = diag::warn_condition_is_assignment;
18792   bool IsOrAssign = false;
18793 
18794   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18795     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18796       return;
18797 
18798     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18799 
18800     // Greylist some idioms by putting them into a warning subcategory.
18801     if (ObjCMessageExpr *ME
18802           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18803       Selector Sel = ME->getSelector();
18804 
18805       // self = [<foo> init...]
18806       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18807         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18808 
18809       // <foo> = [<bar> nextObject]
18810       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18811         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18812     }
18813 
18814     Loc = Op->getOperatorLoc();
18815   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18816     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18817       return;
18818 
18819     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18820     Loc = Op->getOperatorLoc();
18821   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18822     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18823   else {
18824     // Not an assignment.
18825     return;
18826   }
18827 
18828   Diag(Loc, diagnostic) << E->getSourceRange();
18829 
18830   SourceLocation Open = E->getBeginLoc();
18831   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18832   Diag(Loc, diag::note_condition_assign_silence)
18833         << FixItHint::CreateInsertion(Open, "(")
18834         << FixItHint::CreateInsertion(Close, ")");
18835 
18836   if (IsOrAssign)
18837     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18838       << FixItHint::CreateReplacement(Loc, "!=");
18839   else
18840     Diag(Loc, diag::note_condition_assign_to_comparison)
18841       << FixItHint::CreateReplacement(Loc, "==");
18842 }
18843 
18844 /// Redundant parentheses over an equality comparison can indicate
18845 /// that the user intended an assignment used as condition.
18846 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18847   // Don't warn if the parens came from a macro.
18848   SourceLocation parenLoc = ParenE->getBeginLoc();
18849   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18850     return;
18851   // Don't warn for dependent expressions.
18852   if (ParenE->isTypeDependent())
18853     return;
18854 
18855   Expr *E = ParenE->IgnoreParens();
18856 
18857   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18858     if (opE->getOpcode() == BO_EQ &&
18859         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18860                                                            == Expr::MLV_Valid) {
18861       SourceLocation Loc = opE->getOperatorLoc();
18862 
18863       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18864       SourceRange ParenERange = ParenE->getSourceRange();
18865       Diag(Loc, diag::note_equality_comparison_silence)
18866         << FixItHint::CreateRemoval(ParenERange.getBegin())
18867         << FixItHint::CreateRemoval(ParenERange.getEnd());
18868       Diag(Loc, diag::note_equality_comparison_to_assign)
18869         << FixItHint::CreateReplacement(Loc, "=");
18870     }
18871 }
18872 
18873 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18874                                        bool IsConstexpr) {
18875   DiagnoseAssignmentAsCondition(E);
18876   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18877     DiagnoseEqualityWithExtraParens(parenE);
18878 
18879   ExprResult result = CheckPlaceholderExpr(E);
18880   if (result.isInvalid()) return ExprError();
18881   E = result.get();
18882 
18883   if (!E->isTypeDependent()) {
18884     if (getLangOpts().CPlusPlus)
18885       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18886 
18887     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18888     if (ERes.isInvalid())
18889       return ExprError();
18890     E = ERes.get();
18891 
18892     QualType T = E->getType();
18893     if (!T->isScalarType()) { // C99 6.8.4.1p1
18894       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18895         << T << E->getSourceRange();
18896       return ExprError();
18897     }
18898     CheckBoolLikeConversion(E, Loc);
18899   }
18900 
18901   return E;
18902 }
18903 
18904 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18905                                            Expr *SubExpr, ConditionKind CK) {
18906   // Empty conditions are valid in for-statements.
18907   if (!SubExpr)
18908     return ConditionResult();
18909 
18910   ExprResult Cond;
18911   switch (CK) {
18912   case ConditionKind::Boolean:
18913     Cond = CheckBooleanCondition(Loc, SubExpr);
18914     break;
18915 
18916   case ConditionKind::ConstexprIf:
18917     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18918     break;
18919 
18920   case ConditionKind::Switch:
18921     Cond = CheckSwitchCondition(Loc, SubExpr);
18922     break;
18923   }
18924   if (Cond.isInvalid()) {
18925     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18926                               {SubExpr});
18927     if (!Cond.get())
18928       return ConditionError();
18929   }
18930   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18931   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18932   if (!FullExpr.get())
18933     return ConditionError();
18934 
18935   return ConditionResult(*this, nullptr, FullExpr,
18936                          CK == ConditionKind::ConstexprIf);
18937 }
18938 
18939 namespace {
18940   /// A visitor for rebuilding a call to an __unknown_any expression
18941   /// to have an appropriate type.
18942   struct RebuildUnknownAnyFunction
18943     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18944 
18945     Sema &S;
18946 
18947     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18948 
18949     ExprResult VisitStmt(Stmt *S) {
18950       llvm_unreachable("unexpected statement!");
18951     }
18952 
18953     ExprResult VisitExpr(Expr *E) {
18954       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18955         << E->getSourceRange();
18956       return ExprError();
18957     }
18958 
18959     /// Rebuild an expression which simply semantically wraps another
18960     /// expression which it shares the type and value kind of.
18961     template <class T> ExprResult rebuildSugarExpr(T *E) {
18962       ExprResult SubResult = Visit(E->getSubExpr());
18963       if (SubResult.isInvalid()) return ExprError();
18964 
18965       Expr *SubExpr = SubResult.get();
18966       E->setSubExpr(SubExpr);
18967       E->setType(SubExpr->getType());
18968       E->setValueKind(SubExpr->getValueKind());
18969       assert(E->getObjectKind() == OK_Ordinary);
18970       return E;
18971     }
18972 
18973     ExprResult VisitParenExpr(ParenExpr *E) {
18974       return rebuildSugarExpr(E);
18975     }
18976 
18977     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18978       return rebuildSugarExpr(E);
18979     }
18980 
18981     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18982       ExprResult SubResult = Visit(E->getSubExpr());
18983       if (SubResult.isInvalid()) return ExprError();
18984 
18985       Expr *SubExpr = SubResult.get();
18986       E->setSubExpr(SubExpr);
18987       E->setType(S.Context.getPointerType(SubExpr->getType()));
18988       assert(E->getValueKind() == VK_RValue);
18989       assert(E->getObjectKind() == OK_Ordinary);
18990       return E;
18991     }
18992 
18993     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18994       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18995 
18996       E->setType(VD->getType());
18997 
18998       assert(E->getValueKind() == VK_RValue);
18999       if (S.getLangOpts().CPlusPlus &&
19000           !(isa<CXXMethodDecl>(VD) &&
19001             cast<CXXMethodDecl>(VD)->isInstance()))
19002         E->setValueKind(VK_LValue);
19003 
19004       return E;
19005     }
19006 
19007     ExprResult VisitMemberExpr(MemberExpr *E) {
19008       return resolveDecl(E, E->getMemberDecl());
19009     }
19010 
19011     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19012       return resolveDecl(E, E->getDecl());
19013     }
19014   };
19015 }
19016 
19017 /// Given a function expression of unknown-any type, try to rebuild it
19018 /// to have a function type.
19019 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19020   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19021   if (Result.isInvalid()) return ExprError();
19022   return S.DefaultFunctionArrayConversion(Result.get());
19023 }
19024 
19025 namespace {
19026   /// A visitor for rebuilding an expression of type __unknown_anytype
19027   /// into one which resolves the type directly on the referring
19028   /// expression.  Strict preservation of the original source
19029   /// structure is not a goal.
19030   struct RebuildUnknownAnyExpr
19031     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19032 
19033     Sema &S;
19034 
19035     /// The current destination type.
19036     QualType DestType;
19037 
19038     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19039       : S(S), DestType(CastType) {}
19040 
19041     ExprResult VisitStmt(Stmt *S) {
19042       llvm_unreachable("unexpected statement!");
19043     }
19044 
19045     ExprResult VisitExpr(Expr *E) {
19046       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19047         << E->getSourceRange();
19048       return ExprError();
19049     }
19050 
19051     ExprResult VisitCallExpr(CallExpr *E);
19052     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19053 
19054     /// Rebuild an expression which simply semantically wraps another
19055     /// expression which it shares the type and value kind of.
19056     template <class T> ExprResult rebuildSugarExpr(T *E) {
19057       ExprResult SubResult = Visit(E->getSubExpr());
19058       if (SubResult.isInvalid()) return ExprError();
19059       Expr *SubExpr = SubResult.get();
19060       E->setSubExpr(SubExpr);
19061       E->setType(SubExpr->getType());
19062       E->setValueKind(SubExpr->getValueKind());
19063       assert(E->getObjectKind() == OK_Ordinary);
19064       return E;
19065     }
19066 
19067     ExprResult VisitParenExpr(ParenExpr *E) {
19068       return rebuildSugarExpr(E);
19069     }
19070 
19071     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19072       return rebuildSugarExpr(E);
19073     }
19074 
19075     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19076       const PointerType *Ptr = DestType->getAs<PointerType>();
19077       if (!Ptr) {
19078         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19079           << E->getSourceRange();
19080         return ExprError();
19081       }
19082 
19083       if (isa<CallExpr>(E->getSubExpr())) {
19084         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19085           << E->getSourceRange();
19086         return ExprError();
19087       }
19088 
19089       assert(E->getValueKind() == VK_RValue);
19090       assert(E->getObjectKind() == OK_Ordinary);
19091       E->setType(DestType);
19092 
19093       // Build the sub-expression as if it were an object of the pointee type.
19094       DestType = Ptr->getPointeeType();
19095       ExprResult SubResult = Visit(E->getSubExpr());
19096       if (SubResult.isInvalid()) return ExprError();
19097       E->setSubExpr(SubResult.get());
19098       return E;
19099     }
19100 
19101     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19102 
19103     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19104 
19105     ExprResult VisitMemberExpr(MemberExpr *E) {
19106       return resolveDecl(E, E->getMemberDecl());
19107     }
19108 
19109     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19110       return resolveDecl(E, E->getDecl());
19111     }
19112   };
19113 }
19114 
19115 /// Rebuilds a call expression which yielded __unknown_anytype.
19116 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19117   Expr *CalleeExpr = E->getCallee();
19118 
19119   enum FnKind {
19120     FK_MemberFunction,
19121     FK_FunctionPointer,
19122     FK_BlockPointer
19123   };
19124 
19125   FnKind Kind;
19126   QualType CalleeType = CalleeExpr->getType();
19127   if (CalleeType == S.Context.BoundMemberTy) {
19128     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19129     Kind = FK_MemberFunction;
19130     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19131   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19132     CalleeType = Ptr->getPointeeType();
19133     Kind = FK_FunctionPointer;
19134   } else {
19135     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19136     Kind = FK_BlockPointer;
19137   }
19138   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19139 
19140   // Verify that this is a legal result type of a function.
19141   if (DestType->isArrayType() || DestType->isFunctionType()) {
19142     unsigned diagID = diag::err_func_returning_array_function;
19143     if (Kind == FK_BlockPointer)
19144       diagID = diag::err_block_returning_array_function;
19145 
19146     S.Diag(E->getExprLoc(), diagID)
19147       << DestType->isFunctionType() << DestType;
19148     return ExprError();
19149   }
19150 
19151   // Otherwise, go ahead and set DestType as the call's result.
19152   E->setType(DestType.getNonLValueExprType(S.Context));
19153   E->setValueKind(Expr::getValueKindForType(DestType));
19154   assert(E->getObjectKind() == OK_Ordinary);
19155 
19156   // Rebuild the function type, replacing the result type with DestType.
19157   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19158   if (Proto) {
19159     // __unknown_anytype(...) is a special case used by the debugger when
19160     // it has no idea what a function's signature is.
19161     //
19162     // We want to build this call essentially under the K&R
19163     // unprototyped rules, but making a FunctionNoProtoType in C++
19164     // would foul up all sorts of assumptions.  However, we cannot
19165     // simply pass all arguments as variadic arguments, nor can we
19166     // portably just call the function under a non-variadic type; see
19167     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19168     // However, it turns out that in practice it is generally safe to
19169     // call a function declared as "A foo(B,C,D);" under the prototype
19170     // "A foo(B,C,D,...);".  The only known exception is with the
19171     // Windows ABI, where any variadic function is implicitly cdecl
19172     // regardless of its normal CC.  Therefore we change the parameter
19173     // types to match the types of the arguments.
19174     //
19175     // This is a hack, but it is far superior to moving the
19176     // corresponding target-specific code from IR-gen to Sema/AST.
19177 
19178     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19179     SmallVector<QualType, 8> ArgTypes;
19180     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19181       ArgTypes.reserve(E->getNumArgs());
19182       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19183         Expr *Arg = E->getArg(i);
19184         QualType ArgType = Arg->getType();
19185         if (E->isLValue()) {
19186           ArgType = S.Context.getLValueReferenceType(ArgType);
19187         } else if (E->isXValue()) {
19188           ArgType = S.Context.getRValueReferenceType(ArgType);
19189         }
19190         ArgTypes.push_back(ArgType);
19191       }
19192       ParamTypes = ArgTypes;
19193     }
19194     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19195                                          Proto->getExtProtoInfo());
19196   } else {
19197     DestType = S.Context.getFunctionNoProtoType(DestType,
19198                                                 FnType->getExtInfo());
19199   }
19200 
19201   // Rebuild the appropriate pointer-to-function type.
19202   switch (Kind) {
19203   case FK_MemberFunction:
19204     // Nothing to do.
19205     break;
19206 
19207   case FK_FunctionPointer:
19208     DestType = S.Context.getPointerType(DestType);
19209     break;
19210 
19211   case FK_BlockPointer:
19212     DestType = S.Context.getBlockPointerType(DestType);
19213     break;
19214   }
19215 
19216   // Finally, we can recurse.
19217   ExprResult CalleeResult = Visit(CalleeExpr);
19218   if (!CalleeResult.isUsable()) return ExprError();
19219   E->setCallee(CalleeResult.get());
19220 
19221   // Bind a temporary if necessary.
19222   return S.MaybeBindToTemporary(E);
19223 }
19224 
19225 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19226   // Verify that this is a legal result type of a call.
19227   if (DestType->isArrayType() || DestType->isFunctionType()) {
19228     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19229       << DestType->isFunctionType() << DestType;
19230     return ExprError();
19231   }
19232 
19233   // Rewrite the method result type if available.
19234   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19235     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19236     Method->setReturnType(DestType);
19237   }
19238 
19239   // Change the type of the message.
19240   E->setType(DestType.getNonReferenceType());
19241   E->setValueKind(Expr::getValueKindForType(DestType));
19242 
19243   return S.MaybeBindToTemporary(E);
19244 }
19245 
19246 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19247   // The only case we should ever see here is a function-to-pointer decay.
19248   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19249     assert(E->getValueKind() == VK_RValue);
19250     assert(E->getObjectKind() == OK_Ordinary);
19251 
19252     E->setType(DestType);
19253 
19254     // Rebuild the sub-expression as the pointee (function) type.
19255     DestType = DestType->castAs<PointerType>()->getPointeeType();
19256 
19257     ExprResult Result = Visit(E->getSubExpr());
19258     if (!Result.isUsable()) return ExprError();
19259 
19260     E->setSubExpr(Result.get());
19261     return E;
19262   } else if (E->getCastKind() == CK_LValueToRValue) {
19263     assert(E->getValueKind() == VK_RValue);
19264     assert(E->getObjectKind() == OK_Ordinary);
19265 
19266     assert(isa<BlockPointerType>(E->getType()));
19267 
19268     E->setType(DestType);
19269 
19270     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19271     DestType = S.Context.getLValueReferenceType(DestType);
19272 
19273     ExprResult Result = Visit(E->getSubExpr());
19274     if (!Result.isUsable()) return ExprError();
19275 
19276     E->setSubExpr(Result.get());
19277     return E;
19278   } else {
19279     llvm_unreachable("Unhandled cast type!");
19280   }
19281 }
19282 
19283 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19284   ExprValueKind ValueKind = VK_LValue;
19285   QualType Type = DestType;
19286 
19287   // We know how to make this work for certain kinds of decls:
19288 
19289   //  - functions
19290   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19291     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19292       DestType = Ptr->getPointeeType();
19293       ExprResult Result = resolveDecl(E, VD);
19294       if (Result.isInvalid()) return ExprError();
19295       return S.ImpCastExprToType(Result.get(), Type,
19296                                  CK_FunctionToPointerDecay, VK_RValue);
19297     }
19298 
19299     if (!Type->isFunctionType()) {
19300       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19301         << VD << E->getSourceRange();
19302       return ExprError();
19303     }
19304     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19305       // We must match the FunctionDecl's type to the hack introduced in
19306       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19307       // type. See the lengthy commentary in that routine.
19308       QualType FDT = FD->getType();
19309       const FunctionType *FnType = FDT->castAs<FunctionType>();
19310       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19311       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19312       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19313         SourceLocation Loc = FD->getLocation();
19314         FunctionDecl *NewFD = FunctionDecl::Create(
19315             S.Context, FD->getDeclContext(), Loc, Loc,
19316             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19317             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19318             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19319 
19320         if (FD->getQualifier())
19321           NewFD->setQualifierInfo(FD->getQualifierLoc());
19322 
19323         SmallVector<ParmVarDecl*, 16> Params;
19324         for (const auto &AI : FT->param_types()) {
19325           ParmVarDecl *Param =
19326             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19327           Param->setScopeInfo(0, Params.size());
19328           Params.push_back(Param);
19329         }
19330         NewFD->setParams(Params);
19331         DRE->setDecl(NewFD);
19332         VD = DRE->getDecl();
19333       }
19334     }
19335 
19336     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19337       if (MD->isInstance()) {
19338         ValueKind = VK_RValue;
19339         Type = S.Context.BoundMemberTy;
19340       }
19341 
19342     // Function references aren't l-values in C.
19343     if (!S.getLangOpts().CPlusPlus)
19344       ValueKind = VK_RValue;
19345 
19346   //  - variables
19347   } else if (isa<VarDecl>(VD)) {
19348     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19349       Type = RefTy->getPointeeType();
19350     } else if (Type->isFunctionType()) {
19351       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19352         << VD << E->getSourceRange();
19353       return ExprError();
19354     }
19355 
19356   //  - nothing else
19357   } else {
19358     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19359       << VD << E->getSourceRange();
19360     return ExprError();
19361   }
19362 
19363   // Modifying the declaration like this is friendly to IR-gen but
19364   // also really dangerous.
19365   VD->setType(DestType);
19366   E->setType(Type);
19367   E->setValueKind(ValueKind);
19368   return E;
19369 }
19370 
19371 /// Check a cast of an unknown-any type.  We intentionally only
19372 /// trigger this for C-style casts.
19373 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19374                                      Expr *CastExpr, CastKind &CastKind,
19375                                      ExprValueKind &VK, CXXCastPath &Path) {
19376   // The type we're casting to must be either void or complete.
19377   if (!CastType->isVoidType() &&
19378       RequireCompleteType(TypeRange.getBegin(), CastType,
19379                           diag::err_typecheck_cast_to_incomplete))
19380     return ExprError();
19381 
19382   // Rewrite the casted expression from scratch.
19383   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19384   if (!result.isUsable()) return ExprError();
19385 
19386   CastExpr = result.get();
19387   VK = CastExpr->getValueKind();
19388   CastKind = CK_NoOp;
19389 
19390   return CastExpr;
19391 }
19392 
19393 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19394   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19395 }
19396 
19397 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19398                                     Expr *arg, QualType &paramType) {
19399   // If the syntactic form of the argument is not an explicit cast of
19400   // any sort, just do default argument promotion.
19401   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19402   if (!castArg) {
19403     ExprResult result = DefaultArgumentPromotion(arg);
19404     if (result.isInvalid()) return ExprError();
19405     paramType = result.get()->getType();
19406     return result;
19407   }
19408 
19409   // Otherwise, use the type that was written in the explicit cast.
19410   assert(!arg->hasPlaceholderType());
19411   paramType = castArg->getTypeAsWritten();
19412 
19413   // Copy-initialize a parameter of that type.
19414   InitializedEntity entity =
19415     InitializedEntity::InitializeParameter(Context, paramType,
19416                                            /*consumed*/ false);
19417   return PerformCopyInitialization(entity, callLoc, arg);
19418 }
19419 
19420 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19421   Expr *orig = E;
19422   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19423   while (true) {
19424     E = E->IgnoreParenImpCasts();
19425     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19426       E = call->getCallee();
19427       diagID = diag::err_uncasted_call_of_unknown_any;
19428     } else {
19429       break;
19430     }
19431   }
19432 
19433   SourceLocation loc;
19434   NamedDecl *d;
19435   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19436     loc = ref->getLocation();
19437     d = ref->getDecl();
19438   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19439     loc = mem->getMemberLoc();
19440     d = mem->getMemberDecl();
19441   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19442     diagID = diag::err_uncasted_call_of_unknown_any;
19443     loc = msg->getSelectorStartLoc();
19444     d = msg->getMethodDecl();
19445     if (!d) {
19446       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19447         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19448         << orig->getSourceRange();
19449       return ExprError();
19450     }
19451   } else {
19452     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19453       << E->getSourceRange();
19454     return ExprError();
19455   }
19456 
19457   S.Diag(loc, diagID) << d << orig->getSourceRange();
19458 
19459   // Never recoverable.
19460   return ExprError();
19461 }
19462 
19463 /// Check for operands with placeholder types and complain if found.
19464 /// Returns ExprError() if there was an error and no recovery was possible.
19465 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19466   if (!Context.isDependenceAllowed()) {
19467     // C cannot handle TypoExpr nodes on either side of a binop because it
19468     // doesn't handle dependent types properly, so make sure any TypoExprs have
19469     // been dealt with before checking the operands.
19470     ExprResult Result = CorrectDelayedTyposInExpr(E);
19471     if (!Result.isUsable()) return ExprError();
19472     E = Result.get();
19473   }
19474 
19475   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19476   if (!placeholderType) return E;
19477 
19478   switch (placeholderType->getKind()) {
19479 
19480   // Overloaded expressions.
19481   case BuiltinType::Overload: {
19482     // Try to resolve a single function template specialization.
19483     // This is obligatory.
19484     ExprResult Result = E;
19485     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19486       return Result;
19487 
19488     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19489     // leaves Result unchanged on failure.
19490     Result = E;
19491     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19492       return Result;
19493 
19494     // If that failed, try to recover with a call.
19495     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19496                          /*complain*/ true);
19497     return Result;
19498   }
19499 
19500   // Bound member functions.
19501   case BuiltinType::BoundMember: {
19502     ExprResult result = E;
19503     const Expr *BME = E->IgnoreParens();
19504     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19505     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19506     if (isa<CXXPseudoDestructorExpr>(BME)) {
19507       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19508     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19509       if (ME->getMemberNameInfo().getName().getNameKind() ==
19510           DeclarationName::CXXDestructorName)
19511         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19512     }
19513     tryToRecoverWithCall(result, PD,
19514                          /*complain*/ true);
19515     return result;
19516   }
19517 
19518   // ARC unbridged casts.
19519   case BuiltinType::ARCUnbridgedCast: {
19520     Expr *realCast = stripARCUnbridgedCast(E);
19521     diagnoseARCUnbridgedCast(realCast);
19522     return realCast;
19523   }
19524 
19525   // Expressions of unknown type.
19526   case BuiltinType::UnknownAny:
19527     return diagnoseUnknownAnyExpr(*this, E);
19528 
19529   // Pseudo-objects.
19530   case BuiltinType::PseudoObject:
19531     return checkPseudoObjectRValue(E);
19532 
19533   case BuiltinType::BuiltinFn: {
19534     // Accept __noop without parens by implicitly converting it to a call expr.
19535     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19536     if (DRE) {
19537       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19538       if (FD->getBuiltinID() == Builtin::BI__noop) {
19539         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19540                               CK_BuiltinFnToFnPtr)
19541                 .get();
19542         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19543                                 VK_RValue, SourceLocation(),
19544                                 FPOptionsOverride());
19545       }
19546     }
19547 
19548     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19549     return ExprError();
19550   }
19551 
19552   case BuiltinType::IncompleteMatrixIdx:
19553     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19554              ->getRowIdx()
19555              ->getBeginLoc(),
19556          diag::err_matrix_incomplete_index);
19557     return ExprError();
19558 
19559   // Expressions of unknown type.
19560   case BuiltinType::OMPArraySection:
19561     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19562     return ExprError();
19563 
19564   // Expressions of unknown type.
19565   case BuiltinType::OMPArrayShaping:
19566     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19567 
19568   case BuiltinType::OMPIterator:
19569     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19570 
19571   // Everything else should be impossible.
19572 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19573   case BuiltinType::Id:
19574 #include "clang/Basic/OpenCLImageTypes.def"
19575 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19576   case BuiltinType::Id:
19577 #include "clang/Basic/OpenCLExtensionTypes.def"
19578 #define SVE_TYPE(Name, Id, SingletonId) \
19579   case BuiltinType::Id:
19580 #include "clang/Basic/AArch64SVEACLETypes.def"
19581 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19582   case BuiltinType::Id:
19583 #include "clang/Basic/PPCTypes.def"
19584 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19585 #include "clang/Basic/RISCVVTypes.def"
19586 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19587 #define PLACEHOLDER_TYPE(Id, SingletonId)
19588 #include "clang/AST/BuiltinTypes.def"
19589     break;
19590   }
19591 
19592   llvm_unreachable("invalid placeholder type!");
19593 }
19594 
19595 bool Sema::CheckCaseExpression(Expr *E) {
19596   if (E->isTypeDependent())
19597     return true;
19598   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19599     return E->getType()->isIntegralOrEnumerationType();
19600   return false;
19601 }
19602 
19603 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19604 ExprResult
19605 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19606   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19607          "Unknown Objective-C Boolean value!");
19608   QualType BoolT = Context.ObjCBuiltinBoolTy;
19609   if (!Context.getBOOLDecl()) {
19610     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19611                         Sema::LookupOrdinaryName);
19612     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19613       NamedDecl *ND = Result.getFoundDecl();
19614       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19615         Context.setBOOLDecl(TD);
19616     }
19617   }
19618   if (Context.getBOOLDecl())
19619     BoolT = Context.getBOOLType();
19620   return new (Context)
19621       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19622 }
19623 
19624 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19625     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19626     SourceLocation RParen) {
19627 
19628   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19629 
19630   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19631     return Spec.getPlatform() == Platform;
19632   });
19633 
19634   VersionTuple Version;
19635   if (Spec != AvailSpecs.end())
19636     Version = Spec->getVersion();
19637 
19638   // The use of `@available` in the enclosing function should be analyzed to
19639   // warn when it's used inappropriately (i.e. not if(@available)).
19640   if (getCurFunctionOrMethodDecl())
19641     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19642   else if (getCurBlock() || getCurLambda())
19643     getCurFunction()->HasPotentialAvailabilityViolations = true;
19644 
19645   return new (Context)
19646       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19647 }
19648 
19649 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19650                                     ArrayRef<Expr *> SubExprs, QualType T) {
19651   if (!Context.getLangOpts().RecoveryAST)
19652     return ExprError();
19653 
19654   if (isSFINAEContext())
19655     return ExprError();
19656 
19657   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19658     // We don't know the concrete type, fallback to dependent type.
19659     T = Context.DependentTy;
19660   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19661 }
19662