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/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296 
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
343       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
344     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
345         << getOpenMPDeclareMapperVarName();
346     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
347     return true;
348   }
349 
350   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
351                              AvoidPartialAvailabilityChecks, ClassReceiver);
352 
353   DiagnoseUnusedOfDecl(*this, D, Loc);
354 
355   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
356 
357   // CUDA/HIP: Diagnose invalid references of host global variables in device
358   // functions. Reference of device global variables in host functions is
359   // allowed through shadow variables therefore it is not diagnosed.
360   if (LangOpts.CUDAIsDevice) {
361     auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext);
362     auto Target = IdentifyCUDATarget(FD);
363     if (FD && Target != CFT_Host) {
364       const auto *VD = dyn_cast<VarDecl>(D);
365       if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() &&
366           !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() &&
367           !VD->getType()->isCUDADeviceBuiltinSurfaceType() &&
368           !VD->getType()->isCUDADeviceBuiltinTextureType() &&
369           !VD->isConstexpr() && !VD->getType().isConstQualified())
370         targetDiag(*Locs.begin(), diag::err_ref_bad_target)
371             << /*host*/ 2 << /*variable*/ 1 << VD << Target;
372     }
373   }
374 
375   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
376     if (const auto *VD = dyn_cast<ValueDecl>(D))
377       checkDeviceDecl(VD, Loc);
378 
379     if (!Context.getTargetInfo().isTLSSupported())
380       if (const auto *VD = dyn_cast<VarDecl>(D))
381         if (VD->getTLSKind() != VarDecl::TLS_None)
382           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
383   }
384 
385   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
386       !isUnevaluatedContext()) {
387     // C++ [expr.prim.req.nested] p3
388     //   A local parameter shall only appear as an unevaluated operand
389     //   (Clause 8) within the constraint-expression.
390     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
391         << D;
392     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
393     return true;
394   }
395 
396   return false;
397 }
398 
399 /// DiagnoseSentinelCalls - This routine checks whether a call or
400 /// message-send is to a declaration with the sentinel attribute, and
401 /// if so, it checks that the requirements of the sentinel are
402 /// satisfied.
403 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
404                                  ArrayRef<Expr *> Args) {
405   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
406   if (!attr)
407     return;
408 
409   // The number of formal parameters of the declaration.
410   unsigned numFormalParams;
411 
412   // The kind of declaration.  This is also an index into a %select in
413   // the diagnostic.
414   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
415 
416   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
417     numFormalParams = MD->param_size();
418     calleeType = CT_Method;
419   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
420     numFormalParams = FD->param_size();
421     calleeType = CT_Function;
422   } else if (isa<VarDecl>(D)) {
423     QualType type = cast<ValueDecl>(D)->getType();
424     const FunctionType *fn = nullptr;
425     if (const PointerType *ptr = type->getAs<PointerType>()) {
426       fn = ptr->getPointeeType()->getAs<FunctionType>();
427       if (!fn) return;
428       calleeType = CT_Function;
429     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
430       fn = ptr->getPointeeType()->castAs<FunctionType>();
431       calleeType = CT_Block;
432     } else {
433       return;
434     }
435 
436     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
437       numFormalParams = proto->getNumParams();
438     } else {
439       numFormalParams = 0;
440     }
441   } else {
442     return;
443   }
444 
445   // "nullPos" is the number of formal parameters at the end which
446   // effectively count as part of the variadic arguments.  This is
447   // useful if you would prefer to not have *any* formal parameters,
448   // but the language forces you to have at least one.
449   unsigned nullPos = attr->getNullPos();
450   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
451   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
452 
453   // The number of arguments which should follow the sentinel.
454   unsigned numArgsAfterSentinel = attr->getSentinel();
455 
456   // If there aren't enough arguments for all the formal parameters,
457   // the sentinel, and the args after the sentinel, complain.
458   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
459     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
460     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461     return;
462   }
463 
464   // Otherwise, find the sentinel expression.
465   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
466   if (!sentinelExpr) return;
467   if (sentinelExpr->isValueDependent()) return;
468   if (Context.isSentinelNullExpr(sentinelExpr)) return;
469 
470   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
471   // or 'NULL' if those are actually defined in the context.  Only use
472   // 'nil' for ObjC methods, where it's much more likely that the
473   // variadic arguments form a list of object pointers.
474   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
475   std::string NullValue;
476   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
477     NullValue = "nil";
478   else if (getLangOpts().CPlusPlus11)
479     NullValue = "nullptr";
480   else if (PP.isMacroDefined("NULL"))
481     NullValue = "NULL";
482   else
483     NullValue = "(void*) 0";
484 
485   if (MissingNilLoc.isInvalid())
486     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
487   else
488     Diag(MissingNilLoc, diag::warn_missing_sentinel)
489       << int(calleeType)
490       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
491   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
492 }
493 
494 SourceRange Sema::getExprRange(Expr *E) const {
495   return E ? E->getSourceRange() : SourceRange();
496 }
497 
498 //===----------------------------------------------------------------------===//
499 //  Standard Promotions and Conversions
500 //===----------------------------------------------------------------------===//
501 
502 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
503 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
504   // Handle any placeholder expressions which made it here.
505   if (E->getType()->isPlaceholderType()) {
506     ExprResult result = CheckPlaceholderExpr(E);
507     if (result.isInvalid()) return ExprError();
508     E = result.get();
509   }
510 
511   QualType Ty = E->getType();
512   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
513 
514   if (Ty->isFunctionType()) {
515     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
516       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
517         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
518           return ExprError();
519 
520     E = ImpCastExprToType(E, Context.getPointerType(Ty),
521                           CK_FunctionToPointerDecay).get();
522   } else if (Ty->isArrayType()) {
523     // In C90 mode, arrays only promote to pointers if the array expression is
524     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
525     // type 'array of type' is converted to an expression that has type 'pointer
526     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
527     // that has type 'array of type' ...".  The relevant change is "an lvalue"
528     // (C90) to "an expression" (C99).
529     //
530     // C++ 4.2p1:
531     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
532     // T" can be converted to an rvalue of type "pointer to T".
533     //
534     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
535       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
536                             CK_ArrayToPointerDecay).get();
537   }
538   return E;
539 }
540 
541 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
542   // Check to see if we are dereferencing a null pointer.  If so,
543   // and if not volatile-qualified, this is undefined behavior that the
544   // optimizer will delete, so warn about it.  People sometimes try to use this
545   // to get a deterministic trap and are surprised by clang's behavior.  This
546   // only handles the pattern "*null", which is a very syntactic check.
547   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
548   if (UO && UO->getOpcode() == UO_Deref &&
549       UO->getSubExpr()->getType()->isPointerType()) {
550     const LangAS AS =
551         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
552     if ((!isTargetAddressSpace(AS) ||
553          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
554         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
555             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
556         !UO->getType().isVolatileQualified()) {
557       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558                             S.PDiag(diag::warn_indirection_through_null)
559                                 << UO->getSubExpr()->getSourceRange());
560       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561                             S.PDiag(diag::note_indirection_through_null));
562     }
563   }
564 }
565 
566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
567                                     SourceLocation AssignLoc,
568                                     const Expr* RHS) {
569   const ObjCIvarDecl *IV = OIRE->getDecl();
570   if (!IV)
571     return;
572 
573   DeclarationName MemberName = IV->getDeclName();
574   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
575   if (!Member || !Member->isStr("isa"))
576     return;
577 
578   const Expr *Base = OIRE->getBase();
579   QualType BaseType = Base->getType();
580   if (OIRE->isArrow())
581     BaseType = BaseType->getPointeeType();
582   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
583     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
584       ObjCInterfaceDecl *ClassDeclared = nullptr;
585       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
586       if (!ClassDeclared->getSuperClass()
587           && (*ClassDeclared->ivar_begin()) == IV) {
588         if (RHS) {
589           NamedDecl *ObjectSetClass =
590             S.LookupSingleName(S.TUScope,
591                                &S.Context.Idents.get("object_setClass"),
592                                SourceLocation(), S.LookupOrdinaryName);
593           if (ObjectSetClass) {
594             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
595             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
596                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
597                                               "object_setClass(")
598                 << FixItHint::CreateReplacement(
599                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
600                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
601           }
602           else
603             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
604         } else {
605           NamedDecl *ObjectGetClass =
606             S.LookupSingleName(S.TUScope,
607                                &S.Context.Idents.get("object_getClass"),
608                                SourceLocation(), S.LookupOrdinaryName);
609           if (ObjectGetClass)
610             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
611                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
612                                               "object_getClass(")
613                 << FixItHint::CreateReplacement(
614                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
615           else
616             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
617         }
618         S.Diag(IV->getLocation(), diag::note_ivar_decl);
619       }
620     }
621 }
622 
623 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
624   // Handle any placeholder expressions which made it here.
625   if (E->getType()->isPlaceholderType()) {
626     ExprResult result = CheckPlaceholderExpr(E);
627     if (result.isInvalid()) return ExprError();
628     E = result.get();
629   }
630 
631   // C++ [conv.lval]p1:
632   //   A glvalue of a non-function, non-array type T can be
633   //   converted to a prvalue.
634   if (!E->isGLValue()) return E;
635 
636   QualType T = E->getType();
637   assert(!T.isNull() && "r-value conversion on typeless expression?");
638 
639   // lvalue-to-rvalue conversion cannot be applied to function or array types.
640   if (T->isFunctionType() || T->isArrayType())
641     return E;
642 
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650 
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658 
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666 
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
674           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
675           << FixItHint::CreateReplacement(
676                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683 
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695 
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700 
701   ExprResult Res = CheckLValueToRValueConversionOperand(E);
702   if (Res.isInvalid())
703     return Res;
704   E = Res.get();
705 
706   // Loading a __weak object implicitly retains the value, so we need a cleanup to
707   // balance that.
708   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709     Cleanup.setExprNeedsCleanups(true);
710 
711   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712     Cleanup.setExprNeedsCleanups(true);
713 
714   // C++ [conv.lval]p3:
715   //   If T is cv std::nullptr_t, the result is a null pointer constant.
716   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
717   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
718                                  CurFPFeatureOverrides());
719 
720   // C11 6.3.2.1p2:
721   //   ... if the lvalue has atomic type, the value has the non-atomic version
722   //   of the type of the lvalue ...
723   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724     T = Atomic->getValueType().getUnqualifiedType();
725     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726                                    nullptr, VK_RValue, FPOptionsOverride());
727   }
728 
729   return Res;
730 }
731 
732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734   if (Res.isInvalid())
735     return ExprError();
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res;
740 }
741 
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745   QualType Ty = E->getType();
746   ExprResult Res = E;
747   // Only do implicit cast for a function type, but not for a pointer
748   // to function type.
749   if (Ty->isFunctionType()) {
750     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751                             CK_FunctionToPointerDecay);
752     if (Res.isInvalid())
753       return ExprError();
754   }
755   Res = DefaultLvalueConversion(Res.get());
756   if (Res.isInvalid())
757     return ExprError();
758   return Res.get();
759 }
760 
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767   // First, convert to an r-value.
768   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769   if (Res.isInvalid())
770     return ExprError();
771   E = Res.get();
772 
773   QualType Ty = E->getType();
774   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775 
776   // Half FP have to be promoted to float unless it is natively supported
777   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
778     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779 
780   // Try to perform integral promotions if the object has a theoretically
781   // promotable type.
782   if (Ty->isIntegralOrUnscopedEnumerationType()) {
783     // C99 6.3.1.1p2:
784     //
785     //   The following may be used in an expression wherever an int or
786     //   unsigned int may be used:
787     //     - an object or expression with an integer type whose integer
788     //       conversion rank is less than or equal to the rank of int
789     //       and unsigned int.
790     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
791     //
792     //   If an int can represent all values of the original type, the
793     //   value is converted to an int; otherwise, it is converted to an
794     //   unsigned int. These are called the integer promotions. All
795     //   other types are unchanged by the integer promotions.
796 
797     QualType PTy = Context.isPromotableBitField(E);
798     if (!PTy.isNull()) {
799       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800       return E;
801     }
802     if (Ty->isPromotableIntegerType()) {
803       QualType PT = Context.getPromotedIntegerType(Ty);
804       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805       return E;
806     }
807   }
808   return E;
809 }
810 
811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812 /// do not have a prototype. Arguments that have type float or __fp16
813 /// are promoted to double. All other argument types are converted by
814 /// UsualUnaryConversions().
815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816   QualType Ty = E->getType();
817   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818 
819   ExprResult Res = UsualUnaryConversions(E);
820   if (Res.isInvalid())
821     return ExprError();
822   E = Res.get();
823 
824   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
825   // promote to double.
826   // Note that default argument promotion applies only to float (and
827   // half/fp16); it does not apply to _Float16.
828   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
829   if (BTy && (BTy->getKind() == BuiltinType::Half ||
830               BTy->getKind() == BuiltinType::Float)) {
831     if (getLangOpts().OpenCL &&
832         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
833         if (BTy->getKind() == BuiltinType::Half) {
834             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
835         }
836     } else {
837       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
838     }
839   }
840 
841   // C++ performs lvalue-to-rvalue conversion as a default argument
842   // promotion, even on class types, but note:
843   //   C++11 [conv.lval]p2:
844   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
845   //     operand or a subexpression thereof the value contained in the
846   //     referenced object is not accessed. Otherwise, if the glvalue
847   //     has a class type, the conversion copy-initializes a temporary
848   //     of type T from the glvalue and the result of the conversion
849   //     is a prvalue for the temporary.
850   // FIXME: add some way to gate this entire thing for correctness in
851   // potentially potentially evaluated contexts.
852   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
853     ExprResult Temp = PerformCopyInitialization(
854                        InitializedEntity::InitializeTemporary(E->getType()),
855                                                 E->getExprLoc(), E);
856     if (Temp.isInvalid())
857       return ExprError();
858     E = Temp.get();
859   }
860 
861   return E;
862 }
863 
864 /// Determine the degree of POD-ness for an expression.
865 /// Incomplete types are considered POD, since this check can be performed
866 /// when we're in an unevaluated context.
867 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
868   if (Ty->isIncompleteType()) {
869     // C++11 [expr.call]p7:
870     //   After these conversions, if the argument does not have arithmetic,
871     //   enumeration, pointer, pointer to member, or class type, the program
872     //   is ill-formed.
873     //
874     // Since we've already performed array-to-pointer and function-to-pointer
875     // decay, the only such type in C++ is cv void. This also handles
876     // initializer lists as variadic arguments.
877     if (Ty->isVoidType())
878       return VAK_Invalid;
879 
880     if (Ty->isObjCObjectType())
881       return VAK_Invalid;
882     return VAK_Valid;
883   }
884 
885   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
886     return VAK_Invalid;
887 
888   if (Ty.isCXX98PODType(Context))
889     return VAK_Valid;
890 
891   // C++11 [expr.call]p7:
892   //   Passing a potentially-evaluated argument of class type (Clause 9)
893   //   having a non-trivial copy constructor, a non-trivial move constructor,
894   //   or a non-trivial destructor, with no corresponding parameter,
895   //   is conditionally-supported with implementation-defined semantics.
896   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
897     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
898       if (!Record->hasNonTrivialCopyConstructor() &&
899           !Record->hasNonTrivialMoveConstructor() &&
900           !Record->hasNonTrivialDestructor())
901         return VAK_ValidInCXX11;
902 
903   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
904     return VAK_Valid;
905 
906   if (Ty->isObjCObjectType())
907     return VAK_Invalid;
908 
909   if (getLangOpts().MSVCCompat)
910     return VAK_MSVCUndefined;
911 
912   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
913   // permitted to reject them. We should consider doing so.
914   return VAK_Undefined;
915 }
916 
917 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
918   // Don't allow one to pass an Objective-C interface to a vararg.
919   const QualType &Ty = E->getType();
920   VarArgKind VAK = isValidVarArgType(Ty);
921 
922   // Complain about passing non-POD types through varargs.
923   switch (VAK) {
924   case VAK_ValidInCXX11:
925     DiagRuntimeBehavior(
926         E->getBeginLoc(), nullptr,
927         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
928     LLVM_FALLTHROUGH;
929   case VAK_Valid:
930     if (Ty->isRecordType()) {
931       // This is unlikely to be what the user intended. If the class has a
932       // 'c_str' member function, the user probably meant to call that.
933       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
934                           PDiag(diag::warn_pass_class_arg_to_vararg)
935                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
936     }
937     break;
938 
939   case VAK_Undefined:
940   case VAK_MSVCUndefined:
941     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
942                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
943                             << getLangOpts().CPlusPlus11 << Ty << CT);
944     break;
945 
946   case VAK_Invalid:
947     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
948       Diag(E->getBeginLoc(),
949            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
950           << Ty << CT;
951     else if (Ty->isObjCObjectType())
952       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
953                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
954                               << Ty << CT);
955     else
956       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
957           << isa<InitListExpr>(E) << Ty << CT;
958     break;
959   }
960 }
961 
962 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
963 /// will create a trap if the resulting type is not a POD type.
964 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
965                                                   FunctionDecl *FDecl) {
966   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
967     // Strip the unbridged-cast placeholder expression off, if applicable.
968     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
969         (CT == VariadicMethod ||
970          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
971       E = stripARCUnbridgedCast(E);
972 
973     // Otherwise, do normal placeholder checking.
974     } else {
975       ExprResult ExprRes = CheckPlaceholderExpr(E);
976       if (ExprRes.isInvalid())
977         return ExprError();
978       E = ExprRes.get();
979     }
980   }
981 
982   ExprResult ExprRes = DefaultArgumentPromotion(E);
983   if (ExprRes.isInvalid())
984     return ExprError();
985 
986   // Copy blocks to the heap.
987   if (ExprRes.get()->getType()->isBlockPointerType())
988     maybeExtendBlockObject(ExprRes);
989 
990   E = ExprRes.get();
991 
992   // Diagnostics regarding non-POD argument types are
993   // emitted along with format string checking in Sema::CheckFunctionCall().
994   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
995     // Turn this into a trap.
996     CXXScopeSpec SS;
997     SourceLocation TemplateKWLoc;
998     UnqualifiedId Name;
999     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1000                        E->getBeginLoc());
1001     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1002                                           /*HasTrailingLParen=*/true,
1003                                           /*IsAddressOfOperand=*/false);
1004     if (TrapFn.isInvalid())
1005       return ExprError();
1006 
1007     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1008                                     None, E->getEndLoc());
1009     if (Call.isInvalid())
1010       return ExprError();
1011 
1012     ExprResult Comma =
1013         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1014     if (Comma.isInvalid())
1015       return ExprError();
1016     return Comma.get();
1017   }
1018 
1019   if (!getLangOpts().CPlusPlus &&
1020       RequireCompleteType(E->getExprLoc(), E->getType(),
1021                           diag::err_call_incomplete_argument))
1022     return ExprError();
1023 
1024   return E;
1025 }
1026 
1027 /// Converts an integer to complex float type.  Helper function of
1028 /// UsualArithmeticConversions()
1029 ///
1030 /// \return false if the integer expression is an integer type and is
1031 /// successfully converted to the complex type.
1032 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1033                                                   ExprResult &ComplexExpr,
1034                                                   QualType IntTy,
1035                                                   QualType ComplexTy,
1036                                                   bool SkipCast) {
1037   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1038   if (SkipCast) return false;
1039   if (IntTy->isIntegerType()) {
1040     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1041     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1042     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1043                                   CK_FloatingRealToComplex);
1044   } else {
1045     assert(IntTy->isComplexIntegerType());
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1047                                   CK_IntegralComplexToFloatingComplex);
1048   }
1049   return false;
1050 }
1051 
1052 /// Handle arithmetic conversion with complex types.  Helper function of
1053 /// UsualArithmeticConversions()
1054 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1055                                              ExprResult &RHS, QualType LHSType,
1056                                              QualType RHSType,
1057                                              bool IsCompAssign) {
1058   // if we have an integer operand, the result is the complex type.
1059   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1060                                              /*skipCast*/false))
1061     return LHSType;
1062   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1063                                              /*skipCast*/IsCompAssign))
1064     return RHSType;
1065 
1066   // This handles complex/complex, complex/float, or float/complex.
1067   // When both operands are complex, the shorter operand is converted to the
1068   // type of the longer, and that is the type of the result. This corresponds
1069   // to what is done when combining two real floating-point operands.
1070   // The fun begins when size promotion occur across type domains.
1071   // From H&S 6.3.4: When one operand is complex and the other is a real
1072   // floating-point type, the less precise type is converted, within it's
1073   // real or complex domain, to the precision of the other type. For example,
1074   // when combining a "long double" with a "double _Complex", the
1075   // "double _Complex" is promoted to "long double _Complex".
1076 
1077   // Compute the rank of the two types, regardless of whether they are complex.
1078   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1079 
1080   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1081   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1082   QualType LHSElementType =
1083       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1084   QualType RHSElementType =
1085       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1086 
1087   QualType ResultType = S.Context.getComplexType(LHSElementType);
1088   if (Order < 0) {
1089     // Promote the precision of the LHS if not an assignment.
1090     ResultType = S.Context.getComplexType(RHSElementType);
1091     if (!IsCompAssign) {
1092       if (LHSComplexType)
1093         LHS =
1094             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1095       else
1096         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1097     }
1098   } else if (Order > 0) {
1099     // Promote the precision of the RHS.
1100     if (RHSComplexType)
1101       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1102     else
1103       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1104   }
1105   return ResultType;
1106 }
1107 
1108 /// Handle arithmetic conversion from integer to float.  Helper function
1109 /// of UsualArithmeticConversions()
1110 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1111                                            ExprResult &IntExpr,
1112                                            QualType FloatTy, QualType IntTy,
1113                                            bool ConvertFloat, bool ConvertInt) {
1114   if (IntTy->isIntegerType()) {
1115     if (ConvertInt)
1116       // Convert intExpr to the lhs floating point type.
1117       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1118                                     CK_IntegralToFloating);
1119     return FloatTy;
1120   }
1121 
1122   // Convert both sides to the appropriate complex float.
1123   assert(IntTy->isComplexIntegerType());
1124   QualType result = S.Context.getComplexType(FloatTy);
1125 
1126   // _Complex int -> _Complex float
1127   if (ConvertInt)
1128     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1129                                   CK_IntegralComplexToFloatingComplex);
1130 
1131   // float -> _Complex float
1132   if (ConvertFloat)
1133     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1134                                     CK_FloatingRealToComplex);
1135 
1136   return result;
1137 }
1138 
1139 /// Handle arithmethic conversion with floating point types.  Helper
1140 /// function of UsualArithmeticConversions()
1141 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1142                                       ExprResult &RHS, QualType LHSType,
1143                                       QualType RHSType, bool IsCompAssign) {
1144   bool LHSFloat = LHSType->isRealFloatingType();
1145   bool RHSFloat = RHSType->isRealFloatingType();
1146 
1147   // N1169 4.1.4: If one of the operands has a floating type and the other
1148   //              operand has a fixed-point type, the fixed-point operand
1149   //              is converted to the floating type [...]
1150   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1151     if (LHSFloat)
1152       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1153     else if (!IsCompAssign)
1154       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1155     return LHSFloat ? LHSType : RHSType;
1156   }
1157 
1158   // If we have two real floating types, convert the smaller operand
1159   // to the bigger result.
1160   if (LHSFloat && RHSFloat) {
1161     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1162     if (order > 0) {
1163       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1164       return LHSType;
1165     }
1166 
1167     assert(order < 0 && "illegal float comparison");
1168     if (!IsCompAssign)
1169       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1170     return RHSType;
1171   }
1172 
1173   if (LHSFloat) {
1174     // Half FP has to be promoted to float unless it is natively supported
1175     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1176       LHSType = S.Context.FloatTy;
1177 
1178     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1179                                       /*ConvertFloat=*/!IsCompAssign,
1180                                       /*ConvertInt=*/ true);
1181   }
1182   assert(RHSFloat);
1183   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1184                                     /*ConvertFloat=*/ true,
1185                                     /*ConvertInt=*/!IsCompAssign);
1186 }
1187 
1188 /// Diagnose attempts to convert between __float128 and long double if
1189 /// there is no support for such conversion. Helper function of
1190 /// UsualArithmeticConversions().
1191 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1192                                       QualType RHSType) {
1193   /*  No issue converting if at least one of the types is not a floating point
1194       type or the two types have the same rank.
1195   */
1196   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1197       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1198     return false;
1199 
1200   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1201          "The remaining types must be floating point types.");
1202 
1203   auto *LHSComplex = LHSType->getAs<ComplexType>();
1204   auto *RHSComplex = RHSType->getAs<ComplexType>();
1205 
1206   QualType LHSElemType = LHSComplex ?
1207     LHSComplex->getElementType() : LHSType;
1208   QualType RHSElemType = RHSComplex ?
1209     RHSComplex->getElementType() : RHSType;
1210 
1211   // No issue if the two types have the same representation
1212   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1213       &S.Context.getFloatTypeSemantics(RHSElemType))
1214     return false;
1215 
1216   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1217                                 RHSElemType == S.Context.LongDoubleTy);
1218   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1219                             RHSElemType == S.Context.Float128Ty);
1220 
1221   // We've handled the situation where __float128 and long double have the same
1222   // representation. We allow all conversions for all possible long double types
1223   // except PPC's double double.
1224   return Float128AndLongDouble &&
1225     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1226      &llvm::APFloat::PPCDoubleDouble());
1227 }
1228 
1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1230 
1231 namespace {
1232 /// These helper callbacks are placed in an anonymous namespace to
1233 /// permit their use as function template parameters.
1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1235   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1236 }
1237 
1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1239   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1240                              CK_IntegralComplexCast);
1241 }
1242 }
1243 
1244 /// Handle integer arithmetic conversions.  Helper function of
1245 /// UsualArithmeticConversions()
1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1248                                         ExprResult &RHS, QualType LHSType,
1249                                         QualType RHSType, bool IsCompAssign) {
1250   // The rules for this case are in C99 6.3.1.8
1251   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254   if (LHSSigned == RHSSigned) {
1255     // Same signedness; use the higher-ranked type
1256     if (order >= 0) {
1257       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258       return LHSType;
1259     } else if (!IsCompAssign)
1260       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261     return RHSType;
1262   } else if (order != (LHSSigned ? 1 : -1)) {
1263     // The unsigned type has greater than or equal rank to the
1264     // signed type, so use the unsigned type
1265     if (RHSSigned) {
1266       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267       return LHSType;
1268     } else if (!IsCompAssign)
1269       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270     return RHSType;
1271   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272     // The two types are different widths; if we are here, that
1273     // means the signed type is larger than the unsigned type, so
1274     // use the signed type.
1275     if (LHSSigned) {
1276       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277       return LHSType;
1278     } else if (!IsCompAssign)
1279       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280     return RHSType;
1281   } else {
1282     // The signed type is higher-ranked than the unsigned type,
1283     // but isn't actually any bigger (like unsigned int and long
1284     // on most 32-bit systems).  Use the unsigned type corresponding
1285     // to the signed type.
1286     QualType result =
1287       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288     RHS = (*doRHSCast)(S, RHS.get(), result);
1289     if (!IsCompAssign)
1290       LHS = (*doLHSCast)(S, LHS.get(), result);
1291     return result;
1292   }
1293 }
1294 
1295 /// Handle conversions with GCC complex int extension.  Helper function
1296 /// of UsualArithmeticConversions()
1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1298                                            ExprResult &RHS, QualType LHSType,
1299                                            QualType RHSType,
1300                                            bool IsCompAssign) {
1301   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1302   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1303 
1304   if (LHSComplexInt && RHSComplexInt) {
1305     QualType LHSEltType = LHSComplexInt->getElementType();
1306     QualType RHSEltType = RHSComplexInt->getElementType();
1307     QualType ScalarType =
1308       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1309         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1310 
1311     return S.Context.getComplexType(ScalarType);
1312   }
1313 
1314   if (LHSComplexInt) {
1315     QualType LHSEltType = LHSComplexInt->getElementType();
1316     QualType ScalarType =
1317       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1318         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1319     QualType ComplexType = S.Context.getComplexType(ScalarType);
1320     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1321                               CK_IntegralRealToComplex);
1322 
1323     return ComplexType;
1324   }
1325 
1326   assert(RHSComplexInt);
1327 
1328   QualType RHSEltType = RHSComplexInt->getElementType();
1329   QualType ScalarType =
1330     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1331       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1332   QualType ComplexType = S.Context.getComplexType(ScalarType);
1333 
1334   if (!IsCompAssign)
1335     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1336                               CK_IntegralRealToComplex);
1337   return ComplexType;
1338 }
1339 
1340 /// Return the rank of a given fixed point or integer type. The value itself
1341 /// doesn't matter, but the values must be increasing with proper increasing
1342 /// rank as described in N1169 4.1.1.
1343 static unsigned GetFixedPointRank(QualType Ty) {
1344   const auto *BTy = Ty->getAs<BuiltinType>();
1345   assert(BTy && "Expected a builtin type.");
1346 
1347   switch (BTy->getKind()) {
1348   case BuiltinType::ShortFract:
1349   case BuiltinType::UShortFract:
1350   case BuiltinType::SatShortFract:
1351   case BuiltinType::SatUShortFract:
1352     return 1;
1353   case BuiltinType::Fract:
1354   case BuiltinType::UFract:
1355   case BuiltinType::SatFract:
1356   case BuiltinType::SatUFract:
1357     return 2;
1358   case BuiltinType::LongFract:
1359   case BuiltinType::ULongFract:
1360   case BuiltinType::SatLongFract:
1361   case BuiltinType::SatULongFract:
1362     return 3;
1363   case BuiltinType::ShortAccum:
1364   case BuiltinType::UShortAccum:
1365   case BuiltinType::SatShortAccum:
1366   case BuiltinType::SatUShortAccum:
1367     return 4;
1368   case BuiltinType::Accum:
1369   case BuiltinType::UAccum:
1370   case BuiltinType::SatAccum:
1371   case BuiltinType::SatUAccum:
1372     return 5;
1373   case BuiltinType::LongAccum:
1374   case BuiltinType::ULongAccum:
1375   case BuiltinType::SatLongAccum:
1376   case BuiltinType::SatULongAccum:
1377     return 6;
1378   default:
1379     if (BTy->isInteger())
1380       return 0;
1381     llvm_unreachable("Unexpected fixed point or integer type");
1382   }
1383 }
1384 
1385 /// handleFixedPointConversion - Fixed point operations between fixed
1386 /// point types and integers or other fixed point types do not fall under
1387 /// usual arithmetic conversion since these conversions could result in loss
1388 /// of precsision (N1169 4.1.4). These operations should be calculated with
1389 /// the full precision of their result type (N1169 4.1.6.2.1).
1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1391                                            QualType RHSTy) {
1392   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1393          "Expected at least one of the operands to be a fixed point type");
1394   assert((LHSTy->isFixedPointOrIntegerType() ||
1395           RHSTy->isFixedPointOrIntegerType()) &&
1396          "Special fixed point arithmetic operation conversions are only "
1397          "applied to ints or other fixed point types");
1398 
1399   // If one operand has signed fixed-point type and the other operand has
1400   // unsigned fixed-point type, then the unsigned fixed-point operand is
1401   // converted to its corresponding signed fixed-point type and the resulting
1402   // type is the type of the converted operand.
1403   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1404     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1405   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1406     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1407 
1408   // The result type is the type with the highest rank, whereby a fixed-point
1409   // conversion rank is always greater than an integer conversion rank; if the
1410   // type of either of the operands is a saturating fixedpoint type, the result
1411   // type shall be the saturating fixed-point type corresponding to the type
1412   // with the highest rank; the resulting value is converted (taking into
1413   // account rounding and overflow) to the precision of the resulting type.
1414   // Same ranks between signed and unsigned types are resolved earlier, so both
1415   // types are either signed or both unsigned at this point.
1416   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1417   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1418 
1419   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1420 
1421   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1422     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1423 
1424   return ResultTy;
1425 }
1426 
1427 /// Check that the usual arithmetic conversions can be performed on this pair of
1428 /// expressions that might be of enumeration type.
1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1430                                            SourceLocation Loc,
1431                                            Sema::ArithConvKind ACK) {
1432   // C++2a [expr.arith.conv]p1:
1433   //   If one operand is of enumeration type and the other operand is of a
1434   //   different enumeration type or a floating-point type, this behavior is
1435   //   deprecated ([depr.arith.conv.enum]).
1436   //
1437   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1438   // Eventually we will presumably reject these cases (in C++23 onwards?).
1439   QualType L = LHS->getType(), R = RHS->getType();
1440   bool LEnum = L->isUnscopedEnumerationType(),
1441        REnum = R->isUnscopedEnumerationType();
1442   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1443   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1444       (REnum && L->isFloatingType())) {
1445     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1446                     ? diag::warn_arith_conv_enum_float_cxx20
1447                     : diag::warn_arith_conv_enum_float)
1448         << LHS->getSourceRange() << RHS->getSourceRange()
1449         << (int)ACK << LEnum << L << R;
1450   } else if (!IsCompAssign && LEnum && REnum &&
1451              !S.Context.hasSameUnqualifiedType(L, R)) {
1452     unsigned DiagID;
1453     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1454         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1455       // If either enumeration type is unnamed, it's less likely that the
1456       // user cares about this, but this situation is still deprecated in
1457       // C++2a. Use a different warning group.
1458       DiagID = S.getLangOpts().CPlusPlus20
1459                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1460                     : diag::warn_arith_conv_mixed_anon_enum_types;
1461     } else if (ACK == Sema::ACK_Conditional) {
1462       // Conditional expressions are separated out because they have
1463       // historically had a different warning flag.
1464       DiagID = S.getLangOpts().CPlusPlus20
1465                    ? diag::warn_conditional_mixed_enum_types_cxx20
1466                    : diag::warn_conditional_mixed_enum_types;
1467     } else if (ACK == Sema::ACK_Comparison) {
1468       // Comparison expressions are separated out because they have
1469       // historically had a different warning flag.
1470       DiagID = S.getLangOpts().CPlusPlus20
1471                    ? diag::warn_comparison_mixed_enum_types_cxx20
1472                    : diag::warn_comparison_mixed_enum_types;
1473     } else {
1474       DiagID = S.getLangOpts().CPlusPlus20
1475                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1476                    : diag::warn_arith_conv_mixed_enum_types;
1477     }
1478     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1479                         << (int)ACK << L << R;
1480   }
1481 }
1482 
1483 /// UsualArithmeticConversions - Performs various conversions that are common to
1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1485 /// routine returns the first non-arithmetic type found. The client is
1486 /// responsible for emitting appropriate error diagnostics.
1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1488                                           SourceLocation Loc,
1489                                           ArithConvKind ACK) {
1490   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1491 
1492   if (ACK != ACK_CompAssign) {
1493     LHS = UsualUnaryConversions(LHS.get());
1494     if (LHS.isInvalid())
1495       return QualType();
1496   }
1497 
1498   RHS = UsualUnaryConversions(RHS.get());
1499   if (RHS.isInvalid())
1500     return QualType();
1501 
1502   // For conversion purposes, we ignore any qualifiers.
1503   // For example, "const float" and "float" are equivalent.
1504   QualType LHSType =
1505     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1506   QualType RHSType =
1507     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1508 
1509   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1510   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1511     LHSType = AtomicLHS->getValueType();
1512 
1513   // If both types are identical, no conversion is needed.
1514   if (LHSType == RHSType)
1515     return LHSType;
1516 
1517   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1518   // The caller can deal with this (e.g. pointer + int).
1519   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1520     return QualType();
1521 
1522   // Apply unary and bitfield promotions to the LHS's type.
1523   QualType LHSUnpromotedType = LHSType;
1524   if (LHSType->isPromotableIntegerType())
1525     LHSType = Context.getPromotedIntegerType(LHSType);
1526   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1527   if (!LHSBitfieldPromoteTy.isNull())
1528     LHSType = LHSBitfieldPromoteTy;
1529   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1530     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1531 
1532   // If both types are identical, no conversion is needed.
1533   if (LHSType == RHSType)
1534     return LHSType;
1535 
1536   // ExtInt types aren't subject to conversions between them or normal integers,
1537   // so this fails.
1538   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1539     return QualType();
1540 
1541   // At this point, we have two different arithmetic types.
1542 
1543   // Diagnose attempts to convert between __float128 and long double where
1544   // such conversions currently can't be handled.
1545   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1546     return QualType();
1547 
1548   // Handle complex types first (C99 6.3.1.8p1).
1549   if (LHSType->isComplexType() || RHSType->isComplexType())
1550     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1551                                         ACK == ACK_CompAssign);
1552 
1553   // Now handle "real" floating types (i.e. float, double, long double).
1554   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1555     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1556                                  ACK == ACK_CompAssign);
1557 
1558   // Handle GCC complex int extension.
1559   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1560     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1561                                       ACK == ACK_CompAssign);
1562 
1563   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1564     return handleFixedPointConversion(*this, LHSType, RHSType);
1565 
1566   // Finally, we have two differing integer types.
1567   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1568            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1569 }
1570 
1571 //===----------------------------------------------------------------------===//
1572 //  Semantic Analysis for various Expression Types
1573 //===----------------------------------------------------------------------===//
1574 
1575 
1576 ExprResult
1577 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1578                                 SourceLocation DefaultLoc,
1579                                 SourceLocation RParenLoc,
1580                                 Expr *ControllingExpr,
1581                                 ArrayRef<ParsedType> ArgTypes,
1582                                 ArrayRef<Expr *> ArgExprs) {
1583   unsigned NumAssocs = ArgTypes.size();
1584   assert(NumAssocs == ArgExprs.size());
1585 
1586   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1587   for (unsigned i = 0; i < NumAssocs; ++i) {
1588     if (ArgTypes[i])
1589       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1590     else
1591       Types[i] = nullptr;
1592   }
1593 
1594   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1595                                              ControllingExpr,
1596                                              llvm::makeArrayRef(Types, NumAssocs),
1597                                              ArgExprs);
1598   delete [] Types;
1599   return ER;
1600 }
1601 
1602 ExprResult
1603 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1604                                  SourceLocation DefaultLoc,
1605                                  SourceLocation RParenLoc,
1606                                  Expr *ControllingExpr,
1607                                  ArrayRef<TypeSourceInfo *> Types,
1608                                  ArrayRef<Expr *> Exprs) {
1609   unsigned NumAssocs = Types.size();
1610   assert(NumAssocs == Exprs.size());
1611 
1612   // Decay and strip qualifiers for the controlling expression type, and handle
1613   // placeholder type replacement. See committee discussion from WG14 DR423.
1614   {
1615     EnterExpressionEvaluationContext Unevaluated(
1616         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1617     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1618     if (R.isInvalid())
1619       return ExprError();
1620     ControllingExpr = R.get();
1621   }
1622 
1623   // The controlling expression is an unevaluated operand, so side effects are
1624   // likely unintended.
1625   if (!inTemplateInstantiation() &&
1626       ControllingExpr->HasSideEffects(Context, false))
1627     Diag(ControllingExpr->getExprLoc(),
1628          diag::warn_side_effects_unevaluated_context);
1629 
1630   bool TypeErrorFound = false,
1631        IsResultDependent = ControllingExpr->isTypeDependent(),
1632        ContainsUnexpandedParameterPack
1633          = ControllingExpr->containsUnexpandedParameterPack();
1634 
1635   for (unsigned i = 0; i < NumAssocs; ++i) {
1636     if (Exprs[i]->containsUnexpandedParameterPack())
1637       ContainsUnexpandedParameterPack = true;
1638 
1639     if (Types[i]) {
1640       if (Types[i]->getType()->containsUnexpandedParameterPack())
1641         ContainsUnexpandedParameterPack = true;
1642 
1643       if (Types[i]->getType()->isDependentType()) {
1644         IsResultDependent = true;
1645       } else {
1646         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1647         // complete object type other than a variably modified type."
1648         unsigned D = 0;
1649         if (Types[i]->getType()->isIncompleteType())
1650           D = diag::err_assoc_type_incomplete;
1651         else if (!Types[i]->getType()->isObjectType())
1652           D = diag::err_assoc_type_nonobject;
1653         else if (Types[i]->getType()->isVariablyModifiedType())
1654           D = diag::err_assoc_type_variably_modified;
1655 
1656         if (D != 0) {
1657           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1658             << Types[i]->getTypeLoc().getSourceRange()
1659             << Types[i]->getType();
1660           TypeErrorFound = true;
1661         }
1662 
1663         // C11 6.5.1.1p2 "No two generic associations in the same generic
1664         // selection shall specify compatible types."
1665         for (unsigned j = i+1; j < NumAssocs; ++j)
1666           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1667               Context.typesAreCompatible(Types[i]->getType(),
1668                                          Types[j]->getType())) {
1669             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1670                  diag::err_assoc_compatible_types)
1671               << Types[j]->getTypeLoc().getSourceRange()
1672               << Types[j]->getType()
1673               << Types[i]->getType();
1674             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1675                  diag::note_compat_assoc)
1676               << Types[i]->getTypeLoc().getSourceRange()
1677               << Types[i]->getType();
1678             TypeErrorFound = true;
1679           }
1680       }
1681     }
1682   }
1683   if (TypeErrorFound)
1684     return ExprError();
1685 
1686   // If we determined that the generic selection is result-dependent, don't
1687   // try to compute the result expression.
1688   if (IsResultDependent)
1689     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1690                                         Exprs, DefaultLoc, RParenLoc,
1691                                         ContainsUnexpandedParameterPack);
1692 
1693   SmallVector<unsigned, 1> CompatIndices;
1694   unsigned DefaultIndex = -1U;
1695   for (unsigned i = 0; i < NumAssocs; ++i) {
1696     if (!Types[i])
1697       DefaultIndex = i;
1698     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1699                                         Types[i]->getType()))
1700       CompatIndices.push_back(i);
1701   }
1702 
1703   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1704   // type compatible with at most one of the types named in its generic
1705   // association list."
1706   if (CompatIndices.size() > 1) {
1707     // We strip parens here because the controlling expression is typically
1708     // parenthesized in macro definitions.
1709     ControllingExpr = ControllingExpr->IgnoreParens();
1710     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1711         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1712         << (unsigned)CompatIndices.size();
1713     for (unsigned I : CompatIndices) {
1714       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1715            diag::note_compat_assoc)
1716         << Types[I]->getTypeLoc().getSourceRange()
1717         << Types[I]->getType();
1718     }
1719     return ExprError();
1720   }
1721 
1722   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1723   // its controlling expression shall have type compatible with exactly one of
1724   // the types named in its generic association list."
1725   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1726     // We strip parens here because the controlling expression is typically
1727     // parenthesized in macro definitions.
1728     ControllingExpr = ControllingExpr->IgnoreParens();
1729     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1730         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1731     return ExprError();
1732   }
1733 
1734   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1735   // type name that is compatible with the type of the controlling expression,
1736   // then the result expression of the generic selection is the expression
1737   // in that generic association. Otherwise, the result expression of the
1738   // generic selection is the expression in the default generic association."
1739   unsigned ResultIndex =
1740     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1741 
1742   return GenericSelectionExpr::Create(
1743       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1744       ContainsUnexpandedParameterPack, ResultIndex);
1745 }
1746 
1747 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1748 /// location of the token and the offset of the ud-suffix within it.
1749 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1750                                      unsigned Offset) {
1751   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1752                                         S.getLangOpts());
1753 }
1754 
1755 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1756 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1757 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1758                                                  IdentifierInfo *UDSuffix,
1759                                                  SourceLocation UDSuffixLoc,
1760                                                  ArrayRef<Expr*> Args,
1761                                                  SourceLocation LitEndLoc) {
1762   assert(Args.size() <= 2 && "too many arguments for literal operator");
1763 
1764   QualType ArgTy[2];
1765   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1766     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1767     if (ArgTy[ArgIdx]->isArrayType())
1768       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1769   }
1770 
1771   DeclarationName OpName =
1772     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1773   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1774   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1775 
1776   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1777   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1778                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1779                               /*AllowStringTemplatePack*/ false,
1780                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1781     return ExprError();
1782 
1783   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1784 }
1785 
1786 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1787 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1788 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1789 /// multiple tokens.  However, the common case is that StringToks points to one
1790 /// string.
1791 ///
1792 ExprResult
1793 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1794   assert(!StringToks.empty() && "Must have at least one string!");
1795 
1796   StringLiteralParser Literal(StringToks, PP);
1797   if (Literal.hadError)
1798     return ExprError();
1799 
1800   SmallVector<SourceLocation, 4> StringTokLocs;
1801   for (const Token &Tok : StringToks)
1802     StringTokLocs.push_back(Tok.getLocation());
1803 
1804   QualType CharTy = Context.CharTy;
1805   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1806   if (Literal.isWide()) {
1807     CharTy = Context.getWideCharType();
1808     Kind = StringLiteral::Wide;
1809   } else if (Literal.isUTF8()) {
1810     if (getLangOpts().Char8)
1811       CharTy = Context.Char8Ty;
1812     Kind = StringLiteral::UTF8;
1813   } else if (Literal.isUTF16()) {
1814     CharTy = Context.Char16Ty;
1815     Kind = StringLiteral::UTF16;
1816   } else if (Literal.isUTF32()) {
1817     CharTy = Context.Char32Ty;
1818     Kind = StringLiteral::UTF32;
1819   } else if (Literal.isPascal()) {
1820     CharTy = Context.UnsignedCharTy;
1821   }
1822 
1823   // Warn on initializing an array of char from a u8 string literal; this
1824   // becomes ill-formed in C++2a.
1825   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1826       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1827     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1828 
1829     // Create removals for all 'u8' prefixes in the string literal(s). This
1830     // ensures C++2a compatibility (but may change the program behavior when
1831     // built by non-Clang compilers for which the execution character set is
1832     // not always UTF-8).
1833     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1834     SourceLocation RemovalDiagLoc;
1835     for (const Token &Tok : StringToks) {
1836       if (Tok.getKind() == tok::utf8_string_literal) {
1837         if (RemovalDiagLoc.isInvalid())
1838           RemovalDiagLoc = Tok.getLocation();
1839         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1840             Tok.getLocation(),
1841             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1842                                            getSourceManager(), getLangOpts())));
1843       }
1844     }
1845     Diag(RemovalDiagLoc, RemovalDiag);
1846   }
1847 
1848   QualType StrTy =
1849       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1850 
1851   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1852   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1853                                              Kind, Literal.Pascal, StrTy,
1854                                              &StringTokLocs[0],
1855                                              StringTokLocs.size());
1856   if (Literal.getUDSuffix().empty())
1857     return Lit;
1858 
1859   // We're building a user-defined literal.
1860   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1861   SourceLocation UDSuffixLoc =
1862     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1863                    Literal.getUDSuffixOffset());
1864 
1865   // Make sure we're allowed user-defined literals here.
1866   if (!UDLScope)
1867     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1868 
1869   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1870   //   operator "" X (str, len)
1871   QualType SizeType = Context.getSizeType();
1872 
1873   DeclarationName OpName =
1874     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1875   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1876   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1877 
1878   QualType ArgTy[] = {
1879     Context.getArrayDecayedType(StrTy), SizeType
1880   };
1881 
1882   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1883   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1884                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1885                                 /*AllowStringTemplatePack*/ true,
1886                                 /*DiagnoseMissing*/ true, Lit)) {
1887 
1888   case LOLR_Cooked: {
1889     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1890     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1891                                                     StringTokLocs[0]);
1892     Expr *Args[] = { Lit, LenArg };
1893 
1894     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1895   }
1896 
1897   case LOLR_Template: {
1898     TemplateArgumentListInfo ExplicitArgs;
1899     TemplateArgument Arg(Lit);
1900     TemplateArgumentLocInfo ArgInfo(Lit);
1901     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1902     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1903                                     &ExplicitArgs);
1904   }
1905 
1906   case LOLR_StringTemplatePack: {
1907     TemplateArgumentListInfo ExplicitArgs;
1908 
1909     unsigned CharBits = Context.getIntWidth(CharTy);
1910     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1911     llvm::APSInt Value(CharBits, CharIsUnsigned);
1912 
1913     TemplateArgument TypeArg(CharTy);
1914     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1915     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1916 
1917     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1918       Value = Lit->getCodeUnit(I);
1919       TemplateArgument Arg(Context, Value, CharTy);
1920       TemplateArgumentLocInfo ArgInfo;
1921       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1922     }
1923     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1924                                     &ExplicitArgs);
1925   }
1926   case LOLR_Raw:
1927   case LOLR_ErrorNoDiagnostic:
1928     llvm_unreachable("unexpected literal operator lookup result");
1929   case LOLR_Error:
1930     return ExprError();
1931   }
1932   llvm_unreachable("unexpected literal operator lookup result");
1933 }
1934 
1935 DeclRefExpr *
1936 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1937                        SourceLocation Loc,
1938                        const CXXScopeSpec *SS) {
1939   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1940   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1941 }
1942 
1943 DeclRefExpr *
1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1945                        const DeclarationNameInfo &NameInfo,
1946                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1947                        SourceLocation TemplateKWLoc,
1948                        const TemplateArgumentListInfo *TemplateArgs) {
1949   NestedNameSpecifierLoc NNS =
1950       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1951   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1952                           TemplateArgs);
1953 }
1954 
1955 // CUDA/HIP: Check whether a captured reference variable is referencing a
1956 // host variable in a device or host device lambda.
1957 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1958                                                             VarDecl *VD) {
1959   if (!S.getLangOpts().CUDA || !VD->hasInit())
1960     return false;
1961   assert(VD->getType()->isReferenceType());
1962 
1963   // Check whether the reference variable is referencing a host variable.
1964   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1965   if (!DRE)
1966     return false;
1967   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1968   if (!Referee || !Referee->hasGlobalStorage() ||
1969       Referee->hasAttr<CUDADeviceAttr>())
1970     return false;
1971 
1972   // Check whether the current function is a device or host device lambda.
1973   // Check whether the reference variable is a capture by getDeclContext()
1974   // since refersToEnclosingVariableOrCapture() is not ready at this point.
1975   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1976   if (MD && MD->getParent()->isLambda() &&
1977       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1978       VD->getDeclContext() != MD)
1979     return true;
1980 
1981   return false;
1982 }
1983 
1984 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1985   // A declaration named in an unevaluated operand never constitutes an odr-use.
1986   if (isUnevaluatedContext())
1987     return NOUR_Unevaluated;
1988 
1989   // C++2a [basic.def.odr]p4:
1990   //   A variable x whose name appears as a potentially-evaluated expression e
1991   //   is odr-used by e unless [...] x is a reference that is usable in
1992   //   constant expressions.
1993   // CUDA/HIP:
1994   //   If a reference variable referencing a host variable is captured in a
1995   //   device or host device lambda, the value of the referee must be copied
1996   //   to the capture and the reference variable must be treated as odr-use
1997   //   since the value of the referee is not known at compile time and must
1998   //   be loaded from the captured.
1999   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2000     if (VD->getType()->isReferenceType() &&
2001         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2002         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2003         VD->isUsableInConstantExpressions(Context))
2004       return NOUR_Constant;
2005   }
2006 
2007   // All remaining non-variable cases constitute an odr-use. For variables, we
2008   // need to wait and see how the expression is used.
2009   return NOUR_None;
2010 }
2011 
2012 /// BuildDeclRefExpr - Build an expression that references a
2013 /// declaration that does not require a closure capture.
2014 DeclRefExpr *
2015 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2016                        const DeclarationNameInfo &NameInfo,
2017                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2018                        SourceLocation TemplateKWLoc,
2019                        const TemplateArgumentListInfo *TemplateArgs) {
2020   bool RefersToCapturedVariable =
2021       isa<VarDecl>(D) &&
2022       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2023 
2024   DeclRefExpr *E = DeclRefExpr::Create(
2025       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2026       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2027   MarkDeclRefReferenced(E);
2028 
2029   // C++ [except.spec]p17:
2030   //   An exception-specification is considered to be needed when:
2031   //   - in an expression, the function is the unique lookup result or
2032   //     the selected member of a set of overloaded functions.
2033   //
2034   // We delay doing this until after we've built the function reference and
2035   // marked it as used so that:
2036   //  a) if the function is defaulted, we get errors from defining it before /
2037   //     instead of errors from computing its exception specification, and
2038   //  b) if the function is a defaulted comparison, we can use the body we
2039   //     build when defining it as input to the exception specification
2040   //     computation rather than computing a new body.
2041   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2042     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2043       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2044         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2045     }
2046   }
2047 
2048   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2049       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2050       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2051     getCurFunction()->recordUseOfWeak(E);
2052 
2053   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2054   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2055     FD = IFD->getAnonField();
2056   if (FD) {
2057     UnusedPrivateFields.remove(FD);
2058     // Just in case we're building an illegal pointer-to-member.
2059     if (FD->isBitField())
2060       E->setObjectKind(OK_BitField);
2061   }
2062 
2063   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2064   // designates a bit-field.
2065   if (auto *BD = dyn_cast<BindingDecl>(D))
2066     if (auto *BE = BD->getBinding())
2067       E->setObjectKind(BE->getObjectKind());
2068 
2069   return E;
2070 }
2071 
2072 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2073 /// possibly a list of template arguments.
2074 ///
2075 /// If this produces template arguments, it is permitted to call
2076 /// DecomposeTemplateName.
2077 ///
2078 /// This actually loses a lot of source location information for
2079 /// non-standard name kinds; we should consider preserving that in
2080 /// some way.
2081 void
2082 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2083                              TemplateArgumentListInfo &Buffer,
2084                              DeclarationNameInfo &NameInfo,
2085                              const TemplateArgumentListInfo *&TemplateArgs) {
2086   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2087     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2088     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2089 
2090     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2091                                        Id.TemplateId->NumArgs);
2092     translateTemplateArguments(TemplateArgsPtr, Buffer);
2093 
2094     TemplateName TName = Id.TemplateId->Template.get();
2095     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2096     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2097     TemplateArgs = &Buffer;
2098   } else {
2099     NameInfo = GetNameFromUnqualifiedId(Id);
2100     TemplateArgs = nullptr;
2101   }
2102 }
2103 
2104 static void emitEmptyLookupTypoDiagnostic(
2105     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2106     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2107     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2108   DeclContext *Ctx =
2109       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2110   if (!TC) {
2111     // Emit a special diagnostic for failed member lookups.
2112     // FIXME: computing the declaration context might fail here (?)
2113     if (Ctx)
2114       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2115                                                  << SS.getRange();
2116     else
2117       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2118     return;
2119   }
2120 
2121   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2122   bool DroppedSpecifier =
2123       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2124   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2125                         ? diag::note_implicit_param_decl
2126                         : diag::note_previous_decl;
2127   if (!Ctx)
2128     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2129                          SemaRef.PDiag(NoteID));
2130   else
2131     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2132                                  << Typo << Ctx << DroppedSpecifier
2133                                  << SS.getRange(),
2134                          SemaRef.PDiag(NoteID));
2135 }
2136 
2137 /// Diagnose a lookup that found results in an enclosing class during error
2138 /// recovery. This usually indicates that the results were found in a dependent
2139 /// base class that could not be searched as part of a template definition.
2140 /// Always issues a diagnostic (though this may be only a warning in MS
2141 /// compatibility mode).
2142 ///
2143 /// Return \c true if the error is unrecoverable, or \c false if the caller
2144 /// should attempt to recover using these lookup results.
2145 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2146   // During a default argument instantiation the CurContext points
2147   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2148   // function parameter list, hence add an explicit check.
2149   bool isDefaultArgument =
2150       !CodeSynthesisContexts.empty() &&
2151       CodeSynthesisContexts.back().Kind ==
2152           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2153   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2154   bool isInstance = CurMethod && CurMethod->isInstance() &&
2155                     R.getNamingClass() == CurMethod->getParent() &&
2156                     !isDefaultArgument;
2157 
2158   // There are two ways we can find a class-scope declaration during template
2159   // instantiation that we did not find in the template definition: if it is a
2160   // member of a dependent base class, or if it is declared after the point of
2161   // use in the same class. Distinguish these by comparing the class in which
2162   // the member was found to the naming class of the lookup.
2163   unsigned DiagID = diag::err_found_in_dependent_base;
2164   unsigned NoteID = diag::note_member_declared_at;
2165   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2166     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2167                                       : diag::err_found_later_in_class;
2168   } else if (getLangOpts().MSVCCompat) {
2169     DiagID = diag::ext_found_in_dependent_base;
2170     NoteID = diag::note_dependent_member_use;
2171   }
2172 
2173   if (isInstance) {
2174     // Give a code modification hint to insert 'this->'.
2175     Diag(R.getNameLoc(), DiagID)
2176         << R.getLookupName()
2177         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2178     CheckCXXThisCapture(R.getNameLoc());
2179   } else {
2180     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2181     // they're not shadowed).
2182     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2183   }
2184 
2185   for (NamedDecl *D : R)
2186     Diag(D->getLocation(), NoteID);
2187 
2188   // Return true if we are inside a default argument instantiation
2189   // and the found name refers to an instance member function, otherwise
2190   // the caller will try to create an implicit member call and this is wrong
2191   // for default arguments.
2192   //
2193   // FIXME: Is this special case necessary? We could allow the caller to
2194   // diagnose this.
2195   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2196     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2197     return true;
2198   }
2199 
2200   // Tell the callee to try to recover.
2201   return false;
2202 }
2203 
2204 /// Diagnose an empty lookup.
2205 ///
2206 /// \return false if new lookup candidates were found
2207 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2208                                CorrectionCandidateCallback &CCC,
2209                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2210                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2211   DeclarationName Name = R.getLookupName();
2212 
2213   unsigned diagnostic = diag::err_undeclared_var_use;
2214   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2215   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2216       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2217       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2218     diagnostic = diag::err_undeclared_use;
2219     diagnostic_suggest = diag::err_undeclared_use_suggest;
2220   }
2221 
2222   // If the original lookup was an unqualified lookup, fake an
2223   // unqualified lookup.  This is useful when (for example) the
2224   // original lookup would not have found something because it was a
2225   // dependent name.
2226   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2227   while (DC) {
2228     if (isa<CXXRecordDecl>(DC)) {
2229       LookupQualifiedName(R, DC);
2230 
2231       if (!R.empty()) {
2232         // Don't give errors about ambiguities in this lookup.
2233         R.suppressDiagnostics();
2234 
2235         // If there's a best viable function among the results, only mention
2236         // that one in the notes.
2237         OverloadCandidateSet Candidates(R.getNameLoc(),
2238                                         OverloadCandidateSet::CSK_Normal);
2239         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2240         OverloadCandidateSet::iterator Best;
2241         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2242             OR_Success) {
2243           R.clear();
2244           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2245           R.resolveKind();
2246         }
2247 
2248         return DiagnoseDependentMemberLookup(R);
2249       }
2250 
2251       R.clear();
2252     }
2253 
2254     DC = DC->getLookupParent();
2255   }
2256 
2257   // We didn't find anything, so try to correct for a typo.
2258   TypoCorrection Corrected;
2259   if (S && Out) {
2260     SourceLocation TypoLoc = R.getNameLoc();
2261     assert(!ExplicitTemplateArgs &&
2262            "Diagnosing an empty lookup with explicit template args!");
2263     *Out = CorrectTypoDelayed(
2264         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2265         [=](const TypoCorrection &TC) {
2266           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2267                                         diagnostic, diagnostic_suggest);
2268         },
2269         nullptr, CTK_ErrorRecovery);
2270     if (*Out)
2271       return true;
2272   } else if (S &&
2273              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2274                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2275     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2276     bool DroppedSpecifier =
2277         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2278     R.setLookupName(Corrected.getCorrection());
2279 
2280     bool AcceptableWithRecovery = false;
2281     bool AcceptableWithoutRecovery = false;
2282     NamedDecl *ND = Corrected.getFoundDecl();
2283     if (ND) {
2284       if (Corrected.isOverloaded()) {
2285         OverloadCandidateSet OCS(R.getNameLoc(),
2286                                  OverloadCandidateSet::CSK_Normal);
2287         OverloadCandidateSet::iterator Best;
2288         for (NamedDecl *CD : Corrected) {
2289           if (FunctionTemplateDecl *FTD =
2290                    dyn_cast<FunctionTemplateDecl>(CD))
2291             AddTemplateOverloadCandidate(
2292                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2293                 Args, OCS);
2294           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2295             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2296               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2297                                    Args, OCS);
2298         }
2299         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2300         case OR_Success:
2301           ND = Best->FoundDecl;
2302           Corrected.setCorrectionDecl(ND);
2303           break;
2304         default:
2305           // FIXME: Arbitrarily pick the first declaration for the note.
2306           Corrected.setCorrectionDecl(ND);
2307           break;
2308         }
2309       }
2310       R.addDecl(ND);
2311       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2312         CXXRecordDecl *Record = nullptr;
2313         if (Corrected.getCorrectionSpecifier()) {
2314           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2315           Record = Ty->getAsCXXRecordDecl();
2316         }
2317         if (!Record)
2318           Record = cast<CXXRecordDecl>(
2319               ND->getDeclContext()->getRedeclContext());
2320         R.setNamingClass(Record);
2321       }
2322 
2323       auto *UnderlyingND = ND->getUnderlyingDecl();
2324       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2325                                isa<FunctionTemplateDecl>(UnderlyingND);
2326       // FIXME: If we ended up with a typo for a type name or
2327       // Objective-C class name, we're in trouble because the parser
2328       // is in the wrong place to recover. Suggest the typo
2329       // correction, but don't make it a fix-it since we're not going
2330       // to recover well anyway.
2331       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2332                                   getAsTypeTemplateDecl(UnderlyingND) ||
2333                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2334     } else {
2335       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2336       // because we aren't able to recover.
2337       AcceptableWithoutRecovery = true;
2338     }
2339 
2340     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2341       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2342                             ? diag::note_implicit_param_decl
2343                             : diag::note_previous_decl;
2344       if (SS.isEmpty())
2345         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2346                      PDiag(NoteID), AcceptableWithRecovery);
2347       else
2348         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2349                                   << Name << computeDeclContext(SS, false)
2350                                   << DroppedSpecifier << SS.getRange(),
2351                      PDiag(NoteID), AcceptableWithRecovery);
2352 
2353       // Tell the callee whether to try to recover.
2354       return !AcceptableWithRecovery;
2355     }
2356   }
2357   R.clear();
2358 
2359   // Emit a special diagnostic for failed member lookups.
2360   // FIXME: computing the declaration context might fail here (?)
2361   if (!SS.isEmpty()) {
2362     Diag(R.getNameLoc(), diag::err_no_member)
2363       << Name << computeDeclContext(SS, false)
2364       << SS.getRange();
2365     return true;
2366   }
2367 
2368   // Give up, we can't recover.
2369   Diag(R.getNameLoc(), diagnostic) << Name;
2370   return true;
2371 }
2372 
2373 /// In Microsoft mode, if we are inside a template class whose parent class has
2374 /// dependent base classes, and we can't resolve an unqualified identifier, then
2375 /// assume the identifier is a member of a dependent base class.  We can only
2376 /// recover successfully in static methods, instance methods, and other contexts
2377 /// where 'this' is available.  This doesn't precisely match MSVC's
2378 /// instantiation model, but it's close enough.
2379 static Expr *
2380 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2381                                DeclarationNameInfo &NameInfo,
2382                                SourceLocation TemplateKWLoc,
2383                                const TemplateArgumentListInfo *TemplateArgs) {
2384   // Only try to recover from lookup into dependent bases in static methods or
2385   // contexts where 'this' is available.
2386   QualType ThisType = S.getCurrentThisType();
2387   const CXXRecordDecl *RD = nullptr;
2388   if (!ThisType.isNull())
2389     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2390   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2391     RD = MD->getParent();
2392   if (!RD || !RD->hasAnyDependentBases())
2393     return nullptr;
2394 
2395   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2396   // is available, suggest inserting 'this->' as a fixit.
2397   SourceLocation Loc = NameInfo.getLoc();
2398   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2399   DB << NameInfo.getName() << RD;
2400 
2401   if (!ThisType.isNull()) {
2402     DB << FixItHint::CreateInsertion(Loc, "this->");
2403     return CXXDependentScopeMemberExpr::Create(
2404         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2405         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2406         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2407   }
2408 
2409   // Synthesize a fake NNS that points to the derived class.  This will
2410   // perform name lookup during template instantiation.
2411   CXXScopeSpec SS;
2412   auto *NNS =
2413       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2414   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2415   return DependentScopeDeclRefExpr::Create(
2416       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2417       TemplateArgs);
2418 }
2419 
2420 ExprResult
2421 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2422                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2423                         bool HasTrailingLParen, bool IsAddressOfOperand,
2424                         CorrectionCandidateCallback *CCC,
2425                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2426   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2427          "cannot be direct & operand and have a trailing lparen");
2428   if (SS.isInvalid())
2429     return ExprError();
2430 
2431   TemplateArgumentListInfo TemplateArgsBuffer;
2432 
2433   // Decompose the UnqualifiedId into the following data.
2434   DeclarationNameInfo NameInfo;
2435   const TemplateArgumentListInfo *TemplateArgs;
2436   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2437 
2438   DeclarationName Name = NameInfo.getName();
2439   IdentifierInfo *II = Name.getAsIdentifierInfo();
2440   SourceLocation NameLoc = NameInfo.getLoc();
2441 
2442   if (II && II->isEditorPlaceholder()) {
2443     // FIXME: When typed placeholders are supported we can create a typed
2444     // placeholder expression node.
2445     return ExprError();
2446   }
2447 
2448   // C++ [temp.dep.expr]p3:
2449   //   An id-expression is type-dependent if it contains:
2450   //     -- an identifier that was declared with a dependent type,
2451   //        (note: handled after lookup)
2452   //     -- a template-id that is dependent,
2453   //        (note: handled in BuildTemplateIdExpr)
2454   //     -- a conversion-function-id that specifies a dependent type,
2455   //     -- a nested-name-specifier that contains a class-name that
2456   //        names a dependent type.
2457   // Determine whether this is a member of an unknown specialization;
2458   // we need to handle these differently.
2459   bool DependentID = false;
2460   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2461       Name.getCXXNameType()->isDependentType()) {
2462     DependentID = true;
2463   } else if (SS.isSet()) {
2464     if (DeclContext *DC = computeDeclContext(SS, false)) {
2465       if (RequireCompleteDeclContext(SS, DC))
2466         return ExprError();
2467     } else {
2468       DependentID = true;
2469     }
2470   }
2471 
2472   if (DependentID)
2473     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2474                                       IsAddressOfOperand, TemplateArgs);
2475 
2476   // Perform the required lookup.
2477   LookupResult R(*this, NameInfo,
2478                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2479                      ? LookupObjCImplicitSelfParam
2480                      : LookupOrdinaryName);
2481   if (TemplateKWLoc.isValid() || TemplateArgs) {
2482     // Lookup the template name again to correctly establish the context in
2483     // which it was found. This is really unfortunate as we already did the
2484     // lookup to determine that it was a template name in the first place. If
2485     // this becomes a performance hit, we can work harder to preserve those
2486     // results until we get here but it's likely not worth it.
2487     bool MemberOfUnknownSpecialization;
2488     AssumedTemplateKind AssumedTemplate;
2489     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2490                            MemberOfUnknownSpecialization, TemplateKWLoc,
2491                            &AssumedTemplate))
2492       return ExprError();
2493 
2494     if (MemberOfUnknownSpecialization ||
2495         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2496       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2497                                         IsAddressOfOperand, TemplateArgs);
2498   } else {
2499     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2500     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2501 
2502     // If the result might be in a dependent base class, this is a dependent
2503     // id-expression.
2504     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2505       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2506                                         IsAddressOfOperand, TemplateArgs);
2507 
2508     // If this reference is in an Objective-C method, then we need to do
2509     // some special Objective-C lookup, too.
2510     if (IvarLookupFollowUp) {
2511       ExprResult E(LookupInObjCMethod(R, S, II, true));
2512       if (E.isInvalid())
2513         return ExprError();
2514 
2515       if (Expr *Ex = E.getAs<Expr>())
2516         return Ex;
2517     }
2518   }
2519 
2520   if (R.isAmbiguous())
2521     return ExprError();
2522 
2523   // This could be an implicitly declared function reference (legal in C90,
2524   // extension in C99, forbidden in C++).
2525   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2526     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2527     if (D) R.addDecl(D);
2528   }
2529 
2530   // Determine whether this name might be a candidate for
2531   // argument-dependent lookup.
2532   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2533 
2534   if (R.empty() && !ADL) {
2535     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2536       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2537                                                    TemplateKWLoc, TemplateArgs))
2538         return E;
2539     }
2540 
2541     // Don't diagnose an empty lookup for inline assembly.
2542     if (IsInlineAsmIdentifier)
2543       return ExprError();
2544 
2545     // If this name wasn't predeclared and if this is not a function
2546     // call, diagnose the problem.
2547     TypoExpr *TE = nullptr;
2548     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2549                                                        : nullptr);
2550     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2551     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2552            "Typo correction callback misconfigured");
2553     if (CCC) {
2554       // Make sure the callback knows what the typo being diagnosed is.
2555       CCC->setTypoName(II);
2556       if (SS.isValid())
2557         CCC->setTypoNNS(SS.getScopeRep());
2558     }
2559     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2560     // a template name, but we happen to have always already looked up the name
2561     // before we get here if it must be a template name.
2562     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2563                             None, &TE)) {
2564       if (TE && KeywordReplacement) {
2565         auto &State = getTypoExprState(TE);
2566         auto BestTC = State.Consumer->getNextCorrection();
2567         if (BestTC.isKeyword()) {
2568           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2569           if (State.DiagHandler)
2570             State.DiagHandler(BestTC);
2571           KeywordReplacement->startToken();
2572           KeywordReplacement->setKind(II->getTokenID());
2573           KeywordReplacement->setIdentifierInfo(II);
2574           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2575           // Clean up the state associated with the TypoExpr, since it has
2576           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2577           clearDelayedTypo(TE);
2578           // Signal that a correction to a keyword was performed by returning a
2579           // valid-but-null ExprResult.
2580           return (Expr*)nullptr;
2581         }
2582         State.Consumer->resetCorrectionStream();
2583       }
2584       return TE ? TE : ExprError();
2585     }
2586 
2587     assert(!R.empty() &&
2588            "DiagnoseEmptyLookup returned false but added no results");
2589 
2590     // If we found an Objective-C instance variable, let
2591     // LookupInObjCMethod build the appropriate expression to
2592     // reference the ivar.
2593     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2594       R.clear();
2595       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2596       // In a hopelessly buggy code, Objective-C instance variable
2597       // lookup fails and no expression will be built to reference it.
2598       if (!E.isInvalid() && !E.get())
2599         return ExprError();
2600       return E;
2601     }
2602   }
2603 
2604   // This is guaranteed from this point on.
2605   assert(!R.empty() || ADL);
2606 
2607   // Check whether this might be a C++ implicit instance member access.
2608   // C++ [class.mfct.non-static]p3:
2609   //   When an id-expression that is not part of a class member access
2610   //   syntax and not used to form a pointer to member is used in the
2611   //   body of a non-static member function of class X, if name lookup
2612   //   resolves the name in the id-expression to a non-static non-type
2613   //   member of some class C, the id-expression is transformed into a
2614   //   class member access expression using (*this) as the
2615   //   postfix-expression to the left of the . operator.
2616   //
2617   // But we don't actually need to do this for '&' operands if R
2618   // resolved to a function or overloaded function set, because the
2619   // expression is ill-formed if it actually works out to be a
2620   // non-static member function:
2621   //
2622   // C++ [expr.ref]p4:
2623   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2624   //   [t]he expression can be used only as the left-hand operand of a
2625   //   member function call.
2626   //
2627   // There are other safeguards against such uses, but it's important
2628   // to get this right here so that we don't end up making a
2629   // spuriously dependent expression if we're inside a dependent
2630   // instance method.
2631   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2632     bool MightBeImplicitMember;
2633     if (!IsAddressOfOperand)
2634       MightBeImplicitMember = true;
2635     else if (!SS.isEmpty())
2636       MightBeImplicitMember = false;
2637     else if (R.isOverloadedResult())
2638       MightBeImplicitMember = false;
2639     else if (R.isUnresolvableResult())
2640       MightBeImplicitMember = true;
2641     else
2642       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2643                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2644                               isa<MSPropertyDecl>(R.getFoundDecl());
2645 
2646     if (MightBeImplicitMember)
2647       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2648                                              R, TemplateArgs, S);
2649   }
2650 
2651   if (TemplateArgs || TemplateKWLoc.isValid()) {
2652 
2653     // In C++1y, if this is a variable template id, then check it
2654     // in BuildTemplateIdExpr().
2655     // The single lookup result must be a variable template declaration.
2656     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2657         Id.TemplateId->Kind == TNK_Var_template) {
2658       assert(R.getAsSingle<VarTemplateDecl>() &&
2659              "There should only be one declaration found.");
2660     }
2661 
2662     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2663   }
2664 
2665   return BuildDeclarationNameExpr(SS, R, ADL);
2666 }
2667 
2668 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2669 /// declaration name, generally during template instantiation.
2670 /// There's a large number of things which don't need to be done along
2671 /// this path.
2672 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2673     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2674     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2675   DeclContext *DC = computeDeclContext(SS, false);
2676   if (!DC)
2677     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2678                                      NameInfo, /*TemplateArgs=*/nullptr);
2679 
2680   if (RequireCompleteDeclContext(SS, DC))
2681     return ExprError();
2682 
2683   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2684   LookupQualifiedName(R, DC);
2685 
2686   if (R.isAmbiguous())
2687     return ExprError();
2688 
2689   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2690     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2691                                      NameInfo, /*TemplateArgs=*/nullptr);
2692 
2693   if (R.empty()) {
2694     // Don't diagnose problems with invalid record decl, the secondary no_member
2695     // diagnostic during template instantiation is likely bogus, e.g. if a class
2696     // is invalid because it's derived from an invalid base class, then missing
2697     // members were likely supposed to be inherited.
2698     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2699       if (CD->isInvalidDecl())
2700         return ExprError();
2701     Diag(NameInfo.getLoc(), diag::err_no_member)
2702       << NameInfo.getName() << DC << SS.getRange();
2703     return ExprError();
2704   }
2705 
2706   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2707     // Diagnose a missing typename if this resolved unambiguously to a type in
2708     // a dependent context.  If we can recover with a type, downgrade this to
2709     // a warning in Microsoft compatibility mode.
2710     unsigned DiagID = diag::err_typename_missing;
2711     if (RecoveryTSI && getLangOpts().MSVCCompat)
2712       DiagID = diag::ext_typename_missing;
2713     SourceLocation Loc = SS.getBeginLoc();
2714     auto D = Diag(Loc, DiagID);
2715     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2716       << SourceRange(Loc, NameInfo.getEndLoc());
2717 
2718     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2719     // context.
2720     if (!RecoveryTSI)
2721       return ExprError();
2722 
2723     // Only issue the fixit if we're prepared to recover.
2724     D << FixItHint::CreateInsertion(Loc, "typename ");
2725 
2726     // Recover by pretending this was an elaborated type.
2727     QualType Ty = Context.getTypeDeclType(TD);
2728     TypeLocBuilder TLB;
2729     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2730 
2731     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2732     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2733     QTL.setElaboratedKeywordLoc(SourceLocation());
2734     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2735 
2736     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2737 
2738     return ExprEmpty();
2739   }
2740 
2741   // Defend against this resolving to an implicit member access. We usually
2742   // won't get here if this might be a legitimate a class member (we end up in
2743   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2744   // a pointer-to-member or in an unevaluated context in C++11.
2745   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2746     return BuildPossibleImplicitMemberExpr(SS,
2747                                            /*TemplateKWLoc=*/SourceLocation(),
2748                                            R, /*TemplateArgs=*/nullptr, S);
2749 
2750   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2751 }
2752 
2753 /// The parser has read a name in, and Sema has detected that we're currently
2754 /// inside an ObjC method. Perform some additional checks and determine if we
2755 /// should form a reference to an ivar.
2756 ///
2757 /// Ideally, most of this would be done by lookup, but there's
2758 /// actually quite a lot of extra work involved.
2759 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2760                                         IdentifierInfo *II) {
2761   SourceLocation Loc = Lookup.getNameLoc();
2762   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2763 
2764   // Check for error condition which is already reported.
2765   if (!CurMethod)
2766     return DeclResult(true);
2767 
2768   // There are two cases to handle here.  1) scoped lookup could have failed,
2769   // in which case we should look for an ivar.  2) scoped lookup could have
2770   // found a decl, but that decl is outside the current instance method (i.e.
2771   // a global variable).  In these two cases, we do a lookup for an ivar with
2772   // this name, if the lookup sucedes, we replace it our current decl.
2773 
2774   // If we're in a class method, we don't normally want to look for
2775   // ivars.  But if we don't find anything else, and there's an
2776   // ivar, that's an error.
2777   bool IsClassMethod = CurMethod->isClassMethod();
2778 
2779   bool LookForIvars;
2780   if (Lookup.empty())
2781     LookForIvars = true;
2782   else if (IsClassMethod)
2783     LookForIvars = false;
2784   else
2785     LookForIvars = (Lookup.isSingleResult() &&
2786                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2787   ObjCInterfaceDecl *IFace = nullptr;
2788   if (LookForIvars) {
2789     IFace = CurMethod->getClassInterface();
2790     ObjCInterfaceDecl *ClassDeclared;
2791     ObjCIvarDecl *IV = nullptr;
2792     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2793       // Diagnose using an ivar in a class method.
2794       if (IsClassMethod) {
2795         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2796         return DeclResult(true);
2797       }
2798 
2799       // Diagnose the use of an ivar outside of the declaring class.
2800       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2801           !declaresSameEntity(ClassDeclared, IFace) &&
2802           !getLangOpts().DebuggerSupport)
2803         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2804 
2805       // Success.
2806       return IV;
2807     }
2808   } else if (CurMethod->isInstanceMethod()) {
2809     // We should warn if a local variable hides an ivar.
2810     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2811       ObjCInterfaceDecl *ClassDeclared;
2812       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2813         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2814             declaresSameEntity(IFace, ClassDeclared))
2815           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2816       }
2817     }
2818   } else if (Lookup.isSingleResult() &&
2819              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2820     // If accessing a stand-alone ivar in a class method, this is an error.
2821     if (const ObjCIvarDecl *IV =
2822             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2823       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2824       return DeclResult(true);
2825     }
2826   }
2827 
2828   // Didn't encounter an error, didn't find an ivar.
2829   return DeclResult(false);
2830 }
2831 
2832 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2833                                   ObjCIvarDecl *IV) {
2834   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2835   assert(CurMethod && CurMethod->isInstanceMethod() &&
2836          "should not reference ivar from this context");
2837 
2838   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2839   assert(IFace && "should not reference ivar from this context");
2840 
2841   // If we're referencing an invalid decl, just return this as a silent
2842   // error node.  The error diagnostic was already emitted on the decl.
2843   if (IV->isInvalidDecl())
2844     return ExprError();
2845 
2846   // Check if referencing a field with __attribute__((deprecated)).
2847   if (DiagnoseUseOfDecl(IV, Loc))
2848     return ExprError();
2849 
2850   // FIXME: This should use a new expr for a direct reference, don't
2851   // turn this into Self->ivar, just return a BareIVarExpr or something.
2852   IdentifierInfo &II = Context.Idents.get("self");
2853   UnqualifiedId SelfName;
2854   SelfName.setIdentifier(&II, SourceLocation());
2855   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2856   CXXScopeSpec SelfScopeSpec;
2857   SourceLocation TemplateKWLoc;
2858   ExprResult SelfExpr =
2859       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2860                         /*HasTrailingLParen=*/false,
2861                         /*IsAddressOfOperand=*/false);
2862   if (SelfExpr.isInvalid())
2863     return ExprError();
2864 
2865   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2866   if (SelfExpr.isInvalid())
2867     return ExprError();
2868 
2869   MarkAnyDeclReferenced(Loc, IV, true);
2870 
2871   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2872   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2873       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2874     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2875 
2876   ObjCIvarRefExpr *Result = new (Context)
2877       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2878                       IV->getLocation(), SelfExpr.get(), true, true);
2879 
2880   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2881     if (!isUnevaluatedContext() &&
2882         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2883       getCurFunction()->recordUseOfWeak(Result);
2884   }
2885   if (getLangOpts().ObjCAutoRefCount)
2886     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2887       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2888 
2889   return Result;
2890 }
2891 
2892 /// The parser has read a name in, and Sema has detected that we're currently
2893 /// inside an ObjC method. Perform some additional checks and determine if we
2894 /// should form a reference to an ivar. If so, build an expression referencing
2895 /// that ivar.
2896 ExprResult
2897 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2898                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2899   // FIXME: Integrate this lookup step into LookupParsedName.
2900   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2901   if (Ivar.isInvalid())
2902     return ExprError();
2903   if (Ivar.isUsable())
2904     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2905                             cast<ObjCIvarDecl>(Ivar.get()));
2906 
2907   if (Lookup.empty() && II && AllowBuiltinCreation)
2908     LookupBuiltin(Lookup);
2909 
2910   // Sentinel value saying that we didn't do anything special.
2911   return ExprResult(false);
2912 }
2913 
2914 /// Cast a base object to a member's actual type.
2915 ///
2916 /// There are two relevant checks:
2917 ///
2918 /// C++ [class.access.base]p7:
2919 ///
2920 ///   If a class member access operator [...] is used to access a non-static
2921 ///   data member or non-static member function, the reference is ill-formed if
2922 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2923 ///   naming class of the right operand.
2924 ///
2925 /// C++ [expr.ref]p7:
2926 ///
2927 ///   If E2 is a non-static data member or a non-static member function, the
2928 ///   program is ill-formed if the class of which E2 is directly a member is an
2929 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2930 ///
2931 /// Note that the latter check does not consider access; the access of the
2932 /// "real" base class is checked as appropriate when checking the access of the
2933 /// member name.
2934 ExprResult
2935 Sema::PerformObjectMemberConversion(Expr *From,
2936                                     NestedNameSpecifier *Qualifier,
2937                                     NamedDecl *FoundDecl,
2938                                     NamedDecl *Member) {
2939   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2940   if (!RD)
2941     return From;
2942 
2943   QualType DestRecordType;
2944   QualType DestType;
2945   QualType FromRecordType;
2946   QualType FromType = From->getType();
2947   bool PointerConversions = false;
2948   if (isa<FieldDecl>(Member)) {
2949     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2950     auto FromPtrType = FromType->getAs<PointerType>();
2951     DestRecordType = Context.getAddrSpaceQualType(
2952         DestRecordType, FromPtrType
2953                             ? FromType->getPointeeType().getAddressSpace()
2954                             : FromType.getAddressSpace());
2955 
2956     if (FromPtrType) {
2957       DestType = Context.getPointerType(DestRecordType);
2958       FromRecordType = FromPtrType->getPointeeType();
2959       PointerConversions = true;
2960     } else {
2961       DestType = DestRecordType;
2962       FromRecordType = FromType;
2963     }
2964   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2965     if (Method->isStatic())
2966       return From;
2967 
2968     DestType = Method->getThisType();
2969     DestRecordType = DestType->getPointeeType();
2970 
2971     if (FromType->getAs<PointerType>()) {
2972       FromRecordType = FromType->getPointeeType();
2973       PointerConversions = true;
2974     } else {
2975       FromRecordType = FromType;
2976       DestType = DestRecordType;
2977     }
2978 
2979     LangAS FromAS = FromRecordType.getAddressSpace();
2980     LangAS DestAS = DestRecordType.getAddressSpace();
2981     if (FromAS != DestAS) {
2982       QualType FromRecordTypeWithoutAS =
2983           Context.removeAddrSpaceQualType(FromRecordType);
2984       QualType FromTypeWithDestAS =
2985           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2986       if (PointerConversions)
2987         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2988       From = ImpCastExprToType(From, FromTypeWithDestAS,
2989                                CK_AddressSpaceConversion, From->getValueKind())
2990                  .get();
2991     }
2992   } else {
2993     // No conversion necessary.
2994     return From;
2995   }
2996 
2997   if (DestType->isDependentType() || FromType->isDependentType())
2998     return From;
2999 
3000   // If the unqualified types are the same, no conversion is necessary.
3001   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3002     return From;
3003 
3004   SourceRange FromRange = From->getSourceRange();
3005   SourceLocation FromLoc = FromRange.getBegin();
3006 
3007   ExprValueKind VK = From->getValueKind();
3008 
3009   // C++ [class.member.lookup]p8:
3010   //   [...] Ambiguities can often be resolved by qualifying a name with its
3011   //   class name.
3012   //
3013   // If the member was a qualified name and the qualified referred to a
3014   // specific base subobject type, we'll cast to that intermediate type
3015   // first and then to the object in which the member is declared. That allows
3016   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3017   //
3018   //   class Base { public: int x; };
3019   //   class Derived1 : public Base { };
3020   //   class Derived2 : public Base { };
3021   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3022   //
3023   //   void VeryDerived::f() {
3024   //     x = 17; // error: ambiguous base subobjects
3025   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3026   //   }
3027   if (Qualifier && Qualifier->getAsType()) {
3028     QualType QType = QualType(Qualifier->getAsType(), 0);
3029     assert(QType->isRecordType() && "lookup done with non-record type");
3030 
3031     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3032 
3033     // In C++98, the qualifier type doesn't actually have to be a base
3034     // type of the object type, in which case we just ignore it.
3035     // Otherwise build the appropriate casts.
3036     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3037       CXXCastPath BasePath;
3038       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3039                                        FromLoc, FromRange, &BasePath))
3040         return ExprError();
3041 
3042       if (PointerConversions)
3043         QType = Context.getPointerType(QType);
3044       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3045                                VK, &BasePath).get();
3046 
3047       FromType = QType;
3048       FromRecordType = QRecordType;
3049 
3050       // If the qualifier type was the same as the destination type,
3051       // we're done.
3052       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3053         return From;
3054     }
3055   }
3056 
3057   CXXCastPath BasePath;
3058   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3059                                    FromLoc, FromRange, &BasePath,
3060                                    /*IgnoreAccess=*/true))
3061     return ExprError();
3062 
3063   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3064                            VK, &BasePath);
3065 }
3066 
3067 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3068                                       const LookupResult &R,
3069                                       bool HasTrailingLParen) {
3070   // Only when used directly as the postfix-expression of a call.
3071   if (!HasTrailingLParen)
3072     return false;
3073 
3074   // Never if a scope specifier was provided.
3075   if (SS.isSet())
3076     return false;
3077 
3078   // Only in C++ or ObjC++.
3079   if (!getLangOpts().CPlusPlus)
3080     return false;
3081 
3082   // Turn off ADL when we find certain kinds of declarations during
3083   // normal lookup:
3084   for (NamedDecl *D : R) {
3085     // C++0x [basic.lookup.argdep]p3:
3086     //     -- a declaration of a class member
3087     // Since using decls preserve this property, we check this on the
3088     // original decl.
3089     if (D->isCXXClassMember())
3090       return false;
3091 
3092     // C++0x [basic.lookup.argdep]p3:
3093     //     -- a block-scope function declaration that is not a
3094     //        using-declaration
3095     // NOTE: we also trigger this for function templates (in fact, we
3096     // don't check the decl type at all, since all other decl types
3097     // turn off ADL anyway).
3098     if (isa<UsingShadowDecl>(D))
3099       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3100     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3101       return false;
3102 
3103     // C++0x [basic.lookup.argdep]p3:
3104     //     -- a declaration that is neither a function or a function
3105     //        template
3106     // And also for builtin functions.
3107     if (isa<FunctionDecl>(D)) {
3108       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3109 
3110       // But also builtin functions.
3111       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3112         return false;
3113     } else if (!isa<FunctionTemplateDecl>(D))
3114       return false;
3115   }
3116 
3117   return true;
3118 }
3119 
3120 
3121 /// Diagnoses obvious problems with the use of the given declaration
3122 /// as an expression.  This is only actually called for lookups that
3123 /// were not overloaded, and it doesn't promise that the declaration
3124 /// will in fact be used.
3125 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3126   if (D->isInvalidDecl())
3127     return true;
3128 
3129   if (isa<TypedefNameDecl>(D)) {
3130     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3131     return true;
3132   }
3133 
3134   if (isa<ObjCInterfaceDecl>(D)) {
3135     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3136     return true;
3137   }
3138 
3139   if (isa<NamespaceDecl>(D)) {
3140     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3141     return true;
3142   }
3143 
3144   return false;
3145 }
3146 
3147 // Certain multiversion types should be treated as overloaded even when there is
3148 // only one result.
3149 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3150   assert(R.isSingleResult() && "Expected only a single result");
3151   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3152   return FD &&
3153          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3154 }
3155 
3156 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3157                                           LookupResult &R, bool NeedsADL,
3158                                           bool AcceptInvalidDecl) {
3159   // If this is a single, fully-resolved result and we don't need ADL,
3160   // just build an ordinary singleton decl ref.
3161   if (!NeedsADL && R.isSingleResult() &&
3162       !R.getAsSingle<FunctionTemplateDecl>() &&
3163       !ShouldLookupResultBeMultiVersionOverload(R))
3164     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3165                                     R.getRepresentativeDecl(), nullptr,
3166                                     AcceptInvalidDecl);
3167 
3168   // We only need to check the declaration if there's exactly one
3169   // result, because in the overloaded case the results can only be
3170   // functions and function templates.
3171   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3172       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3173     return ExprError();
3174 
3175   // Otherwise, just build an unresolved lookup expression.  Suppress
3176   // any lookup-related diagnostics; we'll hash these out later, when
3177   // we've picked a target.
3178   R.suppressDiagnostics();
3179 
3180   UnresolvedLookupExpr *ULE
3181     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3182                                    SS.getWithLocInContext(Context),
3183                                    R.getLookupNameInfo(),
3184                                    NeedsADL, R.isOverloadedResult(),
3185                                    R.begin(), R.end());
3186 
3187   return ULE;
3188 }
3189 
3190 static void
3191 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3192                                    ValueDecl *var, DeclContext *DC);
3193 
3194 /// Complete semantic analysis for a reference to the given declaration.
3195 ExprResult Sema::BuildDeclarationNameExpr(
3196     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3197     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3198     bool AcceptInvalidDecl) {
3199   assert(D && "Cannot refer to a NULL declaration");
3200   assert(!isa<FunctionTemplateDecl>(D) &&
3201          "Cannot refer unambiguously to a function template");
3202 
3203   SourceLocation Loc = NameInfo.getLoc();
3204   if (CheckDeclInExpr(*this, Loc, D))
3205     return ExprError();
3206 
3207   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3208     // Specifically diagnose references to class templates that are missing
3209     // a template argument list.
3210     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3211     return ExprError();
3212   }
3213 
3214   // Make sure that we're referring to a value.
3215   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3216   if (!VD) {
3217     Diag(Loc, diag::err_ref_non_value)
3218       << D << SS.getRange();
3219     Diag(D->getLocation(), diag::note_declared_at);
3220     return ExprError();
3221   }
3222 
3223   // Check whether this declaration can be used. Note that we suppress
3224   // this check when we're going to perform argument-dependent lookup
3225   // on this function name, because this might not be the function
3226   // that overload resolution actually selects.
3227   if (DiagnoseUseOfDecl(VD, Loc))
3228     return ExprError();
3229 
3230   // Only create DeclRefExpr's for valid Decl's.
3231   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3232     return ExprError();
3233 
3234   // Handle members of anonymous structs and unions.  If we got here,
3235   // and the reference is to a class member indirect field, then this
3236   // must be the subject of a pointer-to-member expression.
3237   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3238     if (!indirectField->isCXXClassMember())
3239       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3240                                                       indirectField);
3241 
3242   {
3243     QualType type = VD->getType();
3244     if (type.isNull())
3245       return ExprError();
3246     ExprValueKind valueKind = VK_RValue;
3247 
3248     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3249     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3250     // is expanded by some outer '...' in the context of the use.
3251     type = type.getNonPackExpansionType();
3252 
3253     switch (D->getKind()) {
3254     // Ignore all the non-ValueDecl kinds.
3255 #define ABSTRACT_DECL(kind)
3256 #define VALUE(type, base)
3257 #define DECL(type, base) \
3258     case Decl::type:
3259 #include "clang/AST/DeclNodes.inc"
3260       llvm_unreachable("invalid value decl kind");
3261 
3262     // These shouldn't make it here.
3263     case Decl::ObjCAtDefsField:
3264       llvm_unreachable("forming non-member reference to ivar?");
3265 
3266     // Enum constants are always r-values and never references.
3267     // Unresolved using declarations are dependent.
3268     case Decl::EnumConstant:
3269     case Decl::UnresolvedUsingValue:
3270     case Decl::OMPDeclareReduction:
3271     case Decl::OMPDeclareMapper:
3272       valueKind = VK_RValue;
3273       break;
3274 
3275     // Fields and indirect fields that got here must be for
3276     // pointer-to-member expressions; we just call them l-values for
3277     // internal consistency, because this subexpression doesn't really
3278     // exist in the high-level semantics.
3279     case Decl::Field:
3280     case Decl::IndirectField:
3281     case Decl::ObjCIvar:
3282       assert(getLangOpts().CPlusPlus &&
3283              "building reference to field in C?");
3284 
3285       // These can't have reference type in well-formed programs, but
3286       // for internal consistency we do this anyway.
3287       type = type.getNonReferenceType();
3288       valueKind = VK_LValue;
3289       break;
3290 
3291     // Non-type template parameters are either l-values or r-values
3292     // depending on the type.
3293     case Decl::NonTypeTemplateParm: {
3294       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3295         type = reftype->getPointeeType();
3296         valueKind = VK_LValue; // even if the parameter is an r-value reference
3297         break;
3298       }
3299 
3300       // [expr.prim.id.unqual]p2:
3301       //   If the entity is a template parameter object for a template
3302       //   parameter of type T, the type of the expression is const T.
3303       //   [...] The expression is an lvalue if the entity is a [...] template
3304       //   parameter object.
3305       if (type->isRecordType()) {
3306         type = type.getUnqualifiedType().withConst();
3307         valueKind = VK_LValue;
3308         break;
3309       }
3310 
3311       // For non-references, we need to strip qualifiers just in case
3312       // the template parameter was declared as 'const int' or whatever.
3313       valueKind = VK_RValue;
3314       type = type.getUnqualifiedType();
3315       break;
3316     }
3317 
3318     case Decl::Var:
3319     case Decl::VarTemplateSpecialization:
3320     case Decl::VarTemplatePartialSpecialization:
3321     case Decl::Decomposition:
3322     case Decl::OMPCapturedExpr:
3323       // In C, "extern void blah;" is valid and is an r-value.
3324       if (!getLangOpts().CPlusPlus &&
3325           !type.hasQualifiers() &&
3326           type->isVoidType()) {
3327         valueKind = VK_RValue;
3328         break;
3329       }
3330       LLVM_FALLTHROUGH;
3331 
3332     case Decl::ImplicitParam:
3333     case Decl::ParmVar: {
3334       // These are always l-values.
3335       valueKind = VK_LValue;
3336       type = type.getNonReferenceType();
3337 
3338       // FIXME: Does the addition of const really only apply in
3339       // potentially-evaluated contexts? Since the variable isn't actually
3340       // captured in an unevaluated context, it seems that the answer is no.
3341       if (!isUnevaluatedContext()) {
3342         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3343         if (!CapturedType.isNull())
3344           type = CapturedType;
3345       }
3346 
3347       break;
3348     }
3349 
3350     case Decl::Binding: {
3351       // These are always lvalues.
3352       valueKind = VK_LValue;
3353       type = type.getNonReferenceType();
3354       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3355       // decides how that's supposed to work.
3356       auto *BD = cast<BindingDecl>(VD);
3357       if (BD->getDeclContext() != CurContext) {
3358         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3359         if (DD && DD->hasLocalStorage())
3360           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3361       }
3362       break;
3363     }
3364 
3365     case Decl::Function: {
3366       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3367         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3368           type = Context.BuiltinFnTy;
3369           valueKind = VK_RValue;
3370           break;
3371         }
3372       }
3373 
3374       const FunctionType *fty = type->castAs<FunctionType>();
3375 
3376       // If we're referring to a function with an __unknown_anytype
3377       // result type, make the entire expression __unknown_anytype.
3378       if (fty->getReturnType() == Context.UnknownAnyTy) {
3379         type = Context.UnknownAnyTy;
3380         valueKind = VK_RValue;
3381         break;
3382       }
3383 
3384       // Functions are l-values in C++.
3385       if (getLangOpts().CPlusPlus) {
3386         valueKind = VK_LValue;
3387         break;
3388       }
3389 
3390       // C99 DR 316 says that, if a function type comes from a
3391       // function definition (without a prototype), that type is only
3392       // used for checking compatibility. Therefore, when referencing
3393       // the function, we pretend that we don't have the full function
3394       // type.
3395       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3396           isa<FunctionProtoType>(fty))
3397         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3398                                               fty->getExtInfo());
3399 
3400       // Functions are r-values in C.
3401       valueKind = VK_RValue;
3402       break;
3403     }
3404 
3405     case Decl::CXXDeductionGuide:
3406       llvm_unreachable("building reference to deduction guide");
3407 
3408     case Decl::MSProperty:
3409     case Decl::MSGuid:
3410     case Decl::TemplateParamObject:
3411       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3412       // capture in OpenMP, or duplicated between host and device?
3413       valueKind = VK_LValue;
3414       break;
3415 
3416     case Decl::CXXMethod:
3417       // If we're referring to a method with an __unknown_anytype
3418       // result type, make the entire expression __unknown_anytype.
3419       // This should only be possible with a type written directly.
3420       if (const FunctionProtoType *proto
3421             = dyn_cast<FunctionProtoType>(VD->getType()))
3422         if (proto->getReturnType() == Context.UnknownAnyTy) {
3423           type = Context.UnknownAnyTy;
3424           valueKind = VK_RValue;
3425           break;
3426         }
3427 
3428       // C++ methods are l-values if static, r-values if non-static.
3429       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3430         valueKind = VK_LValue;
3431         break;
3432       }
3433       LLVM_FALLTHROUGH;
3434 
3435     case Decl::CXXConversion:
3436     case Decl::CXXDestructor:
3437     case Decl::CXXConstructor:
3438       valueKind = VK_RValue;
3439       break;
3440     }
3441 
3442     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3443                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3444                             TemplateArgs);
3445   }
3446 }
3447 
3448 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3449                                     SmallString<32> &Target) {
3450   Target.resize(CharByteWidth * (Source.size() + 1));
3451   char *ResultPtr = &Target[0];
3452   const llvm::UTF8 *ErrorPtr;
3453   bool success =
3454       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3455   (void)success;
3456   assert(success);
3457   Target.resize(ResultPtr - &Target[0]);
3458 }
3459 
3460 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3461                                      PredefinedExpr::IdentKind IK) {
3462   // Pick the current block, lambda, captured statement or function.
3463   Decl *currentDecl = nullptr;
3464   if (const BlockScopeInfo *BSI = getCurBlock())
3465     currentDecl = BSI->TheDecl;
3466   else if (const LambdaScopeInfo *LSI = getCurLambda())
3467     currentDecl = LSI->CallOperator;
3468   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3469     currentDecl = CSI->TheCapturedDecl;
3470   else
3471     currentDecl = getCurFunctionOrMethodDecl();
3472 
3473   if (!currentDecl) {
3474     Diag(Loc, diag::ext_predef_outside_function);
3475     currentDecl = Context.getTranslationUnitDecl();
3476   }
3477 
3478   QualType ResTy;
3479   StringLiteral *SL = nullptr;
3480   if (cast<DeclContext>(currentDecl)->isDependentContext())
3481     ResTy = Context.DependentTy;
3482   else {
3483     // Pre-defined identifiers are of type char[x], where x is the length of
3484     // the string.
3485     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3486     unsigned Length = Str.length();
3487 
3488     llvm::APInt LengthI(32, Length + 1);
3489     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3490       ResTy =
3491           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3492       SmallString<32> RawChars;
3493       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3494                               Str, RawChars);
3495       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3496                                            ArrayType::Normal,
3497                                            /*IndexTypeQuals*/ 0);
3498       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3499                                  /*Pascal*/ false, ResTy, Loc);
3500     } else {
3501       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3502       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503                                            ArrayType::Normal,
3504                                            /*IndexTypeQuals*/ 0);
3505       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3506                                  /*Pascal*/ false, ResTy, Loc);
3507     }
3508   }
3509 
3510   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3511 }
3512 
3513 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3514   PredefinedExpr::IdentKind IK;
3515 
3516   switch (Kind) {
3517   default: llvm_unreachable("Unknown simple primary expr!");
3518   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3519   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3520   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3521   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3522   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3523   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3524   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3525   }
3526 
3527   return BuildPredefinedExpr(Loc, IK);
3528 }
3529 
3530 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3531   SmallString<16> CharBuffer;
3532   bool Invalid = false;
3533   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3534   if (Invalid)
3535     return ExprError();
3536 
3537   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3538                             PP, Tok.getKind());
3539   if (Literal.hadError())
3540     return ExprError();
3541 
3542   QualType Ty;
3543   if (Literal.isWide())
3544     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3545   else if (Literal.isUTF8() && getLangOpts().Char8)
3546     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3547   else if (Literal.isUTF16())
3548     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3549   else if (Literal.isUTF32())
3550     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3551   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3552     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3553   else
3554     Ty = Context.CharTy;  // 'x' -> char in C++
3555 
3556   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3557   if (Literal.isWide())
3558     Kind = CharacterLiteral::Wide;
3559   else if (Literal.isUTF16())
3560     Kind = CharacterLiteral::UTF16;
3561   else if (Literal.isUTF32())
3562     Kind = CharacterLiteral::UTF32;
3563   else if (Literal.isUTF8())
3564     Kind = CharacterLiteral::UTF8;
3565 
3566   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3567                                              Tok.getLocation());
3568 
3569   if (Literal.getUDSuffix().empty())
3570     return Lit;
3571 
3572   // We're building a user-defined literal.
3573   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3574   SourceLocation UDSuffixLoc =
3575     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3576 
3577   // Make sure we're allowed user-defined literals here.
3578   if (!UDLScope)
3579     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3580 
3581   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3582   //   operator "" X (ch)
3583   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3584                                         Lit, Tok.getLocation());
3585 }
3586 
3587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3588   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3589   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3590                                 Context.IntTy, Loc);
3591 }
3592 
3593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3594                                   QualType Ty, SourceLocation Loc) {
3595   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3596 
3597   using llvm::APFloat;
3598   APFloat Val(Format);
3599 
3600   APFloat::opStatus result = Literal.GetFloatValue(Val);
3601 
3602   // Overflow is always an error, but underflow is only an error if
3603   // we underflowed to zero (APFloat reports denormals as underflow).
3604   if ((result & APFloat::opOverflow) ||
3605       ((result & APFloat::opUnderflow) && Val.isZero())) {
3606     unsigned diagnostic;
3607     SmallString<20> buffer;
3608     if (result & APFloat::opOverflow) {
3609       diagnostic = diag::warn_float_overflow;
3610       APFloat::getLargest(Format).toString(buffer);
3611     } else {
3612       diagnostic = diag::warn_float_underflow;
3613       APFloat::getSmallest(Format).toString(buffer);
3614     }
3615 
3616     S.Diag(Loc, diagnostic)
3617       << Ty
3618       << StringRef(buffer.data(), buffer.size());
3619   }
3620 
3621   bool isExact = (result == APFloat::opOK);
3622   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3623 }
3624 
3625 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3626   assert(E && "Invalid expression");
3627 
3628   if (E->isValueDependent())
3629     return false;
3630 
3631   QualType QT = E->getType();
3632   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3633     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3634     return true;
3635   }
3636 
3637   llvm::APSInt ValueAPS;
3638   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3639 
3640   if (R.isInvalid())
3641     return true;
3642 
3643   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3644   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3645     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3646         << ValueAPS.toString(10) << ValueIsPositive;
3647     return true;
3648   }
3649 
3650   return false;
3651 }
3652 
3653 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3654   // Fast path for a single digit (which is quite common).  A single digit
3655   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3656   if (Tok.getLength() == 1) {
3657     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3658     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3659   }
3660 
3661   SmallString<128> SpellingBuffer;
3662   // NumericLiteralParser wants to overread by one character.  Add padding to
3663   // the buffer in case the token is copied to the buffer.  If getSpelling()
3664   // returns a StringRef to the memory buffer, it should have a null char at
3665   // the EOF, so it is also safe.
3666   SpellingBuffer.resize(Tok.getLength() + 1);
3667 
3668   // Get the spelling of the token, which eliminates trigraphs, etc.
3669   bool Invalid = false;
3670   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3671   if (Invalid)
3672     return ExprError();
3673 
3674   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3675                                PP.getSourceManager(), PP.getLangOpts(),
3676                                PP.getTargetInfo(), PP.getDiagnostics());
3677   if (Literal.hadError)
3678     return ExprError();
3679 
3680   if (Literal.hasUDSuffix()) {
3681     // We're building a user-defined literal.
3682     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3683     SourceLocation UDSuffixLoc =
3684       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3685 
3686     // Make sure we're allowed user-defined literals here.
3687     if (!UDLScope)
3688       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3689 
3690     QualType CookedTy;
3691     if (Literal.isFloatingLiteral()) {
3692       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3693       // long double, the literal is treated as a call of the form
3694       //   operator "" X (f L)
3695       CookedTy = Context.LongDoubleTy;
3696     } else {
3697       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3698       // unsigned long long, the literal is treated as a call of the form
3699       //   operator "" X (n ULL)
3700       CookedTy = Context.UnsignedLongLongTy;
3701     }
3702 
3703     DeclarationName OpName =
3704       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3705     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3706     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3707 
3708     SourceLocation TokLoc = Tok.getLocation();
3709 
3710     // Perform literal operator lookup to determine if we're building a raw
3711     // literal or a cooked one.
3712     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3713     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3714                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3715                                   /*AllowStringTemplatePack*/ false,
3716                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3717     case LOLR_ErrorNoDiagnostic:
3718       // Lookup failure for imaginary constants isn't fatal, there's still the
3719       // GNU extension producing _Complex types.
3720       break;
3721     case LOLR_Error:
3722       return ExprError();
3723     case LOLR_Cooked: {
3724       Expr *Lit;
3725       if (Literal.isFloatingLiteral()) {
3726         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3727       } else {
3728         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3729         if (Literal.GetIntegerValue(ResultVal))
3730           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3731               << /* Unsigned */ 1;
3732         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3733                                      Tok.getLocation());
3734       }
3735       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3736     }
3737 
3738     case LOLR_Raw: {
3739       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3740       // literal is treated as a call of the form
3741       //   operator "" X ("n")
3742       unsigned Length = Literal.getUDSuffixOffset();
3743       QualType StrTy = Context.getConstantArrayType(
3744           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3745           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3746       Expr *Lit = StringLiteral::Create(
3747           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3748           /*Pascal*/false, StrTy, &TokLoc, 1);
3749       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3750     }
3751 
3752     case LOLR_Template: {
3753       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3754       // template), L is treated as a call fo the form
3755       //   operator "" X <'c1', 'c2', ... 'ck'>()
3756       // where n is the source character sequence c1 c2 ... ck.
3757       TemplateArgumentListInfo ExplicitArgs;
3758       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3759       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3760       llvm::APSInt Value(CharBits, CharIsUnsigned);
3761       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3762         Value = TokSpelling[I];
3763         TemplateArgument Arg(Context, Value, Context.CharTy);
3764         TemplateArgumentLocInfo ArgInfo;
3765         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3766       }
3767       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3768                                       &ExplicitArgs);
3769     }
3770     case LOLR_StringTemplatePack:
3771       llvm_unreachable("unexpected literal operator lookup result");
3772     }
3773   }
3774 
3775   Expr *Res;
3776 
3777   if (Literal.isFixedPointLiteral()) {
3778     QualType Ty;
3779 
3780     if (Literal.isAccum) {
3781       if (Literal.isHalf) {
3782         Ty = Context.ShortAccumTy;
3783       } else if (Literal.isLong) {
3784         Ty = Context.LongAccumTy;
3785       } else {
3786         Ty = Context.AccumTy;
3787       }
3788     } else if (Literal.isFract) {
3789       if (Literal.isHalf) {
3790         Ty = Context.ShortFractTy;
3791       } else if (Literal.isLong) {
3792         Ty = Context.LongFractTy;
3793       } else {
3794         Ty = Context.FractTy;
3795       }
3796     }
3797 
3798     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3799 
3800     bool isSigned = !Literal.isUnsigned;
3801     unsigned scale = Context.getFixedPointScale(Ty);
3802     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3803 
3804     llvm::APInt Val(bit_width, 0, isSigned);
3805     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3806     bool ValIsZero = Val.isNullValue() && !Overflowed;
3807 
3808     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3809     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3810       // Clause 6.4.4 - The value of a constant shall be in the range of
3811       // representable values for its type, with exception for constants of a
3812       // fract type with a value of exactly 1; such a constant shall denote
3813       // the maximal value for the type.
3814       --Val;
3815     else if (Val.ugt(MaxVal) || Overflowed)
3816       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3817 
3818     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3819                                               Tok.getLocation(), scale);
3820   } else if (Literal.isFloatingLiteral()) {
3821     QualType Ty;
3822     if (Literal.isHalf){
3823       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3824         Ty = Context.HalfTy;
3825       else {
3826         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3827         return ExprError();
3828       }
3829     } else if (Literal.isFloat)
3830       Ty = Context.FloatTy;
3831     else if (Literal.isLong)
3832       Ty = Context.LongDoubleTy;
3833     else if (Literal.isFloat16)
3834       Ty = Context.Float16Ty;
3835     else if (Literal.isFloat128)
3836       Ty = Context.Float128Ty;
3837     else
3838       Ty = Context.DoubleTy;
3839 
3840     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3841 
3842     if (Ty == Context.DoubleTy) {
3843       if (getLangOpts().SinglePrecisionConstants) {
3844         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3845           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3846         }
3847       } else if (getLangOpts().OpenCL &&
3848                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3849         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3850         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3851         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3852       }
3853     }
3854   } else if (!Literal.isIntegerLiteral()) {
3855     return ExprError();
3856   } else {
3857     QualType Ty;
3858 
3859     // 'long long' is a C99 or C++11 feature.
3860     if (!getLangOpts().C99 && Literal.isLongLong) {
3861       if (getLangOpts().CPlusPlus)
3862         Diag(Tok.getLocation(),
3863              getLangOpts().CPlusPlus11 ?
3864              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3865       else
3866         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3867     }
3868 
3869     // Get the value in the widest-possible width.
3870     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3871     llvm::APInt ResultVal(MaxWidth, 0);
3872 
3873     if (Literal.GetIntegerValue(ResultVal)) {
3874       // If this value didn't fit into uintmax_t, error and force to ull.
3875       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3876           << /* Unsigned */ 1;
3877       Ty = Context.UnsignedLongLongTy;
3878       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3879              "long long is not intmax_t?");
3880     } else {
3881       // If this value fits into a ULL, try to figure out what else it fits into
3882       // according to the rules of C99 6.4.4.1p5.
3883 
3884       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3885       // be an unsigned int.
3886       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3887 
3888       // Check from smallest to largest, picking the smallest type we can.
3889       unsigned Width = 0;
3890 
3891       // Microsoft specific integer suffixes are explicitly sized.
3892       if (Literal.MicrosoftInteger) {
3893         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3894           Width = 8;
3895           Ty = Context.CharTy;
3896         } else {
3897           Width = Literal.MicrosoftInteger;
3898           Ty = Context.getIntTypeForBitwidth(Width,
3899                                              /*Signed=*/!Literal.isUnsigned);
3900         }
3901       }
3902 
3903       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3904         // Are int/unsigned possibilities?
3905         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3906 
3907         // Does it fit in a unsigned int?
3908         if (ResultVal.isIntN(IntSize)) {
3909           // Does it fit in a signed int?
3910           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3911             Ty = Context.IntTy;
3912           else if (AllowUnsigned)
3913             Ty = Context.UnsignedIntTy;
3914           Width = IntSize;
3915         }
3916       }
3917 
3918       // Are long/unsigned long possibilities?
3919       if (Ty.isNull() && !Literal.isLongLong) {
3920         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3921 
3922         // Does it fit in a unsigned long?
3923         if (ResultVal.isIntN(LongSize)) {
3924           // Does it fit in a signed long?
3925           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3926             Ty = Context.LongTy;
3927           else if (AllowUnsigned)
3928             Ty = Context.UnsignedLongTy;
3929           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3930           // is compatible.
3931           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3932             const unsigned LongLongSize =
3933                 Context.getTargetInfo().getLongLongWidth();
3934             Diag(Tok.getLocation(),
3935                  getLangOpts().CPlusPlus
3936                      ? Literal.isLong
3937                            ? diag::warn_old_implicitly_unsigned_long_cxx
3938                            : /*C++98 UB*/ diag::
3939                                  ext_old_implicitly_unsigned_long_cxx
3940                      : diag::warn_old_implicitly_unsigned_long)
3941                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3942                                             : /*will be ill-formed*/ 1);
3943             Ty = Context.UnsignedLongTy;
3944           }
3945           Width = LongSize;
3946         }
3947       }
3948 
3949       // Check long long if needed.
3950       if (Ty.isNull()) {
3951         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3952 
3953         // Does it fit in a unsigned long long?
3954         if (ResultVal.isIntN(LongLongSize)) {
3955           // Does it fit in a signed long long?
3956           // To be compatible with MSVC, hex integer literals ending with the
3957           // LL or i64 suffix are always signed in Microsoft mode.
3958           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3959               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3960             Ty = Context.LongLongTy;
3961           else if (AllowUnsigned)
3962             Ty = Context.UnsignedLongLongTy;
3963           Width = LongLongSize;
3964         }
3965       }
3966 
3967       // If we still couldn't decide a type, we probably have something that
3968       // does not fit in a signed long long, but has no U suffix.
3969       if (Ty.isNull()) {
3970         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3971         Ty = Context.UnsignedLongLongTy;
3972         Width = Context.getTargetInfo().getLongLongWidth();
3973       }
3974 
3975       if (ResultVal.getBitWidth() != Width)
3976         ResultVal = ResultVal.trunc(Width);
3977     }
3978     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3979   }
3980 
3981   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3982   if (Literal.isImaginary) {
3983     Res = new (Context) ImaginaryLiteral(Res,
3984                                         Context.getComplexType(Res->getType()));
3985 
3986     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3987   }
3988   return Res;
3989 }
3990 
3991 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3992   assert(E && "ActOnParenExpr() missing expr");
3993   return new (Context) ParenExpr(L, R, E);
3994 }
3995 
3996 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3997                                          SourceLocation Loc,
3998                                          SourceRange ArgRange) {
3999   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4000   // scalar or vector data type argument..."
4001   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4002   // type (C99 6.2.5p18) or void.
4003   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4004     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4005       << T << ArgRange;
4006     return true;
4007   }
4008 
4009   assert((T->isVoidType() || !T->isIncompleteType()) &&
4010          "Scalar types should always be complete");
4011   return false;
4012 }
4013 
4014 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4015                                            SourceLocation Loc,
4016                                            SourceRange ArgRange,
4017                                            UnaryExprOrTypeTrait TraitKind) {
4018   // Invalid types must be hard errors for SFINAE in C++.
4019   if (S.LangOpts.CPlusPlus)
4020     return true;
4021 
4022   // C99 6.5.3.4p1:
4023   if (T->isFunctionType() &&
4024       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4025        TraitKind == UETT_PreferredAlignOf)) {
4026     // sizeof(function)/alignof(function) is allowed as an extension.
4027     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4028         << getTraitSpelling(TraitKind) << ArgRange;
4029     return false;
4030   }
4031 
4032   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4033   // this is an error (OpenCL v1.1 s6.3.k)
4034   if (T->isVoidType()) {
4035     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4036                                         : diag::ext_sizeof_alignof_void_type;
4037     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4038     return false;
4039   }
4040 
4041   return true;
4042 }
4043 
4044 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4045                                              SourceLocation Loc,
4046                                              SourceRange ArgRange,
4047                                              UnaryExprOrTypeTrait TraitKind) {
4048   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4049   // runtime doesn't allow it.
4050   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4051     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4052       << T << (TraitKind == UETT_SizeOf)
4053       << ArgRange;
4054     return true;
4055   }
4056 
4057   return false;
4058 }
4059 
4060 /// Check whether E is a pointer from a decayed array type (the decayed
4061 /// pointer type is equal to T) and emit a warning if it is.
4062 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4063                                      Expr *E) {
4064   // Don't warn if the operation changed the type.
4065   if (T != E->getType())
4066     return;
4067 
4068   // Now look for array decays.
4069   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4070   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4071     return;
4072 
4073   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4074                                              << ICE->getType()
4075                                              << ICE->getSubExpr()->getType();
4076 }
4077 
4078 /// Check the constraints on expression operands to unary type expression
4079 /// and type traits.
4080 ///
4081 /// Completes any types necessary and validates the constraints on the operand
4082 /// expression. The logic mostly mirrors the type-based overload, but may modify
4083 /// the expression as it completes the type for that expression through template
4084 /// instantiation, etc.
4085 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4086                                             UnaryExprOrTypeTrait ExprKind) {
4087   QualType ExprTy = E->getType();
4088   assert(!ExprTy->isReferenceType());
4089 
4090   bool IsUnevaluatedOperand =
4091       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4092        ExprKind == UETT_PreferredAlignOf);
4093   if (IsUnevaluatedOperand) {
4094     ExprResult Result = CheckUnevaluatedOperand(E);
4095     if (Result.isInvalid())
4096       return true;
4097     E = Result.get();
4098   }
4099 
4100   if (ExprKind == UETT_VecStep)
4101     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4102                                         E->getSourceRange());
4103 
4104   // Explicitly list some types as extensions.
4105   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4106                                       E->getSourceRange(), ExprKind))
4107     return false;
4108 
4109   // 'alignof' applied to an expression only requires the base element type of
4110   // the expression to be complete. 'sizeof' requires the expression's type to
4111   // be complete (and will attempt to complete it if it's an array of unknown
4112   // bound).
4113   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4114     if (RequireCompleteSizedType(
4115             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4116             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4117             getTraitSpelling(ExprKind), E->getSourceRange()))
4118       return true;
4119   } else {
4120     if (RequireCompleteSizedExprType(
4121             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4122             getTraitSpelling(ExprKind), E->getSourceRange()))
4123       return true;
4124   }
4125 
4126   // Completing the expression's type may have changed it.
4127   ExprTy = E->getType();
4128   assert(!ExprTy->isReferenceType());
4129 
4130   if (ExprTy->isFunctionType()) {
4131     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4132         << getTraitSpelling(ExprKind) << E->getSourceRange();
4133     return true;
4134   }
4135 
4136   // The operand for sizeof and alignof is in an unevaluated expression context,
4137   // so side effects could result in unintended consequences.
4138   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4139       E->HasSideEffects(Context, false))
4140     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4141 
4142   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4143                                        E->getSourceRange(), ExprKind))
4144     return true;
4145 
4146   if (ExprKind == UETT_SizeOf) {
4147     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4148       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4149         QualType OType = PVD->getOriginalType();
4150         QualType Type = PVD->getType();
4151         if (Type->isPointerType() && OType->isArrayType()) {
4152           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4153             << Type << OType;
4154           Diag(PVD->getLocation(), diag::note_declared_at);
4155         }
4156       }
4157     }
4158 
4159     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4160     // decays into a pointer and returns an unintended result. This is most
4161     // likely a typo for "sizeof(array) op x".
4162     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4163       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4164                                BO->getLHS());
4165       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4166                                BO->getRHS());
4167     }
4168   }
4169 
4170   return false;
4171 }
4172 
4173 /// Check the constraints on operands to unary expression and type
4174 /// traits.
4175 ///
4176 /// This will complete any types necessary, and validate the various constraints
4177 /// on those operands.
4178 ///
4179 /// The UsualUnaryConversions() function is *not* called by this routine.
4180 /// C99 6.3.2.1p[2-4] all state:
4181 ///   Except when it is the operand of the sizeof operator ...
4182 ///
4183 /// C++ [expr.sizeof]p4
4184 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4185 ///   standard conversions are not applied to the operand of sizeof.
4186 ///
4187 /// This policy is followed for all of the unary trait expressions.
4188 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4189                                             SourceLocation OpLoc,
4190                                             SourceRange ExprRange,
4191                                             UnaryExprOrTypeTrait ExprKind) {
4192   if (ExprType->isDependentType())
4193     return false;
4194 
4195   // C++ [expr.sizeof]p2:
4196   //     When applied to a reference or a reference type, the result
4197   //     is the size of the referenced type.
4198   // C++11 [expr.alignof]p3:
4199   //     When alignof is applied to a reference type, the result
4200   //     shall be the alignment of the referenced type.
4201   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4202     ExprType = Ref->getPointeeType();
4203 
4204   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4205   //   When alignof or _Alignof is applied to an array type, the result
4206   //   is the alignment of the element type.
4207   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4208       ExprKind == UETT_OpenMPRequiredSimdAlign)
4209     ExprType = Context.getBaseElementType(ExprType);
4210 
4211   if (ExprKind == UETT_VecStep)
4212     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4213 
4214   // Explicitly list some types as extensions.
4215   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4216                                       ExprKind))
4217     return false;
4218 
4219   if (RequireCompleteSizedType(
4220           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4221           getTraitSpelling(ExprKind), ExprRange))
4222     return true;
4223 
4224   if (ExprType->isFunctionType()) {
4225     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4226         << getTraitSpelling(ExprKind) << ExprRange;
4227     return true;
4228   }
4229 
4230   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4231                                        ExprKind))
4232     return true;
4233 
4234   return false;
4235 }
4236 
4237 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4238   // Cannot know anything else if the expression is dependent.
4239   if (E->isTypeDependent())
4240     return false;
4241 
4242   if (E->getObjectKind() == OK_BitField) {
4243     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4244        << 1 << E->getSourceRange();
4245     return true;
4246   }
4247 
4248   ValueDecl *D = nullptr;
4249   Expr *Inner = E->IgnoreParens();
4250   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4251     D = DRE->getDecl();
4252   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4253     D = ME->getMemberDecl();
4254   }
4255 
4256   // If it's a field, require the containing struct to have a
4257   // complete definition so that we can compute the layout.
4258   //
4259   // This can happen in C++11 onwards, either by naming the member
4260   // in a way that is not transformed into a member access expression
4261   // (in an unevaluated operand, for instance), or by naming the member
4262   // in a trailing-return-type.
4263   //
4264   // For the record, since __alignof__ on expressions is a GCC
4265   // extension, GCC seems to permit this but always gives the
4266   // nonsensical answer 0.
4267   //
4268   // We don't really need the layout here --- we could instead just
4269   // directly check for all the appropriate alignment-lowing
4270   // attributes --- but that would require duplicating a lot of
4271   // logic that just isn't worth duplicating for such a marginal
4272   // use-case.
4273   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4274     // Fast path this check, since we at least know the record has a
4275     // definition if we can find a member of it.
4276     if (!FD->getParent()->isCompleteDefinition()) {
4277       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4278         << E->getSourceRange();
4279       return true;
4280     }
4281 
4282     // Otherwise, if it's a field, and the field doesn't have
4283     // reference type, then it must have a complete type (or be a
4284     // flexible array member, which we explicitly want to
4285     // white-list anyway), which makes the following checks trivial.
4286     if (!FD->getType()->isReferenceType())
4287       return false;
4288   }
4289 
4290   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4291 }
4292 
4293 bool Sema::CheckVecStepExpr(Expr *E) {
4294   E = E->IgnoreParens();
4295 
4296   // Cannot know anything else if the expression is dependent.
4297   if (E->isTypeDependent())
4298     return false;
4299 
4300   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4301 }
4302 
4303 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4304                                         CapturingScopeInfo *CSI) {
4305   assert(T->isVariablyModifiedType());
4306   assert(CSI != nullptr);
4307 
4308   // We're going to walk down into the type and look for VLA expressions.
4309   do {
4310     const Type *Ty = T.getTypePtr();
4311     switch (Ty->getTypeClass()) {
4312 #define TYPE(Class, Base)
4313 #define ABSTRACT_TYPE(Class, Base)
4314 #define NON_CANONICAL_TYPE(Class, Base)
4315 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4317 #include "clang/AST/TypeNodes.inc"
4318       T = QualType();
4319       break;
4320     // These types are never variably-modified.
4321     case Type::Builtin:
4322     case Type::Complex:
4323     case Type::Vector:
4324     case Type::ExtVector:
4325     case Type::ConstantMatrix:
4326     case Type::Record:
4327     case Type::Enum:
4328     case Type::Elaborated:
4329     case Type::TemplateSpecialization:
4330     case Type::ObjCObject:
4331     case Type::ObjCInterface:
4332     case Type::ObjCObjectPointer:
4333     case Type::ObjCTypeParam:
4334     case Type::Pipe:
4335     case Type::ExtInt:
4336       llvm_unreachable("type class is never variably-modified!");
4337     case Type::Adjusted:
4338       T = cast<AdjustedType>(Ty)->getOriginalType();
4339       break;
4340     case Type::Decayed:
4341       T = cast<DecayedType>(Ty)->getPointeeType();
4342       break;
4343     case Type::Pointer:
4344       T = cast<PointerType>(Ty)->getPointeeType();
4345       break;
4346     case Type::BlockPointer:
4347       T = cast<BlockPointerType>(Ty)->getPointeeType();
4348       break;
4349     case Type::LValueReference:
4350     case Type::RValueReference:
4351       T = cast<ReferenceType>(Ty)->getPointeeType();
4352       break;
4353     case Type::MemberPointer:
4354       T = cast<MemberPointerType>(Ty)->getPointeeType();
4355       break;
4356     case Type::ConstantArray:
4357     case Type::IncompleteArray:
4358       // Losing element qualification here is fine.
4359       T = cast<ArrayType>(Ty)->getElementType();
4360       break;
4361     case Type::VariableArray: {
4362       // Losing element qualification here is fine.
4363       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4364 
4365       // Unknown size indication requires no size computation.
4366       // Otherwise, evaluate and record it.
4367       auto Size = VAT->getSizeExpr();
4368       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4369           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4370         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4371 
4372       T = VAT->getElementType();
4373       break;
4374     }
4375     case Type::FunctionProto:
4376     case Type::FunctionNoProto:
4377       T = cast<FunctionType>(Ty)->getReturnType();
4378       break;
4379     case Type::Paren:
4380     case Type::TypeOf:
4381     case Type::UnaryTransform:
4382     case Type::Attributed:
4383     case Type::SubstTemplateTypeParm:
4384     case Type::MacroQualified:
4385       // Keep walking after single level desugaring.
4386       T = T.getSingleStepDesugaredType(Context);
4387       break;
4388     case Type::Typedef:
4389       T = cast<TypedefType>(Ty)->desugar();
4390       break;
4391     case Type::Decltype:
4392       T = cast<DecltypeType>(Ty)->desugar();
4393       break;
4394     case Type::Auto:
4395     case Type::DeducedTemplateSpecialization:
4396       T = cast<DeducedType>(Ty)->getDeducedType();
4397       break;
4398     case Type::TypeOfExpr:
4399       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4400       break;
4401     case Type::Atomic:
4402       T = cast<AtomicType>(Ty)->getValueType();
4403       break;
4404     }
4405   } while (!T.isNull() && T->isVariablyModifiedType());
4406 }
4407 
4408 /// Build a sizeof or alignof expression given a type operand.
4409 ExprResult
4410 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4411                                      SourceLocation OpLoc,
4412                                      UnaryExprOrTypeTrait ExprKind,
4413                                      SourceRange R) {
4414   if (!TInfo)
4415     return ExprError();
4416 
4417   QualType T = TInfo->getType();
4418 
4419   if (!T->isDependentType() &&
4420       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4421     return ExprError();
4422 
4423   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4424     if (auto *TT = T->getAs<TypedefType>()) {
4425       for (auto I = FunctionScopes.rbegin(),
4426                 E = std::prev(FunctionScopes.rend());
4427            I != E; ++I) {
4428         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4429         if (CSI == nullptr)
4430           break;
4431         DeclContext *DC = nullptr;
4432         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4433           DC = LSI->CallOperator;
4434         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4435           DC = CRSI->TheCapturedDecl;
4436         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4437           DC = BSI->TheDecl;
4438         if (DC) {
4439           if (DC->containsDecl(TT->getDecl()))
4440             break;
4441           captureVariablyModifiedType(Context, T, CSI);
4442         }
4443       }
4444     }
4445   }
4446 
4447   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4448   return new (Context) UnaryExprOrTypeTraitExpr(
4449       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4450 }
4451 
4452 /// Build a sizeof or alignof expression given an expression
4453 /// operand.
4454 ExprResult
4455 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4456                                      UnaryExprOrTypeTrait ExprKind) {
4457   ExprResult PE = CheckPlaceholderExpr(E);
4458   if (PE.isInvalid())
4459     return ExprError();
4460 
4461   E = PE.get();
4462 
4463   // Verify that the operand is valid.
4464   bool isInvalid = false;
4465   if (E->isTypeDependent()) {
4466     // Delay type-checking for type-dependent expressions.
4467   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4468     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4469   } else if (ExprKind == UETT_VecStep) {
4470     isInvalid = CheckVecStepExpr(E);
4471   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4472       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4473       isInvalid = true;
4474   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4475     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4476     isInvalid = true;
4477   } else {
4478     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4479   }
4480 
4481   if (isInvalid)
4482     return ExprError();
4483 
4484   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4485     PE = TransformToPotentiallyEvaluated(E);
4486     if (PE.isInvalid()) return ExprError();
4487     E = PE.get();
4488   }
4489 
4490   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4491   return new (Context) UnaryExprOrTypeTraitExpr(
4492       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4493 }
4494 
4495 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4496 /// expr and the same for @c alignof and @c __alignof
4497 /// Note that the ArgRange is invalid if isType is false.
4498 ExprResult
4499 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4500                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4501                                     void *TyOrEx, SourceRange ArgRange) {
4502   // If error parsing type, ignore.
4503   if (!TyOrEx) return ExprError();
4504 
4505   if (IsType) {
4506     TypeSourceInfo *TInfo;
4507     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4508     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4509   }
4510 
4511   Expr *ArgEx = (Expr *)TyOrEx;
4512   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4513   return Result;
4514 }
4515 
4516 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4517                                      bool IsReal) {
4518   if (V.get()->isTypeDependent())
4519     return S.Context.DependentTy;
4520 
4521   // _Real and _Imag are only l-values for normal l-values.
4522   if (V.get()->getObjectKind() != OK_Ordinary) {
4523     V = S.DefaultLvalueConversion(V.get());
4524     if (V.isInvalid())
4525       return QualType();
4526   }
4527 
4528   // These operators return the element type of a complex type.
4529   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4530     return CT->getElementType();
4531 
4532   // Otherwise they pass through real integer and floating point types here.
4533   if (V.get()->getType()->isArithmeticType())
4534     return V.get()->getType();
4535 
4536   // Test for placeholders.
4537   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4538   if (PR.isInvalid()) return QualType();
4539   if (PR.get() != V.get()) {
4540     V = PR;
4541     return CheckRealImagOperand(S, V, Loc, IsReal);
4542   }
4543 
4544   // Reject anything else.
4545   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4546     << (IsReal ? "__real" : "__imag");
4547   return QualType();
4548 }
4549 
4550 
4551 
4552 ExprResult
4553 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4554                           tok::TokenKind Kind, Expr *Input) {
4555   UnaryOperatorKind Opc;
4556   switch (Kind) {
4557   default: llvm_unreachable("Unknown unary op!");
4558   case tok::plusplus:   Opc = UO_PostInc; break;
4559   case tok::minusminus: Opc = UO_PostDec; break;
4560   }
4561 
4562   // Since this might is a postfix expression, get rid of ParenListExprs.
4563   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4564   if (Result.isInvalid()) return ExprError();
4565   Input = Result.get();
4566 
4567   return BuildUnaryOp(S, OpLoc, Opc, Input);
4568 }
4569 
4570 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4571 ///
4572 /// \return true on error
4573 static bool checkArithmeticOnObjCPointer(Sema &S,
4574                                          SourceLocation opLoc,
4575                                          Expr *op) {
4576   assert(op->getType()->isObjCObjectPointerType());
4577   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4578       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4579     return false;
4580 
4581   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4582     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4583     << op->getSourceRange();
4584   return true;
4585 }
4586 
4587 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4588   auto *BaseNoParens = Base->IgnoreParens();
4589   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4590     return MSProp->getPropertyDecl()->getType()->isArrayType();
4591   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4592 }
4593 
4594 ExprResult
4595 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4596                               Expr *idx, SourceLocation rbLoc) {
4597   if (base && !base->getType().isNull() &&
4598       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4599     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4600                                     SourceLocation(), /*Length*/ nullptr,
4601                                     /*Stride=*/nullptr, rbLoc);
4602 
4603   // Since this might be a postfix expression, get rid of ParenListExprs.
4604   if (isa<ParenListExpr>(base)) {
4605     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4606     if (result.isInvalid()) return ExprError();
4607     base = result.get();
4608   }
4609 
4610   // Check if base and idx form a MatrixSubscriptExpr.
4611   //
4612   // Helper to check for comma expressions, which are not allowed as indices for
4613   // matrix subscript expressions.
4614   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4615     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4616       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4617           << SourceRange(base->getBeginLoc(), rbLoc);
4618       return true;
4619     }
4620     return false;
4621   };
4622   // The matrix subscript operator ([][])is considered a single operator.
4623   // Separating the index expressions by parenthesis is not allowed.
4624   if (base->getType()->isSpecificPlaceholderType(
4625           BuiltinType::IncompleteMatrixIdx) &&
4626       !isa<MatrixSubscriptExpr>(base)) {
4627     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4628         << SourceRange(base->getBeginLoc(), rbLoc);
4629     return ExprError();
4630   }
4631   // If the base is a MatrixSubscriptExpr, try to create a new
4632   // MatrixSubscriptExpr.
4633   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4634   if (matSubscriptE) {
4635     if (CheckAndReportCommaError(idx))
4636       return ExprError();
4637 
4638     assert(matSubscriptE->isIncomplete() &&
4639            "base has to be an incomplete matrix subscript");
4640     return CreateBuiltinMatrixSubscriptExpr(
4641         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4642   }
4643 
4644   // Handle any non-overload placeholder types in the base and index
4645   // expressions.  We can't handle overloads here because the other
4646   // operand might be an overloadable type, in which case the overload
4647   // resolution for the operator overload should get the first crack
4648   // at the overload.
4649   bool IsMSPropertySubscript = false;
4650   if (base->getType()->isNonOverloadPlaceholderType()) {
4651     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4652     if (!IsMSPropertySubscript) {
4653       ExprResult result = CheckPlaceholderExpr(base);
4654       if (result.isInvalid())
4655         return ExprError();
4656       base = result.get();
4657     }
4658   }
4659 
4660   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4661   if (base->getType()->isMatrixType()) {
4662     if (CheckAndReportCommaError(idx))
4663       return ExprError();
4664 
4665     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4666   }
4667 
4668   // A comma-expression as the index is deprecated in C++2a onwards.
4669   if (getLangOpts().CPlusPlus20 &&
4670       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4671        (isa<CXXOperatorCallExpr>(idx) &&
4672         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4673     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4674         << SourceRange(base->getBeginLoc(), rbLoc);
4675   }
4676 
4677   if (idx->getType()->isNonOverloadPlaceholderType()) {
4678     ExprResult result = CheckPlaceholderExpr(idx);
4679     if (result.isInvalid()) return ExprError();
4680     idx = result.get();
4681   }
4682 
4683   // Build an unanalyzed expression if either operand is type-dependent.
4684   if (getLangOpts().CPlusPlus &&
4685       (base->isTypeDependent() || idx->isTypeDependent())) {
4686     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4687                                             VK_LValue, OK_Ordinary, rbLoc);
4688   }
4689 
4690   // MSDN, property (C++)
4691   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4692   // This attribute can also be used in the declaration of an empty array in a
4693   // class or structure definition. For example:
4694   // __declspec(property(get=GetX, put=PutX)) int x[];
4695   // The above statement indicates that x[] can be used with one or more array
4696   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4697   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4698   if (IsMSPropertySubscript) {
4699     // Build MS property subscript expression if base is MS property reference
4700     // or MS property subscript.
4701     return new (Context) MSPropertySubscriptExpr(
4702         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4703   }
4704 
4705   // Use C++ overloaded-operator rules if either operand has record
4706   // type.  The spec says to do this if either type is *overloadable*,
4707   // but enum types can't declare subscript operators or conversion
4708   // operators, so there's nothing interesting for overload resolution
4709   // to do if there aren't any record types involved.
4710   //
4711   // ObjC pointers have their own subscripting logic that is not tied
4712   // to overload resolution and so should not take this path.
4713   if (getLangOpts().CPlusPlus &&
4714       (base->getType()->isRecordType() ||
4715        (!base->getType()->isObjCObjectPointerType() &&
4716         idx->getType()->isRecordType()))) {
4717     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4718   }
4719 
4720   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4721 
4722   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4723     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4724 
4725   return Res;
4726 }
4727 
4728 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4729   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4730   InitializationKind Kind =
4731       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4732   InitializationSequence InitSeq(*this, Entity, Kind, E);
4733   return InitSeq.Perform(*this, Entity, Kind, E);
4734 }
4735 
4736 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4737                                                   Expr *ColumnIdx,
4738                                                   SourceLocation RBLoc) {
4739   ExprResult BaseR = CheckPlaceholderExpr(Base);
4740   if (BaseR.isInvalid())
4741     return BaseR;
4742   Base = BaseR.get();
4743 
4744   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4745   if (RowR.isInvalid())
4746     return RowR;
4747   RowIdx = RowR.get();
4748 
4749   if (!ColumnIdx)
4750     return new (Context) MatrixSubscriptExpr(
4751         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4752 
4753   // Build an unanalyzed expression if any of the operands is type-dependent.
4754   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4755       ColumnIdx->isTypeDependent())
4756     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4757                                              Context.DependentTy, RBLoc);
4758 
4759   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4760   if (ColumnR.isInvalid())
4761     return ColumnR;
4762   ColumnIdx = ColumnR.get();
4763 
4764   // Check that IndexExpr is an integer expression. If it is a constant
4765   // expression, check that it is less than Dim (= the number of elements in the
4766   // corresponding dimension).
4767   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4768                           bool IsColumnIdx) -> Expr * {
4769     if (!IndexExpr->getType()->isIntegerType() &&
4770         !IndexExpr->isTypeDependent()) {
4771       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4772           << IsColumnIdx;
4773       return nullptr;
4774     }
4775 
4776     if (Optional<llvm::APSInt> Idx =
4777             IndexExpr->getIntegerConstantExpr(Context)) {
4778       if ((*Idx < 0 || *Idx >= Dim)) {
4779         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4780             << IsColumnIdx << Dim;
4781         return nullptr;
4782       }
4783     }
4784 
4785     ExprResult ConvExpr =
4786         tryConvertExprToType(IndexExpr, Context.getSizeType());
4787     assert(!ConvExpr.isInvalid() &&
4788            "should be able to convert any integer type to size type");
4789     return ConvExpr.get();
4790   };
4791 
4792   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4793   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4794   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4795   if (!RowIdx || !ColumnIdx)
4796     return ExprError();
4797 
4798   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4799                                            MTy->getElementType(), RBLoc);
4800 }
4801 
4802 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4803   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4804   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4805 
4806   // For expressions like `&(*s).b`, the base is recorded and what should be
4807   // checked.
4808   const MemberExpr *Member = nullptr;
4809   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4810     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4811 
4812   LastRecord.PossibleDerefs.erase(StrippedExpr);
4813 }
4814 
4815 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4816   if (isUnevaluatedContext())
4817     return;
4818 
4819   QualType ResultTy = E->getType();
4820   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4821 
4822   // Bail if the element is an array since it is not memory access.
4823   if (isa<ArrayType>(ResultTy))
4824     return;
4825 
4826   if (ResultTy->hasAttr(attr::NoDeref)) {
4827     LastRecord.PossibleDerefs.insert(E);
4828     return;
4829   }
4830 
4831   // Check if the base type is a pointer to a member access of a struct
4832   // marked with noderef.
4833   const Expr *Base = E->getBase();
4834   QualType BaseTy = Base->getType();
4835   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4836     // Not a pointer access
4837     return;
4838 
4839   const MemberExpr *Member = nullptr;
4840   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4841          Member->isArrow())
4842     Base = Member->getBase();
4843 
4844   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4845     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4846       LastRecord.PossibleDerefs.insert(E);
4847   }
4848 }
4849 
4850 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4851                                           Expr *LowerBound,
4852                                           SourceLocation ColonLocFirst,
4853                                           SourceLocation ColonLocSecond,
4854                                           Expr *Length, Expr *Stride,
4855                                           SourceLocation RBLoc) {
4856   if (Base->getType()->isPlaceholderType() &&
4857       !Base->getType()->isSpecificPlaceholderType(
4858           BuiltinType::OMPArraySection)) {
4859     ExprResult Result = CheckPlaceholderExpr(Base);
4860     if (Result.isInvalid())
4861       return ExprError();
4862     Base = Result.get();
4863   }
4864   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4865     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4866     if (Result.isInvalid())
4867       return ExprError();
4868     Result = DefaultLvalueConversion(Result.get());
4869     if (Result.isInvalid())
4870       return ExprError();
4871     LowerBound = Result.get();
4872   }
4873   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4874     ExprResult Result = CheckPlaceholderExpr(Length);
4875     if (Result.isInvalid())
4876       return ExprError();
4877     Result = DefaultLvalueConversion(Result.get());
4878     if (Result.isInvalid())
4879       return ExprError();
4880     Length = Result.get();
4881   }
4882   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4883     ExprResult Result = CheckPlaceholderExpr(Stride);
4884     if (Result.isInvalid())
4885       return ExprError();
4886     Result = DefaultLvalueConversion(Result.get());
4887     if (Result.isInvalid())
4888       return ExprError();
4889     Stride = Result.get();
4890   }
4891 
4892   // Build an unanalyzed expression if either operand is type-dependent.
4893   if (Base->isTypeDependent() ||
4894       (LowerBound &&
4895        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4896       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4897       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4898     return new (Context) OMPArraySectionExpr(
4899         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4900         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4901   }
4902 
4903   // Perform default conversions.
4904   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4905   QualType ResultTy;
4906   if (OriginalTy->isAnyPointerType()) {
4907     ResultTy = OriginalTy->getPointeeType();
4908   } else if (OriginalTy->isArrayType()) {
4909     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4910   } else {
4911     return ExprError(
4912         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4913         << Base->getSourceRange());
4914   }
4915   // C99 6.5.2.1p1
4916   if (LowerBound) {
4917     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4918                                                       LowerBound);
4919     if (Res.isInvalid())
4920       return ExprError(Diag(LowerBound->getExprLoc(),
4921                             diag::err_omp_typecheck_section_not_integer)
4922                        << 0 << LowerBound->getSourceRange());
4923     LowerBound = Res.get();
4924 
4925     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4926         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4927       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4928           << 0 << LowerBound->getSourceRange();
4929   }
4930   if (Length) {
4931     auto Res =
4932         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4933     if (Res.isInvalid())
4934       return ExprError(Diag(Length->getExprLoc(),
4935                             diag::err_omp_typecheck_section_not_integer)
4936                        << 1 << Length->getSourceRange());
4937     Length = Res.get();
4938 
4939     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4940         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4941       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4942           << 1 << Length->getSourceRange();
4943   }
4944   if (Stride) {
4945     ExprResult Res =
4946         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4947     if (Res.isInvalid())
4948       return ExprError(Diag(Stride->getExprLoc(),
4949                             diag::err_omp_typecheck_section_not_integer)
4950                        << 1 << Stride->getSourceRange());
4951     Stride = Res.get();
4952 
4953     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4954         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4955       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4956           << 1 << Stride->getSourceRange();
4957   }
4958 
4959   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4960   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4961   // type. Note that functions are not objects, and that (in C99 parlance)
4962   // incomplete types are not object types.
4963   if (ResultTy->isFunctionType()) {
4964     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4965         << ResultTy << Base->getSourceRange();
4966     return ExprError();
4967   }
4968 
4969   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4970                           diag::err_omp_section_incomplete_type, Base))
4971     return ExprError();
4972 
4973   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4974     Expr::EvalResult Result;
4975     if (LowerBound->EvaluateAsInt(Result, Context)) {
4976       // OpenMP 5.0, [2.1.5 Array Sections]
4977       // The array section must be a subset of the original array.
4978       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4979       if (LowerBoundValue.isNegative()) {
4980         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4981             << LowerBound->getSourceRange();
4982         return ExprError();
4983       }
4984     }
4985   }
4986 
4987   if (Length) {
4988     Expr::EvalResult Result;
4989     if (Length->EvaluateAsInt(Result, Context)) {
4990       // OpenMP 5.0, [2.1.5 Array Sections]
4991       // The length must evaluate to non-negative integers.
4992       llvm::APSInt LengthValue = Result.Val.getInt();
4993       if (LengthValue.isNegative()) {
4994         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4995             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4996             << Length->getSourceRange();
4997         return ExprError();
4998       }
4999     }
5000   } else if (ColonLocFirst.isValid() &&
5001              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5002                                       !OriginalTy->isVariableArrayType()))) {
5003     // OpenMP 5.0, [2.1.5 Array Sections]
5004     // When the size of the array dimension is not known, the length must be
5005     // specified explicitly.
5006     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5007         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5008     return ExprError();
5009   }
5010 
5011   if (Stride) {
5012     Expr::EvalResult Result;
5013     if (Stride->EvaluateAsInt(Result, Context)) {
5014       // OpenMP 5.0, [2.1.5 Array Sections]
5015       // The stride must evaluate to a positive integer.
5016       llvm::APSInt StrideValue = Result.Val.getInt();
5017       if (!StrideValue.isStrictlyPositive()) {
5018         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5019             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5020             << Stride->getSourceRange();
5021         return ExprError();
5022       }
5023     }
5024   }
5025 
5026   if (!Base->getType()->isSpecificPlaceholderType(
5027           BuiltinType::OMPArraySection)) {
5028     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5029     if (Result.isInvalid())
5030       return ExprError();
5031     Base = Result.get();
5032   }
5033   return new (Context) OMPArraySectionExpr(
5034       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5035       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5036 }
5037 
5038 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5039                                           SourceLocation RParenLoc,
5040                                           ArrayRef<Expr *> Dims,
5041                                           ArrayRef<SourceRange> Brackets) {
5042   if (Base->getType()->isPlaceholderType()) {
5043     ExprResult Result = CheckPlaceholderExpr(Base);
5044     if (Result.isInvalid())
5045       return ExprError();
5046     Result = DefaultLvalueConversion(Result.get());
5047     if (Result.isInvalid())
5048       return ExprError();
5049     Base = Result.get();
5050   }
5051   QualType BaseTy = Base->getType();
5052   // Delay analysis of the types/expressions if instantiation/specialization is
5053   // required.
5054   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5055     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5056                                        LParenLoc, RParenLoc, Dims, Brackets);
5057   if (!BaseTy->isPointerType() ||
5058       (!Base->isTypeDependent() &&
5059        BaseTy->getPointeeType()->isIncompleteType()))
5060     return ExprError(Diag(Base->getExprLoc(),
5061                           diag::err_omp_non_pointer_type_array_shaping_base)
5062                      << Base->getSourceRange());
5063 
5064   SmallVector<Expr *, 4> NewDims;
5065   bool ErrorFound = false;
5066   for (Expr *Dim : Dims) {
5067     if (Dim->getType()->isPlaceholderType()) {
5068       ExprResult Result = CheckPlaceholderExpr(Dim);
5069       if (Result.isInvalid()) {
5070         ErrorFound = true;
5071         continue;
5072       }
5073       Result = DefaultLvalueConversion(Result.get());
5074       if (Result.isInvalid()) {
5075         ErrorFound = true;
5076         continue;
5077       }
5078       Dim = Result.get();
5079     }
5080     if (!Dim->isTypeDependent()) {
5081       ExprResult Result =
5082           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5083       if (Result.isInvalid()) {
5084         ErrorFound = true;
5085         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5086             << Dim->getSourceRange();
5087         continue;
5088       }
5089       Dim = Result.get();
5090       Expr::EvalResult EvResult;
5091       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5092         // OpenMP 5.0, [2.1.4 Array Shaping]
5093         // Each si is an integral type expression that must evaluate to a
5094         // positive integer.
5095         llvm::APSInt Value = EvResult.Val.getInt();
5096         if (!Value.isStrictlyPositive()) {
5097           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5098               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5099               << Dim->getSourceRange();
5100           ErrorFound = true;
5101           continue;
5102         }
5103       }
5104     }
5105     NewDims.push_back(Dim);
5106   }
5107   if (ErrorFound)
5108     return ExprError();
5109   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5110                                      LParenLoc, RParenLoc, NewDims, Brackets);
5111 }
5112 
5113 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5114                                       SourceLocation LLoc, SourceLocation RLoc,
5115                                       ArrayRef<OMPIteratorData> Data) {
5116   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5117   bool IsCorrect = true;
5118   for (const OMPIteratorData &D : Data) {
5119     TypeSourceInfo *TInfo = nullptr;
5120     SourceLocation StartLoc;
5121     QualType DeclTy;
5122     if (!D.Type.getAsOpaquePtr()) {
5123       // OpenMP 5.0, 2.1.6 Iterators
5124       // In an iterator-specifier, if the iterator-type is not specified then
5125       // the type of that iterator is of int type.
5126       DeclTy = Context.IntTy;
5127       StartLoc = D.DeclIdentLoc;
5128     } else {
5129       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5130       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5131     }
5132 
5133     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5134                              DeclTy->containsUnexpandedParameterPack() ||
5135                              DeclTy->isInstantiationDependentType();
5136     if (!IsDeclTyDependent) {
5137       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5138         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5139         // The iterator-type must be an integral or pointer type.
5140         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5141             << DeclTy;
5142         IsCorrect = false;
5143         continue;
5144       }
5145       if (DeclTy.isConstant(Context)) {
5146         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5147         // The iterator-type must not be const qualified.
5148         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5149             << DeclTy;
5150         IsCorrect = false;
5151         continue;
5152       }
5153     }
5154 
5155     // Iterator declaration.
5156     assert(D.DeclIdent && "Identifier expected.");
5157     // Always try to create iterator declarator to avoid extra error messages
5158     // about unknown declarations use.
5159     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5160                                D.DeclIdent, DeclTy, TInfo, SC_None);
5161     VD->setImplicit();
5162     if (S) {
5163       // Check for conflicting previous declaration.
5164       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5165       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5166                             ForVisibleRedeclaration);
5167       Previous.suppressDiagnostics();
5168       LookupName(Previous, S);
5169 
5170       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5171                            /*AllowInlineNamespace=*/false);
5172       if (!Previous.empty()) {
5173         NamedDecl *Old = Previous.getRepresentativeDecl();
5174         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5175         Diag(Old->getLocation(), diag::note_previous_definition);
5176       } else {
5177         PushOnScopeChains(VD, S);
5178       }
5179     } else {
5180       CurContext->addDecl(VD);
5181     }
5182     Expr *Begin = D.Range.Begin;
5183     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5184       ExprResult BeginRes =
5185           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5186       Begin = BeginRes.get();
5187     }
5188     Expr *End = D.Range.End;
5189     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5190       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5191       End = EndRes.get();
5192     }
5193     Expr *Step = D.Range.Step;
5194     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5195       if (!Step->getType()->isIntegralType(Context)) {
5196         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5197             << Step << Step->getSourceRange();
5198         IsCorrect = false;
5199         continue;
5200       }
5201       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5202       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5203       // If the step expression of a range-specification equals zero, the
5204       // behavior is unspecified.
5205       if (Result && Result->isNullValue()) {
5206         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5207             << Step << Step->getSourceRange();
5208         IsCorrect = false;
5209         continue;
5210       }
5211     }
5212     if (!Begin || !End || !IsCorrect) {
5213       IsCorrect = false;
5214       continue;
5215     }
5216     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5217     IDElem.IteratorDecl = VD;
5218     IDElem.AssignmentLoc = D.AssignLoc;
5219     IDElem.Range.Begin = Begin;
5220     IDElem.Range.End = End;
5221     IDElem.Range.Step = Step;
5222     IDElem.ColonLoc = D.ColonLoc;
5223     IDElem.SecondColonLoc = D.SecColonLoc;
5224   }
5225   if (!IsCorrect) {
5226     // Invalidate all created iterator declarations if error is found.
5227     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5228       if (Decl *ID = D.IteratorDecl)
5229         ID->setInvalidDecl();
5230     }
5231     return ExprError();
5232   }
5233   SmallVector<OMPIteratorHelperData, 4> Helpers;
5234   if (!CurContext->isDependentContext()) {
5235     // Build number of ityeration for each iteration range.
5236     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5237     // ((Begini-Stepi-1-Endi) / -Stepi);
5238     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5239       // (Endi - Begini)
5240       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5241                                           D.Range.Begin);
5242       if(!Res.isUsable()) {
5243         IsCorrect = false;
5244         continue;
5245       }
5246       ExprResult St, St1;
5247       if (D.Range.Step) {
5248         St = D.Range.Step;
5249         // (Endi - Begini) + Stepi
5250         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5251         if (!Res.isUsable()) {
5252           IsCorrect = false;
5253           continue;
5254         }
5255         // (Endi - Begini) + Stepi - 1
5256         Res =
5257             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5258                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5259         if (!Res.isUsable()) {
5260           IsCorrect = false;
5261           continue;
5262         }
5263         // ((Endi - Begini) + Stepi - 1) / Stepi
5264         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5265         if (!Res.isUsable()) {
5266           IsCorrect = false;
5267           continue;
5268         }
5269         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5270         // (Begini - Endi)
5271         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5272                                              D.Range.Begin, D.Range.End);
5273         if (!Res1.isUsable()) {
5274           IsCorrect = false;
5275           continue;
5276         }
5277         // (Begini - Endi) - Stepi
5278         Res1 =
5279             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5280         if (!Res1.isUsable()) {
5281           IsCorrect = false;
5282           continue;
5283         }
5284         // (Begini - Endi) - Stepi - 1
5285         Res1 =
5286             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5287                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5288         if (!Res1.isUsable()) {
5289           IsCorrect = false;
5290           continue;
5291         }
5292         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5293         Res1 =
5294             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5295         if (!Res1.isUsable()) {
5296           IsCorrect = false;
5297           continue;
5298         }
5299         // Stepi > 0.
5300         ExprResult CmpRes =
5301             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5302                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5303         if (!CmpRes.isUsable()) {
5304           IsCorrect = false;
5305           continue;
5306         }
5307         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5308                                  Res.get(), Res1.get());
5309         if (!Res.isUsable()) {
5310           IsCorrect = false;
5311           continue;
5312         }
5313       }
5314       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5315       if (!Res.isUsable()) {
5316         IsCorrect = false;
5317         continue;
5318       }
5319 
5320       // Build counter update.
5321       // Build counter.
5322       auto *CounterVD =
5323           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5324                           D.IteratorDecl->getBeginLoc(), nullptr,
5325                           Res.get()->getType(), nullptr, SC_None);
5326       CounterVD->setImplicit();
5327       ExprResult RefRes =
5328           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5329                            D.IteratorDecl->getBeginLoc());
5330       // Build counter update.
5331       // I = Begini + counter * Stepi;
5332       ExprResult UpdateRes;
5333       if (D.Range.Step) {
5334         UpdateRes = CreateBuiltinBinOp(
5335             D.AssignmentLoc, BO_Mul,
5336             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5337       } else {
5338         UpdateRes = DefaultLvalueConversion(RefRes.get());
5339       }
5340       if (!UpdateRes.isUsable()) {
5341         IsCorrect = false;
5342         continue;
5343       }
5344       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5345                                      UpdateRes.get());
5346       if (!UpdateRes.isUsable()) {
5347         IsCorrect = false;
5348         continue;
5349       }
5350       ExprResult VDRes =
5351           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5352                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5353                            D.IteratorDecl->getBeginLoc());
5354       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5355                                      UpdateRes.get());
5356       if (!UpdateRes.isUsable()) {
5357         IsCorrect = false;
5358         continue;
5359       }
5360       UpdateRes =
5361           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5362       if (!UpdateRes.isUsable()) {
5363         IsCorrect = false;
5364         continue;
5365       }
5366       ExprResult CounterUpdateRes =
5367           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5368       if (!CounterUpdateRes.isUsable()) {
5369         IsCorrect = false;
5370         continue;
5371       }
5372       CounterUpdateRes =
5373           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5374       if (!CounterUpdateRes.isUsable()) {
5375         IsCorrect = false;
5376         continue;
5377       }
5378       OMPIteratorHelperData &HD = Helpers.emplace_back();
5379       HD.CounterVD = CounterVD;
5380       HD.Upper = Res.get();
5381       HD.Update = UpdateRes.get();
5382       HD.CounterUpdate = CounterUpdateRes.get();
5383     }
5384   } else {
5385     Helpers.assign(ID.size(), {});
5386   }
5387   if (!IsCorrect) {
5388     // Invalidate all created iterator declarations if error is found.
5389     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5390       if (Decl *ID = D.IteratorDecl)
5391         ID->setInvalidDecl();
5392     }
5393     return ExprError();
5394   }
5395   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5396                                  LLoc, RLoc, ID, Helpers);
5397 }
5398 
5399 ExprResult
5400 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5401                                       Expr *Idx, SourceLocation RLoc) {
5402   Expr *LHSExp = Base;
5403   Expr *RHSExp = Idx;
5404 
5405   ExprValueKind VK = VK_LValue;
5406   ExprObjectKind OK = OK_Ordinary;
5407 
5408   // Per C++ core issue 1213, the result is an xvalue if either operand is
5409   // a non-lvalue array, and an lvalue otherwise.
5410   if (getLangOpts().CPlusPlus11) {
5411     for (auto *Op : {LHSExp, RHSExp}) {
5412       Op = Op->IgnoreImplicit();
5413       if (Op->getType()->isArrayType() && !Op->isLValue())
5414         VK = VK_XValue;
5415     }
5416   }
5417 
5418   // Perform default conversions.
5419   if (!LHSExp->getType()->getAs<VectorType>()) {
5420     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5421     if (Result.isInvalid())
5422       return ExprError();
5423     LHSExp = Result.get();
5424   }
5425   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5426   if (Result.isInvalid())
5427     return ExprError();
5428   RHSExp = Result.get();
5429 
5430   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5431 
5432   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5433   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5434   // in the subscript position. As a result, we need to derive the array base
5435   // and index from the expression types.
5436   Expr *BaseExpr, *IndexExpr;
5437   QualType ResultType;
5438   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5439     BaseExpr = LHSExp;
5440     IndexExpr = RHSExp;
5441     ResultType = Context.DependentTy;
5442   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5443     BaseExpr = LHSExp;
5444     IndexExpr = RHSExp;
5445     ResultType = PTy->getPointeeType();
5446   } else if (const ObjCObjectPointerType *PTy =
5447                LHSTy->getAs<ObjCObjectPointerType>()) {
5448     BaseExpr = LHSExp;
5449     IndexExpr = RHSExp;
5450 
5451     // Use custom logic if this should be the pseudo-object subscript
5452     // expression.
5453     if (!LangOpts.isSubscriptPointerArithmetic())
5454       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5455                                           nullptr);
5456 
5457     ResultType = PTy->getPointeeType();
5458   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5459      // Handle the uncommon case of "123[Ptr]".
5460     BaseExpr = RHSExp;
5461     IndexExpr = LHSExp;
5462     ResultType = PTy->getPointeeType();
5463   } else if (const ObjCObjectPointerType *PTy =
5464                RHSTy->getAs<ObjCObjectPointerType>()) {
5465      // Handle the uncommon case of "123[Ptr]".
5466     BaseExpr = RHSExp;
5467     IndexExpr = LHSExp;
5468     ResultType = PTy->getPointeeType();
5469     if (!LangOpts.isSubscriptPointerArithmetic()) {
5470       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5471         << ResultType << BaseExpr->getSourceRange();
5472       return ExprError();
5473     }
5474   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5475     BaseExpr = LHSExp;    // vectors: V[123]
5476     IndexExpr = RHSExp;
5477     // We apply C++ DR1213 to vector subscripting too.
5478     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5479       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5480       if (Materialized.isInvalid())
5481         return ExprError();
5482       LHSExp = Materialized.get();
5483     }
5484     VK = LHSExp->getValueKind();
5485     if (VK != VK_RValue)
5486       OK = OK_VectorComponent;
5487 
5488     ResultType = VTy->getElementType();
5489     QualType BaseType = BaseExpr->getType();
5490     Qualifiers BaseQuals = BaseType.getQualifiers();
5491     Qualifiers MemberQuals = ResultType.getQualifiers();
5492     Qualifiers Combined = BaseQuals + MemberQuals;
5493     if (Combined != MemberQuals)
5494       ResultType = Context.getQualifiedType(ResultType, Combined);
5495   } else if (LHSTy->isArrayType()) {
5496     // If we see an array that wasn't promoted by
5497     // DefaultFunctionArrayLvalueConversion, it must be an array that
5498     // wasn't promoted because of the C90 rule that doesn't
5499     // allow promoting non-lvalue arrays.  Warn, then
5500     // force the promotion here.
5501     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5502         << LHSExp->getSourceRange();
5503     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5504                                CK_ArrayToPointerDecay).get();
5505     LHSTy = LHSExp->getType();
5506 
5507     BaseExpr = LHSExp;
5508     IndexExpr = RHSExp;
5509     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5510   } else if (RHSTy->isArrayType()) {
5511     // Same as previous, except for 123[f().a] case
5512     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5513         << RHSExp->getSourceRange();
5514     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5515                                CK_ArrayToPointerDecay).get();
5516     RHSTy = RHSExp->getType();
5517 
5518     BaseExpr = RHSExp;
5519     IndexExpr = LHSExp;
5520     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5521   } else {
5522     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5523        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5524   }
5525   // C99 6.5.2.1p1
5526   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5527     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5528                      << IndexExpr->getSourceRange());
5529 
5530   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5531        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5532          && !IndexExpr->isTypeDependent())
5533     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5534 
5535   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5536   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5537   // type. Note that Functions are not objects, and that (in C99 parlance)
5538   // incomplete types are not object types.
5539   if (ResultType->isFunctionType()) {
5540     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5541         << ResultType << BaseExpr->getSourceRange();
5542     return ExprError();
5543   }
5544 
5545   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5546     // GNU extension: subscripting on pointer to void
5547     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5548       << BaseExpr->getSourceRange();
5549 
5550     // C forbids expressions of unqualified void type from being l-values.
5551     // See IsCForbiddenLValueType.
5552     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5553   } else if (!ResultType->isDependentType() &&
5554              RequireCompleteSizedType(
5555                  LLoc, ResultType,
5556                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5557     return ExprError();
5558 
5559   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5560          !ResultType.isCForbiddenLValueType());
5561 
5562   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5563       FunctionScopes.size() > 1) {
5564     if (auto *TT =
5565             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5566       for (auto I = FunctionScopes.rbegin(),
5567                 E = std::prev(FunctionScopes.rend());
5568            I != E; ++I) {
5569         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5570         if (CSI == nullptr)
5571           break;
5572         DeclContext *DC = nullptr;
5573         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5574           DC = LSI->CallOperator;
5575         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5576           DC = CRSI->TheCapturedDecl;
5577         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5578           DC = BSI->TheDecl;
5579         if (DC) {
5580           if (DC->containsDecl(TT->getDecl()))
5581             break;
5582           captureVariablyModifiedType(
5583               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5584         }
5585       }
5586     }
5587   }
5588 
5589   return new (Context)
5590       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5591 }
5592 
5593 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5594                                   ParmVarDecl *Param) {
5595   if (Param->hasUnparsedDefaultArg()) {
5596     // If we've already cleared out the location for the default argument,
5597     // that means we're parsing it right now.
5598     if (!UnparsedDefaultArgLocs.count(Param)) {
5599       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5600       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5601       Param->setInvalidDecl();
5602       return true;
5603     }
5604 
5605     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5606         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5607     Diag(UnparsedDefaultArgLocs[Param],
5608          diag::note_default_argument_declared_here);
5609     return true;
5610   }
5611 
5612   if (Param->hasUninstantiatedDefaultArg() &&
5613       InstantiateDefaultArgument(CallLoc, FD, Param))
5614     return true;
5615 
5616   assert(Param->hasInit() && "default argument but no initializer?");
5617 
5618   // If the default expression creates temporaries, we need to
5619   // push them to the current stack of expression temporaries so they'll
5620   // be properly destroyed.
5621   // FIXME: We should really be rebuilding the default argument with new
5622   // bound temporaries; see the comment in PR5810.
5623   // We don't need to do that with block decls, though, because
5624   // blocks in default argument expression can never capture anything.
5625   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5626     // Set the "needs cleanups" bit regardless of whether there are
5627     // any explicit objects.
5628     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5629 
5630     // Append all the objects to the cleanup list.  Right now, this
5631     // should always be a no-op, because blocks in default argument
5632     // expressions should never be able to capture anything.
5633     assert(!Init->getNumObjects() &&
5634            "default argument expression has capturing blocks?");
5635   }
5636 
5637   // We already type-checked the argument, so we know it works.
5638   // Just mark all of the declarations in this potentially-evaluated expression
5639   // as being "referenced".
5640   EnterExpressionEvaluationContext EvalContext(
5641       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5642   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5643                                    /*SkipLocalVariables=*/true);
5644   return false;
5645 }
5646 
5647 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5648                                         FunctionDecl *FD, ParmVarDecl *Param) {
5649   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5650   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5651     return ExprError();
5652   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5653 }
5654 
5655 Sema::VariadicCallType
5656 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5657                           Expr *Fn) {
5658   if (Proto && Proto->isVariadic()) {
5659     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5660       return VariadicConstructor;
5661     else if (Fn && Fn->getType()->isBlockPointerType())
5662       return VariadicBlock;
5663     else if (FDecl) {
5664       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5665         if (Method->isInstance())
5666           return VariadicMethod;
5667     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5668       return VariadicMethod;
5669     return VariadicFunction;
5670   }
5671   return VariadicDoesNotApply;
5672 }
5673 
5674 namespace {
5675 class FunctionCallCCC final : public FunctionCallFilterCCC {
5676 public:
5677   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5678                   unsigned NumArgs, MemberExpr *ME)
5679       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5680         FunctionName(FuncName) {}
5681 
5682   bool ValidateCandidate(const TypoCorrection &candidate) override {
5683     if (!candidate.getCorrectionSpecifier() ||
5684         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5685       return false;
5686     }
5687 
5688     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5689   }
5690 
5691   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5692     return std::make_unique<FunctionCallCCC>(*this);
5693   }
5694 
5695 private:
5696   const IdentifierInfo *const FunctionName;
5697 };
5698 }
5699 
5700 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5701                                                FunctionDecl *FDecl,
5702                                                ArrayRef<Expr *> Args) {
5703   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5704   DeclarationName FuncName = FDecl->getDeclName();
5705   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5706 
5707   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5708   if (TypoCorrection Corrected = S.CorrectTypo(
5709           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5710           S.getScopeForContext(S.CurContext), nullptr, CCC,
5711           Sema::CTK_ErrorRecovery)) {
5712     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5713       if (Corrected.isOverloaded()) {
5714         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5715         OverloadCandidateSet::iterator Best;
5716         for (NamedDecl *CD : Corrected) {
5717           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5718             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5719                                    OCS);
5720         }
5721         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5722         case OR_Success:
5723           ND = Best->FoundDecl;
5724           Corrected.setCorrectionDecl(ND);
5725           break;
5726         default:
5727           break;
5728         }
5729       }
5730       ND = ND->getUnderlyingDecl();
5731       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5732         return Corrected;
5733     }
5734   }
5735   return TypoCorrection();
5736 }
5737 
5738 /// ConvertArgumentsForCall - Converts the arguments specified in
5739 /// Args/NumArgs to the parameter types of the function FDecl with
5740 /// function prototype Proto. Call is the call expression itself, and
5741 /// Fn is the function expression. For a C++ member function, this
5742 /// routine does not attempt to convert the object argument. Returns
5743 /// true if the call is ill-formed.
5744 bool
5745 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5746                               FunctionDecl *FDecl,
5747                               const FunctionProtoType *Proto,
5748                               ArrayRef<Expr *> Args,
5749                               SourceLocation RParenLoc,
5750                               bool IsExecConfig) {
5751   // Bail out early if calling a builtin with custom typechecking.
5752   if (FDecl)
5753     if (unsigned ID = FDecl->getBuiltinID())
5754       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5755         return false;
5756 
5757   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5758   // assignment, to the types of the corresponding parameter, ...
5759   unsigned NumParams = Proto->getNumParams();
5760   bool Invalid = false;
5761   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5762   unsigned FnKind = Fn->getType()->isBlockPointerType()
5763                        ? 1 /* block */
5764                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5765                                        : 0 /* function */);
5766 
5767   // If too few arguments are available (and we don't have default
5768   // arguments for the remaining parameters), don't make the call.
5769   if (Args.size() < NumParams) {
5770     if (Args.size() < MinArgs) {
5771       TypoCorrection TC;
5772       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5773         unsigned diag_id =
5774             MinArgs == NumParams && !Proto->isVariadic()
5775                 ? diag::err_typecheck_call_too_few_args_suggest
5776                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5777         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5778                                         << static_cast<unsigned>(Args.size())
5779                                         << TC.getCorrectionRange());
5780       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5781         Diag(RParenLoc,
5782              MinArgs == NumParams && !Proto->isVariadic()
5783                  ? diag::err_typecheck_call_too_few_args_one
5784                  : diag::err_typecheck_call_too_few_args_at_least_one)
5785             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5786       else
5787         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5788                             ? diag::err_typecheck_call_too_few_args
5789                             : diag::err_typecheck_call_too_few_args_at_least)
5790             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5791             << Fn->getSourceRange();
5792 
5793       // Emit the location of the prototype.
5794       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5795         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5796 
5797       return true;
5798     }
5799     // We reserve space for the default arguments when we create
5800     // the call expression, before calling ConvertArgumentsForCall.
5801     assert((Call->getNumArgs() == NumParams) &&
5802            "We should have reserved space for the default arguments before!");
5803   }
5804 
5805   // If too many are passed and not variadic, error on the extras and drop
5806   // them.
5807   if (Args.size() > NumParams) {
5808     if (!Proto->isVariadic()) {
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_many_args_suggest
5814                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5815         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5816                                         << static_cast<unsigned>(Args.size())
5817                                         << TC.getCorrectionRange());
5818       } else if (NumParams == 1 && FDecl &&
5819                  FDecl->getParamDecl(0)->getDeclName())
5820         Diag(Args[NumParams]->getBeginLoc(),
5821              MinArgs == NumParams
5822                  ? diag::err_typecheck_call_too_many_args_one
5823                  : diag::err_typecheck_call_too_many_args_at_most_one)
5824             << FnKind << FDecl->getParamDecl(0)
5825             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5826             << SourceRange(Args[NumParams]->getBeginLoc(),
5827                            Args.back()->getEndLoc());
5828       else
5829         Diag(Args[NumParams]->getBeginLoc(),
5830              MinArgs == NumParams
5831                  ? diag::err_typecheck_call_too_many_args
5832                  : diag::err_typecheck_call_too_many_args_at_most)
5833             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5834             << Fn->getSourceRange()
5835             << SourceRange(Args[NumParams]->getBeginLoc(),
5836                            Args.back()->getEndLoc());
5837 
5838       // Emit the location of the prototype.
5839       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5840         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5841 
5842       // This deletes the extra arguments.
5843       Call->shrinkNumArgs(NumParams);
5844       return true;
5845     }
5846   }
5847   SmallVector<Expr *, 8> AllArgs;
5848   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5849 
5850   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5851                                    AllArgs, CallType);
5852   if (Invalid)
5853     return true;
5854   unsigned TotalNumArgs = AllArgs.size();
5855   for (unsigned i = 0; i < TotalNumArgs; ++i)
5856     Call->setArg(i, AllArgs[i]);
5857 
5858   return false;
5859 }
5860 
5861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5862                                   const FunctionProtoType *Proto,
5863                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5864                                   SmallVectorImpl<Expr *> &AllArgs,
5865                                   VariadicCallType CallType, bool AllowExplicit,
5866                                   bool IsListInitialization) {
5867   unsigned NumParams = Proto->getNumParams();
5868   bool Invalid = false;
5869   size_t ArgIx = 0;
5870   // Continue to check argument types (even if we have too few/many args).
5871   for (unsigned i = FirstParam; i < NumParams; i++) {
5872     QualType ProtoArgType = Proto->getParamType(i);
5873 
5874     Expr *Arg;
5875     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5876     if (ArgIx < Args.size()) {
5877       Arg = Args[ArgIx++];
5878 
5879       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5880                               diag::err_call_incomplete_argument, Arg))
5881         return true;
5882 
5883       // Strip the unbridged-cast placeholder expression off, if applicable.
5884       bool CFAudited = false;
5885       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5886           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5887           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5888         Arg = stripARCUnbridgedCast(Arg);
5889       else if (getLangOpts().ObjCAutoRefCount &&
5890                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5891                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5892         CFAudited = true;
5893 
5894       if (Proto->getExtParameterInfo(i).isNoEscape())
5895         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5896           BE->getBlockDecl()->setDoesNotEscape();
5897 
5898       InitializedEntity Entity =
5899           Param ? InitializedEntity::InitializeParameter(Context, Param,
5900                                                          ProtoArgType)
5901                 : InitializedEntity::InitializeParameter(
5902                       Context, ProtoArgType, Proto->isParamConsumed(i));
5903 
5904       // Remember that parameter belongs to a CF audited API.
5905       if (CFAudited)
5906         Entity.setParameterCFAudited();
5907 
5908       ExprResult ArgE = PerformCopyInitialization(
5909           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5910       if (ArgE.isInvalid())
5911         return true;
5912 
5913       Arg = ArgE.getAs<Expr>();
5914     } else {
5915       assert(Param && "can't use default arguments without a known callee");
5916 
5917       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5918       if (ArgExpr.isInvalid())
5919         return true;
5920 
5921       Arg = ArgExpr.getAs<Expr>();
5922     }
5923 
5924     // Check for array bounds violations for each argument to the call. This
5925     // check only triggers warnings when the argument isn't a more complex Expr
5926     // with its own checking, such as a BinaryOperator.
5927     CheckArrayAccess(Arg);
5928 
5929     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5930     CheckStaticArrayArgument(CallLoc, Param, Arg);
5931 
5932     AllArgs.push_back(Arg);
5933   }
5934 
5935   // If this is a variadic call, handle args passed through "...".
5936   if (CallType != VariadicDoesNotApply) {
5937     // Assume that extern "C" functions with variadic arguments that
5938     // return __unknown_anytype aren't *really* variadic.
5939     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5940         FDecl->isExternC()) {
5941       for (Expr *A : Args.slice(ArgIx)) {
5942         QualType paramType; // ignored
5943         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5944         Invalid |= arg.isInvalid();
5945         AllArgs.push_back(arg.get());
5946       }
5947 
5948     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5949     } else {
5950       for (Expr *A : Args.slice(ArgIx)) {
5951         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5952         Invalid |= Arg.isInvalid();
5953         AllArgs.push_back(Arg.get());
5954       }
5955     }
5956 
5957     // Check for array bounds violations.
5958     for (Expr *A : Args.slice(ArgIx))
5959       CheckArrayAccess(A);
5960   }
5961   return Invalid;
5962 }
5963 
5964 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5965   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5966   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5967     TL = DTL.getOriginalLoc();
5968   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5969     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5970       << ATL.getLocalSourceRange();
5971 }
5972 
5973 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5974 /// array parameter, check that it is non-null, and that if it is formed by
5975 /// array-to-pointer decay, the underlying array is sufficiently large.
5976 ///
5977 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5978 /// array type derivation, then for each call to the function, the value of the
5979 /// corresponding actual argument shall provide access to the first element of
5980 /// an array with at least as many elements as specified by the size expression.
5981 void
5982 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5983                                ParmVarDecl *Param,
5984                                const Expr *ArgExpr) {
5985   // Static array parameters are not supported in C++.
5986   if (!Param || getLangOpts().CPlusPlus)
5987     return;
5988 
5989   QualType OrigTy = Param->getOriginalType();
5990 
5991   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5992   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5993     return;
5994 
5995   if (ArgExpr->isNullPointerConstant(Context,
5996                                      Expr::NPC_NeverValueDependent)) {
5997     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5998     DiagnoseCalleeStaticArrayParam(*this, Param);
5999     return;
6000   }
6001 
6002   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6003   if (!CAT)
6004     return;
6005 
6006   const ConstantArrayType *ArgCAT =
6007     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6008   if (!ArgCAT)
6009     return;
6010 
6011   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6012                                              ArgCAT->getElementType())) {
6013     if (ArgCAT->getSize().ult(CAT->getSize())) {
6014       Diag(CallLoc, diag::warn_static_array_too_small)
6015           << ArgExpr->getSourceRange()
6016           << (unsigned)ArgCAT->getSize().getZExtValue()
6017           << (unsigned)CAT->getSize().getZExtValue() << 0;
6018       DiagnoseCalleeStaticArrayParam(*this, Param);
6019     }
6020     return;
6021   }
6022 
6023   Optional<CharUnits> ArgSize =
6024       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6025   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6026   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6027     Diag(CallLoc, diag::warn_static_array_too_small)
6028         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6029         << (unsigned)ParmSize->getQuantity() << 1;
6030     DiagnoseCalleeStaticArrayParam(*this, Param);
6031   }
6032 }
6033 
6034 /// Given a function expression of unknown-any type, try to rebuild it
6035 /// to have a function type.
6036 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6037 
6038 /// Is the given type a placeholder that we need to lower out
6039 /// immediately during argument processing?
6040 static bool isPlaceholderToRemoveAsArg(QualType type) {
6041   // Placeholders are never sugared.
6042   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6043   if (!placeholder) return false;
6044 
6045   switch (placeholder->getKind()) {
6046   // Ignore all the non-placeholder types.
6047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6048   case BuiltinType::Id:
6049 #include "clang/Basic/OpenCLImageTypes.def"
6050 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6051   case BuiltinType::Id:
6052 #include "clang/Basic/OpenCLExtensionTypes.def"
6053   // In practice we'll never use this, since all SVE types are sugared
6054   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6055 #define SVE_TYPE(Name, Id, SingletonId) \
6056   case BuiltinType::Id:
6057 #include "clang/Basic/AArch64SVEACLETypes.def"
6058 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6059   case BuiltinType::Id:
6060 #include "clang/Basic/PPCTypes.def"
6061 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6062 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6063 #include "clang/AST/BuiltinTypes.def"
6064     return false;
6065 
6066   // We cannot lower out overload sets; they might validly be resolved
6067   // by the call machinery.
6068   case BuiltinType::Overload:
6069     return false;
6070 
6071   // Unbridged casts in ARC can be handled in some call positions and
6072   // should be left in place.
6073   case BuiltinType::ARCUnbridgedCast:
6074     return false;
6075 
6076   // Pseudo-objects should be converted as soon as possible.
6077   case BuiltinType::PseudoObject:
6078     return true;
6079 
6080   // The debugger mode could theoretically but currently does not try
6081   // to resolve unknown-typed arguments based on known parameter types.
6082   case BuiltinType::UnknownAny:
6083     return true;
6084 
6085   // These are always invalid as call arguments and should be reported.
6086   case BuiltinType::BoundMember:
6087   case BuiltinType::BuiltinFn:
6088   case BuiltinType::IncompleteMatrixIdx:
6089   case BuiltinType::OMPArraySection:
6090   case BuiltinType::OMPArrayShaping:
6091   case BuiltinType::OMPIterator:
6092     return true;
6093 
6094   }
6095   llvm_unreachable("bad builtin type kind");
6096 }
6097 
6098 /// Check an argument list for placeholders that we won't try to
6099 /// handle later.
6100 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6101   // Apply this processing to all the arguments at once instead of
6102   // dying at the first failure.
6103   bool hasInvalid = false;
6104   for (size_t i = 0, e = args.size(); i != e; i++) {
6105     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6106       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6107       if (result.isInvalid()) hasInvalid = true;
6108       else args[i] = result.get();
6109     }
6110   }
6111   return hasInvalid;
6112 }
6113 
6114 /// If a builtin function has a pointer argument with no explicit address
6115 /// space, then it should be able to accept a pointer to any address
6116 /// space as input.  In order to do this, we need to replace the
6117 /// standard builtin declaration with one that uses the same address space
6118 /// as the call.
6119 ///
6120 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6121 ///                  it does not contain any pointer arguments without
6122 ///                  an address space qualifer.  Otherwise the rewritten
6123 ///                  FunctionDecl is returned.
6124 /// TODO: Handle pointer return types.
6125 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6126                                                 FunctionDecl *FDecl,
6127                                                 MultiExprArg ArgExprs) {
6128 
6129   QualType DeclType = FDecl->getType();
6130   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6131 
6132   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6133       ArgExprs.size() < FT->getNumParams())
6134     return nullptr;
6135 
6136   bool NeedsNewDecl = false;
6137   unsigned i = 0;
6138   SmallVector<QualType, 8> OverloadParams;
6139 
6140   for (QualType ParamType : FT->param_types()) {
6141 
6142     // Convert array arguments to pointer to simplify type lookup.
6143     ExprResult ArgRes =
6144         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6145     if (ArgRes.isInvalid())
6146       return nullptr;
6147     Expr *Arg = ArgRes.get();
6148     QualType ArgType = Arg->getType();
6149     if (!ParamType->isPointerType() ||
6150         ParamType.hasAddressSpace() ||
6151         !ArgType->isPointerType() ||
6152         !ArgType->getPointeeType().hasAddressSpace()) {
6153       OverloadParams.push_back(ParamType);
6154       continue;
6155     }
6156 
6157     QualType PointeeType = ParamType->getPointeeType();
6158     if (PointeeType.hasAddressSpace())
6159       continue;
6160 
6161     NeedsNewDecl = true;
6162     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6163 
6164     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6165     OverloadParams.push_back(Context.getPointerType(PointeeType));
6166   }
6167 
6168   if (!NeedsNewDecl)
6169     return nullptr;
6170 
6171   FunctionProtoType::ExtProtoInfo EPI;
6172   EPI.Variadic = FT->isVariadic();
6173   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6174                                                 OverloadParams, EPI);
6175   DeclContext *Parent = FDecl->getParent();
6176   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6177                                                     FDecl->getLocation(),
6178                                                     FDecl->getLocation(),
6179                                                     FDecl->getIdentifier(),
6180                                                     OverloadTy,
6181                                                     /*TInfo=*/nullptr,
6182                                                     SC_Extern, false,
6183                                                     /*hasPrototype=*/true);
6184   SmallVector<ParmVarDecl*, 16> Params;
6185   FT = cast<FunctionProtoType>(OverloadTy);
6186   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6187     QualType ParamType = FT->getParamType(i);
6188     ParmVarDecl *Parm =
6189         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6190                                 SourceLocation(), nullptr, ParamType,
6191                                 /*TInfo=*/nullptr, SC_None, nullptr);
6192     Parm->setScopeInfo(0, i);
6193     Params.push_back(Parm);
6194   }
6195   OverloadDecl->setParams(Params);
6196   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6197   return OverloadDecl;
6198 }
6199 
6200 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6201                                     FunctionDecl *Callee,
6202                                     MultiExprArg ArgExprs) {
6203   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6204   // similar attributes) really don't like it when functions are called with an
6205   // invalid number of args.
6206   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6207                          /*PartialOverloading=*/false) &&
6208       !Callee->isVariadic())
6209     return;
6210   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6211     return;
6212 
6213   if (const EnableIfAttr *Attr =
6214           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6215     S.Diag(Fn->getBeginLoc(),
6216            isa<CXXMethodDecl>(Callee)
6217                ? diag::err_ovl_no_viable_member_function_in_call
6218                : diag::err_ovl_no_viable_function_in_call)
6219         << Callee << Callee->getSourceRange();
6220     S.Diag(Callee->getLocation(),
6221            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6222         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6223     return;
6224   }
6225 }
6226 
6227 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6228     const UnresolvedMemberExpr *const UME, Sema &S) {
6229 
6230   const auto GetFunctionLevelDCIfCXXClass =
6231       [](Sema &S) -> const CXXRecordDecl * {
6232     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6233     if (!DC || !DC->getParent())
6234       return nullptr;
6235 
6236     // If the call to some member function was made from within a member
6237     // function body 'M' return return 'M's parent.
6238     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6239       return MD->getParent()->getCanonicalDecl();
6240     // else the call was made from within a default member initializer of a
6241     // class, so return the class.
6242     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6243       return RD->getCanonicalDecl();
6244     return nullptr;
6245   };
6246   // If our DeclContext is neither a member function nor a class (in the
6247   // case of a lambda in a default member initializer), we can't have an
6248   // enclosing 'this'.
6249 
6250   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6251   if (!CurParentClass)
6252     return false;
6253 
6254   // The naming class for implicit member functions call is the class in which
6255   // name lookup starts.
6256   const CXXRecordDecl *const NamingClass =
6257       UME->getNamingClass()->getCanonicalDecl();
6258   assert(NamingClass && "Must have naming class even for implicit access");
6259 
6260   // If the unresolved member functions were found in a 'naming class' that is
6261   // related (either the same or derived from) to the class that contains the
6262   // member function that itself contained the implicit member access.
6263 
6264   return CurParentClass == NamingClass ||
6265          CurParentClass->isDerivedFrom(NamingClass);
6266 }
6267 
6268 static void
6269 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6270     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6271 
6272   if (!UME)
6273     return;
6274 
6275   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6276   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6277   // already been captured, or if this is an implicit member function call (if
6278   // it isn't, an attempt to capture 'this' should already have been made).
6279   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6280       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6281     return;
6282 
6283   // Check if the naming class in which the unresolved members were found is
6284   // related (same as or is a base of) to the enclosing class.
6285 
6286   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6287     return;
6288 
6289 
6290   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6291   // If the enclosing function is not dependent, then this lambda is
6292   // capture ready, so if we can capture this, do so.
6293   if (!EnclosingFunctionCtx->isDependentContext()) {
6294     // If the current lambda and all enclosing lambdas can capture 'this' -
6295     // then go ahead and capture 'this' (since our unresolved overload set
6296     // contains at least one non-static member function).
6297     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6298       S.CheckCXXThisCapture(CallLoc);
6299   } else if (S.CurContext->isDependentContext()) {
6300     // ... since this is an implicit member reference, that might potentially
6301     // involve a 'this' capture, mark 'this' for potential capture in
6302     // enclosing lambdas.
6303     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6304       CurLSI->addPotentialThisCapture(CallLoc);
6305   }
6306 }
6307 
6308 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6309                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6310                                Expr *ExecConfig) {
6311   ExprResult Call =
6312       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6313                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6314   if (Call.isInvalid())
6315     return Call;
6316 
6317   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6318   // language modes.
6319   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6320     if (ULE->hasExplicitTemplateArgs() &&
6321         ULE->decls_begin() == ULE->decls_end()) {
6322       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6323                                  ? diag::warn_cxx17_compat_adl_only_template_id
6324                                  : diag::ext_adl_only_template_id)
6325           << ULE->getName();
6326     }
6327   }
6328 
6329   if (LangOpts.OpenMP)
6330     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6331                            ExecConfig);
6332 
6333   return Call;
6334 }
6335 
6336 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6337 /// This provides the location of the left/right parens and a list of comma
6338 /// locations.
6339 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6340                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6341                                Expr *ExecConfig, bool IsExecConfig,
6342                                bool AllowRecovery) {
6343   // Since this might be a postfix expression, get rid of ParenListExprs.
6344   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6345   if (Result.isInvalid()) return ExprError();
6346   Fn = Result.get();
6347 
6348   if (checkArgsForPlaceholders(*this, ArgExprs))
6349     return ExprError();
6350 
6351   if (getLangOpts().CPlusPlus) {
6352     // If this is a pseudo-destructor expression, build the call immediately.
6353     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6354       if (!ArgExprs.empty()) {
6355         // Pseudo-destructor calls should not have any arguments.
6356         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6357             << FixItHint::CreateRemoval(
6358                    SourceRange(ArgExprs.front()->getBeginLoc(),
6359                                ArgExprs.back()->getEndLoc()));
6360       }
6361 
6362       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6363                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6364     }
6365     if (Fn->getType() == Context.PseudoObjectTy) {
6366       ExprResult result = CheckPlaceholderExpr(Fn);
6367       if (result.isInvalid()) return ExprError();
6368       Fn = result.get();
6369     }
6370 
6371     // Determine whether this is a dependent call inside a C++ template,
6372     // in which case we won't do any semantic analysis now.
6373     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6374       if (ExecConfig) {
6375         return CUDAKernelCallExpr::Create(
6376             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6377             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6378       } else {
6379 
6380         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6381             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6382             Fn->getBeginLoc());
6383 
6384         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6385                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6386       }
6387     }
6388 
6389     // Determine whether this is a call to an object (C++ [over.call.object]).
6390     if (Fn->getType()->isRecordType())
6391       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6392                                           RParenLoc);
6393 
6394     if (Fn->getType() == Context.UnknownAnyTy) {
6395       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6396       if (result.isInvalid()) return ExprError();
6397       Fn = result.get();
6398     }
6399 
6400     if (Fn->getType() == Context.BoundMemberTy) {
6401       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6402                                        RParenLoc, AllowRecovery);
6403     }
6404   }
6405 
6406   // Check for overloaded calls.  This can happen even in C due to extensions.
6407   if (Fn->getType() == Context.OverloadTy) {
6408     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6409 
6410     // We aren't supposed to apply this logic if there's an '&' involved.
6411     if (!find.HasFormOfMemberPointer) {
6412       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6413         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6414                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6415       OverloadExpr *ovl = find.Expression;
6416       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6417         return BuildOverloadedCallExpr(
6418             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6419             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6420       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6421                                        RParenLoc, AllowRecovery);
6422     }
6423   }
6424 
6425   // If we're directly calling a function, get the appropriate declaration.
6426   if (Fn->getType() == Context.UnknownAnyTy) {
6427     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6428     if (result.isInvalid()) return ExprError();
6429     Fn = result.get();
6430   }
6431 
6432   Expr *NakedFn = Fn->IgnoreParens();
6433 
6434   bool CallingNDeclIndirectly = false;
6435   NamedDecl *NDecl = nullptr;
6436   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6437     if (UnOp->getOpcode() == UO_AddrOf) {
6438       CallingNDeclIndirectly = true;
6439       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6440     }
6441   }
6442 
6443   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6444     NDecl = DRE->getDecl();
6445 
6446     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6447     if (FDecl && FDecl->getBuiltinID()) {
6448       // Rewrite the function decl for this builtin by replacing parameters
6449       // with no explicit address space with the address space of the arguments
6450       // in ArgExprs.
6451       if ((FDecl =
6452                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6453         NDecl = FDecl;
6454         Fn = DeclRefExpr::Create(
6455             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6456             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6457             nullptr, DRE->isNonOdrUse());
6458       }
6459     }
6460   } else if (isa<MemberExpr>(NakedFn))
6461     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6462 
6463   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6464     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6465                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6466       return ExprError();
6467 
6468     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6469       return ExprError();
6470 
6471     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6472   }
6473 
6474   if (Context.isDependenceAllowed() &&
6475       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6476     assert(!getLangOpts().CPlusPlus);
6477     assert((Fn->containsErrors() ||
6478             llvm::any_of(ArgExprs,
6479                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6480            "should only occur in error-recovery path.");
6481     QualType ReturnType =
6482         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6483             ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType()
6484             : Context.DependentTy;
6485     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6486                             Expr::getValueKindForType(ReturnType), RParenLoc,
6487                             CurFPFeatureOverrides());
6488   }
6489   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6490                                ExecConfig, IsExecConfig);
6491 }
6492 
6493 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6494 ///
6495 /// __builtin_astype( value, dst type )
6496 ///
6497 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6498                                  SourceLocation BuiltinLoc,
6499                                  SourceLocation RParenLoc) {
6500   ExprValueKind VK = VK_RValue;
6501   ExprObjectKind OK = OK_Ordinary;
6502   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6503   QualType SrcTy = E->getType();
6504   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6505     return ExprError(Diag(BuiltinLoc,
6506                           diag::err_invalid_astype_of_different_size)
6507                      << DstTy
6508                      << SrcTy
6509                      << E->getSourceRange());
6510   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6511 }
6512 
6513 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6514 /// provided arguments.
6515 ///
6516 /// __builtin_convertvector( value, dst type )
6517 ///
6518 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6519                                         SourceLocation BuiltinLoc,
6520                                         SourceLocation RParenLoc) {
6521   TypeSourceInfo *TInfo;
6522   GetTypeFromParser(ParsedDestTy, &TInfo);
6523   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6524 }
6525 
6526 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6527 /// i.e. an expression not of \p OverloadTy.  The expression should
6528 /// unary-convert to an expression of function-pointer or
6529 /// block-pointer type.
6530 ///
6531 /// \param NDecl the declaration being called, if available
6532 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6533                                        SourceLocation LParenLoc,
6534                                        ArrayRef<Expr *> Args,
6535                                        SourceLocation RParenLoc, Expr *Config,
6536                                        bool IsExecConfig, ADLCallKind UsesADL) {
6537   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6538   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6539 
6540   // Functions with 'interrupt' attribute cannot be called directly.
6541   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6542     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6543     return ExprError();
6544   }
6545 
6546   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6547   // so there's some risk when calling out to non-interrupt handler functions
6548   // that the callee might not preserve them. This is easy to diagnose here,
6549   // but can be very challenging to debug.
6550   if (auto *Caller = getCurFunctionDecl())
6551     if (Caller->hasAttr<ARMInterruptAttr>()) {
6552       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6553       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6554         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6555     }
6556 
6557   // Promote the function operand.
6558   // We special-case function promotion here because we only allow promoting
6559   // builtin functions to function pointers in the callee of a call.
6560   ExprResult Result;
6561   QualType ResultTy;
6562   if (BuiltinID &&
6563       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6564     // Extract the return type from the (builtin) function pointer type.
6565     // FIXME Several builtins still have setType in
6566     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6567     // Builtins.def to ensure they are correct before removing setType calls.
6568     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6569     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6570     ResultTy = FDecl->getCallResultType();
6571   } else {
6572     Result = CallExprUnaryConversions(Fn);
6573     ResultTy = Context.BoolTy;
6574   }
6575   if (Result.isInvalid())
6576     return ExprError();
6577   Fn = Result.get();
6578 
6579   // Check for a valid function type, but only if it is not a builtin which
6580   // requires custom type checking. These will be handled by
6581   // CheckBuiltinFunctionCall below just after creation of the call expression.
6582   const FunctionType *FuncT = nullptr;
6583   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6584   retry:
6585     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6586       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6587       // have type pointer to function".
6588       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6589       if (!FuncT)
6590         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6591                          << Fn->getType() << Fn->getSourceRange());
6592     } else if (const BlockPointerType *BPT =
6593                    Fn->getType()->getAs<BlockPointerType>()) {
6594       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6595     } else {
6596       // Handle calls to expressions of unknown-any type.
6597       if (Fn->getType() == Context.UnknownAnyTy) {
6598         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6599         if (rewrite.isInvalid())
6600           return ExprError();
6601         Fn = rewrite.get();
6602         goto retry;
6603       }
6604 
6605       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6606                        << Fn->getType() << Fn->getSourceRange());
6607     }
6608   }
6609 
6610   // Get the number of parameters in the function prototype, if any.
6611   // We will allocate space for max(Args.size(), NumParams) arguments
6612   // in the call expression.
6613   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6614   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6615 
6616   CallExpr *TheCall;
6617   if (Config) {
6618     assert(UsesADL == ADLCallKind::NotADL &&
6619            "CUDAKernelCallExpr should not use ADL");
6620     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6621                                          Args, ResultTy, VK_RValue, RParenLoc,
6622                                          CurFPFeatureOverrides(), NumParams);
6623   } else {
6624     TheCall =
6625         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6626                          CurFPFeatureOverrides(), NumParams, UsesADL);
6627   }
6628 
6629   if (!Context.isDependenceAllowed()) {
6630     // Forget about the nulled arguments since typo correction
6631     // do not handle them well.
6632     TheCall->shrinkNumArgs(Args.size());
6633     // C cannot always handle TypoExpr nodes in builtin calls and direct
6634     // function calls as their argument checking don't necessarily handle
6635     // dependent types properly, so make sure any TypoExprs have been
6636     // dealt with.
6637     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6638     if (!Result.isUsable()) return ExprError();
6639     CallExpr *TheOldCall = TheCall;
6640     TheCall = dyn_cast<CallExpr>(Result.get());
6641     bool CorrectedTypos = TheCall != TheOldCall;
6642     if (!TheCall) return Result;
6643     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6644 
6645     // A new call expression node was created if some typos were corrected.
6646     // However it may not have been constructed with enough storage. In this
6647     // case, rebuild the node with enough storage. The waste of space is
6648     // immaterial since this only happens when some typos were corrected.
6649     if (CorrectedTypos && Args.size() < NumParams) {
6650       if (Config)
6651         TheCall = CUDAKernelCallExpr::Create(
6652             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6653             RParenLoc, CurFPFeatureOverrides(), NumParams);
6654       else
6655         TheCall =
6656             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6657                              CurFPFeatureOverrides(), NumParams, UsesADL);
6658     }
6659     // We can now handle the nulled arguments for the default arguments.
6660     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6661   }
6662 
6663   // Bail out early if calling a builtin with custom type checking.
6664   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6665     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6666 
6667   if (getLangOpts().CUDA) {
6668     if (Config) {
6669       // CUDA: Kernel calls must be to global functions
6670       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6671         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6672             << FDecl << Fn->getSourceRange());
6673 
6674       // CUDA: Kernel function must have 'void' return type
6675       if (!FuncT->getReturnType()->isVoidType() &&
6676           !FuncT->getReturnType()->getAs<AutoType>() &&
6677           !FuncT->getReturnType()->isInstantiationDependentType())
6678         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6679             << Fn->getType() << Fn->getSourceRange());
6680     } else {
6681       // CUDA: Calls to global functions must be configured
6682       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6683         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6684             << FDecl << Fn->getSourceRange());
6685     }
6686   }
6687 
6688   // Check for a valid return type
6689   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6690                           FDecl))
6691     return ExprError();
6692 
6693   // We know the result type of the call, set it.
6694   TheCall->setType(FuncT->getCallResultType(Context));
6695   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6696 
6697   if (Proto) {
6698     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6699                                 IsExecConfig))
6700       return ExprError();
6701   } else {
6702     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6703 
6704     if (FDecl) {
6705       // Check if we have too few/too many template arguments, based
6706       // on our knowledge of the function definition.
6707       const FunctionDecl *Def = nullptr;
6708       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6709         Proto = Def->getType()->getAs<FunctionProtoType>();
6710        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6711           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6712           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6713       }
6714 
6715       // If the function we're calling isn't a function prototype, but we have
6716       // a function prototype from a prior declaratiom, use that prototype.
6717       if (!FDecl->hasPrototype())
6718         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6719     }
6720 
6721     // Promote the arguments (C99 6.5.2.2p6).
6722     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6723       Expr *Arg = Args[i];
6724 
6725       if (Proto && i < Proto->getNumParams()) {
6726         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6727             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6728         ExprResult ArgE =
6729             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6730         if (ArgE.isInvalid())
6731           return true;
6732 
6733         Arg = ArgE.getAs<Expr>();
6734 
6735       } else {
6736         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6737 
6738         if (ArgE.isInvalid())
6739           return true;
6740 
6741         Arg = ArgE.getAs<Expr>();
6742       }
6743 
6744       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6745                               diag::err_call_incomplete_argument, Arg))
6746         return ExprError();
6747 
6748       TheCall->setArg(i, Arg);
6749     }
6750   }
6751 
6752   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6753     if (!Method->isStatic())
6754       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6755         << Fn->getSourceRange());
6756 
6757   // Check for sentinels
6758   if (NDecl)
6759     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6760 
6761   // Warn for unions passing across security boundary (CMSE).
6762   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6763     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6764       if (const auto *RT =
6765               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6766         if (RT->getDecl()->isOrContainsUnion())
6767           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6768               << 0 << i;
6769       }
6770     }
6771   }
6772 
6773   // Do special checking on direct calls to functions.
6774   if (FDecl) {
6775     if (CheckFunctionCall(FDecl, TheCall, Proto))
6776       return ExprError();
6777 
6778     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6779 
6780     if (BuiltinID)
6781       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6782   } else if (NDecl) {
6783     if (CheckPointerCall(NDecl, TheCall, Proto))
6784       return ExprError();
6785   } else {
6786     if (CheckOtherCall(TheCall, Proto))
6787       return ExprError();
6788   }
6789 
6790   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6791 }
6792 
6793 ExprResult
6794 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6795                            SourceLocation RParenLoc, Expr *InitExpr) {
6796   assert(Ty && "ActOnCompoundLiteral(): missing type");
6797   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6798 
6799   TypeSourceInfo *TInfo;
6800   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6801   if (!TInfo)
6802     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6803 
6804   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6805 }
6806 
6807 ExprResult
6808 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6809                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6810   QualType literalType = TInfo->getType();
6811 
6812   if (literalType->isArrayType()) {
6813     if (RequireCompleteSizedType(
6814             LParenLoc, Context.getBaseElementType(literalType),
6815             diag::err_array_incomplete_or_sizeless_type,
6816             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6817       return ExprError();
6818     if (literalType->isVariableArrayType())
6819       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6820         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6821   } else if (!literalType->isDependentType() &&
6822              RequireCompleteType(LParenLoc, literalType,
6823                diag::err_typecheck_decl_incomplete_type,
6824                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6825     return ExprError();
6826 
6827   InitializedEntity Entity
6828     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6829   InitializationKind Kind
6830     = InitializationKind::CreateCStyleCast(LParenLoc,
6831                                            SourceRange(LParenLoc, RParenLoc),
6832                                            /*InitList=*/true);
6833   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6834   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6835                                       &literalType);
6836   if (Result.isInvalid())
6837     return ExprError();
6838   LiteralExpr = Result.get();
6839 
6840   bool isFileScope = !CurContext->isFunctionOrMethod();
6841 
6842   // In C, compound literals are l-values for some reason.
6843   // For GCC compatibility, in C++, file-scope array compound literals with
6844   // constant initializers are also l-values, and compound literals are
6845   // otherwise prvalues.
6846   //
6847   // (GCC also treats C++ list-initialized file-scope array prvalues with
6848   // constant initializers as l-values, but that's non-conforming, so we don't
6849   // follow it there.)
6850   //
6851   // FIXME: It would be better to handle the lvalue cases as materializing and
6852   // lifetime-extending a temporary object, but our materialized temporaries
6853   // representation only supports lifetime extension from a variable, not "out
6854   // of thin air".
6855   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6856   // is bound to the result of applying array-to-pointer decay to the compound
6857   // literal.
6858   // FIXME: GCC supports compound literals of reference type, which should
6859   // obviously have a value kind derived from the kind of reference involved.
6860   ExprValueKind VK =
6861       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6862           ? VK_RValue
6863           : VK_LValue;
6864 
6865   if (isFileScope)
6866     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6867       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6868         Expr *Init = ILE->getInit(i);
6869         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6870       }
6871 
6872   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6873                                               VK, LiteralExpr, isFileScope);
6874   if (isFileScope) {
6875     if (!LiteralExpr->isTypeDependent() &&
6876         !LiteralExpr->isValueDependent() &&
6877         !literalType->isDependentType()) // C99 6.5.2.5p3
6878       if (CheckForConstantInitializer(LiteralExpr, literalType))
6879         return ExprError();
6880   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6881              literalType.getAddressSpace() != LangAS::Default) {
6882     // Embedded-C extensions to C99 6.5.2.5:
6883     //   "If the compound literal occurs inside the body of a function, the
6884     //   type name shall not be qualified by an address-space qualifier."
6885     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6886       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6887     return ExprError();
6888   }
6889 
6890   if (!isFileScope && !getLangOpts().CPlusPlus) {
6891     // Compound literals that have automatic storage duration are destroyed at
6892     // the end of the scope in C; in C++, they're just temporaries.
6893 
6894     // Emit diagnostics if it is or contains a C union type that is non-trivial
6895     // to destruct.
6896     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6897       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6898                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6899 
6900     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6901     if (literalType.isDestructedType()) {
6902       Cleanup.setExprNeedsCleanups(true);
6903       ExprCleanupObjects.push_back(E);
6904       getCurFunction()->setHasBranchProtectedScope();
6905     }
6906   }
6907 
6908   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6909       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6910     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6911                                        E->getInitializer()->getExprLoc());
6912 
6913   return MaybeBindToTemporary(E);
6914 }
6915 
6916 ExprResult
6917 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6918                     SourceLocation RBraceLoc) {
6919   // Only produce each kind of designated initialization diagnostic once.
6920   SourceLocation FirstDesignator;
6921   bool DiagnosedArrayDesignator = false;
6922   bool DiagnosedNestedDesignator = false;
6923   bool DiagnosedMixedDesignator = false;
6924 
6925   // Check that any designated initializers are syntactically valid in the
6926   // current language mode.
6927   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6928     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6929       if (FirstDesignator.isInvalid())
6930         FirstDesignator = DIE->getBeginLoc();
6931 
6932       if (!getLangOpts().CPlusPlus)
6933         break;
6934 
6935       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6936         DiagnosedNestedDesignator = true;
6937         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6938           << DIE->getDesignatorsSourceRange();
6939       }
6940 
6941       for (auto &Desig : DIE->designators()) {
6942         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6943           DiagnosedArrayDesignator = true;
6944           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6945             << Desig.getSourceRange();
6946         }
6947       }
6948 
6949       if (!DiagnosedMixedDesignator &&
6950           !isa<DesignatedInitExpr>(InitArgList[0])) {
6951         DiagnosedMixedDesignator = true;
6952         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6953           << DIE->getSourceRange();
6954         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6955           << InitArgList[0]->getSourceRange();
6956       }
6957     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6958                isa<DesignatedInitExpr>(InitArgList[0])) {
6959       DiagnosedMixedDesignator = true;
6960       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6961       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6962         << DIE->getSourceRange();
6963       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6964         << InitArgList[I]->getSourceRange();
6965     }
6966   }
6967 
6968   if (FirstDesignator.isValid()) {
6969     // Only diagnose designated initiaization as a C++20 extension if we didn't
6970     // already diagnose use of (non-C++20) C99 designator syntax.
6971     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6972         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6973       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6974                                 ? diag::warn_cxx17_compat_designated_init
6975                                 : diag::ext_cxx_designated_init);
6976     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6977       Diag(FirstDesignator, diag::ext_designated_init);
6978     }
6979   }
6980 
6981   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6982 }
6983 
6984 ExprResult
6985 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6986                     SourceLocation RBraceLoc) {
6987   // Semantic analysis for initializers is done by ActOnDeclarator() and
6988   // CheckInitializer() - it requires knowledge of the object being initialized.
6989 
6990   // Immediately handle non-overload placeholders.  Overloads can be
6991   // resolved contextually, but everything else here can't.
6992   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6993     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6994       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6995 
6996       // Ignore failures; dropping the entire initializer list because
6997       // of one failure would be terrible for indexing/etc.
6998       if (result.isInvalid()) continue;
6999 
7000       InitArgList[I] = result.get();
7001     }
7002   }
7003 
7004   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7005                                                RBraceLoc);
7006   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7007   return E;
7008 }
7009 
7010 /// Do an explicit extend of the given block pointer if we're in ARC.
7011 void Sema::maybeExtendBlockObject(ExprResult &E) {
7012   assert(E.get()->getType()->isBlockPointerType());
7013   assert(E.get()->isRValue());
7014 
7015   // Only do this in an r-value context.
7016   if (!getLangOpts().ObjCAutoRefCount) return;
7017 
7018   E = ImplicitCastExpr::Create(
7019       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7020       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7021   Cleanup.setExprNeedsCleanups(true);
7022 }
7023 
7024 /// Prepare a conversion of the given expression to an ObjC object
7025 /// pointer type.
7026 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7027   QualType type = E.get()->getType();
7028   if (type->isObjCObjectPointerType()) {
7029     return CK_BitCast;
7030   } else if (type->isBlockPointerType()) {
7031     maybeExtendBlockObject(E);
7032     return CK_BlockPointerToObjCPointerCast;
7033   } else {
7034     assert(type->isPointerType());
7035     return CK_CPointerToObjCPointerCast;
7036   }
7037 }
7038 
7039 /// Prepares for a scalar cast, performing all the necessary stages
7040 /// except the final cast and returning the kind required.
7041 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7042   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7043   // Also, callers should have filtered out the invalid cases with
7044   // pointers.  Everything else should be possible.
7045 
7046   QualType SrcTy = Src.get()->getType();
7047   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7048     return CK_NoOp;
7049 
7050   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7051   case Type::STK_MemberPointer:
7052     llvm_unreachable("member pointer type in C");
7053 
7054   case Type::STK_CPointer:
7055   case Type::STK_BlockPointer:
7056   case Type::STK_ObjCObjectPointer:
7057     switch (DestTy->getScalarTypeKind()) {
7058     case Type::STK_CPointer: {
7059       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7060       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7061       if (SrcAS != DestAS)
7062         return CK_AddressSpaceConversion;
7063       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7064         return CK_NoOp;
7065       return CK_BitCast;
7066     }
7067     case Type::STK_BlockPointer:
7068       return (SrcKind == Type::STK_BlockPointer
7069                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7070     case Type::STK_ObjCObjectPointer:
7071       if (SrcKind == Type::STK_ObjCObjectPointer)
7072         return CK_BitCast;
7073       if (SrcKind == Type::STK_CPointer)
7074         return CK_CPointerToObjCPointerCast;
7075       maybeExtendBlockObject(Src);
7076       return CK_BlockPointerToObjCPointerCast;
7077     case Type::STK_Bool:
7078       return CK_PointerToBoolean;
7079     case Type::STK_Integral:
7080       return CK_PointerToIntegral;
7081     case Type::STK_Floating:
7082     case Type::STK_FloatingComplex:
7083     case Type::STK_IntegralComplex:
7084     case Type::STK_MemberPointer:
7085     case Type::STK_FixedPoint:
7086       llvm_unreachable("illegal cast from pointer");
7087     }
7088     llvm_unreachable("Should have returned before this");
7089 
7090   case Type::STK_FixedPoint:
7091     switch (DestTy->getScalarTypeKind()) {
7092     case Type::STK_FixedPoint:
7093       return CK_FixedPointCast;
7094     case Type::STK_Bool:
7095       return CK_FixedPointToBoolean;
7096     case Type::STK_Integral:
7097       return CK_FixedPointToIntegral;
7098     case Type::STK_Floating:
7099       return CK_FixedPointToFloating;
7100     case Type::STK_IntegralComplex:
7101     case Type::STK_FloatingComplex:
7102       Diag(Src.get()->getExprLoc(),
7103            diag::err_unimplemented_conversion_with_fixed_point_type)
7104           << DestTy;
7105       return CK_IntegralCast;
7106     case Type::STK_CPointer:
7107     case Type::STK_ObjCObjectPointer:
7108     case Type::STK_BlockPointer:
7109     case Type::STK_MemberPointer:
7110       llvm_unreachable("illegal cast to pointer type");
7111     }
7112     llvm_unreachable("Should have returned before this");
7113 
7114   case Type::STK_Bool: // casting from bool is like casting from an integer
7115   case Type::STK_Integral:
7116     switch (DestTy->getScalarTypeKind()) {
7117     case Type::STK_CPointer:
7118     case Type::STK_ObjCObjectPointer:
7119     case Type::STK_BlockPointer:
7120       if (Src.get()->isNullPointerConstant(Context,
7121                                            Expr::NPC_ValueDependentIsNull))
7122         return CK_NullToPointer;
7123       return CK_IntegralToPointer;
7124     case Type::STK_Bool:
7125       return CK_IntegralToBoolean;
7126     case Type::STK_Integral:
7127       return CK_IntegralCast;
7128     case Type::STK_Floating:
7129       return CK_IntegralToFloating;
7130     case Type::STK_IntegralComplex:
7131       Src = ImpCastExprToType(Src.get(),
7132                       DestTy->castAs<ComplexType>()->getElementType(),
7133                       CK_IntegralCast);
7134       return CK_IntegralRealToComplex;
7135     case Type::STK_FloatingComplex:
7136       Src = ImpCastExprToType(Src.get(),
7137                       DestTy->castAs<ComplexType>()->getElementType(),
7138                       CK_IntegralToFloating);
7139       return CK_FloatingRealToComplex;
7140     case Type::STK_MemberPointer:
7141       llvm_unreachable("member pointer type in C");
7142     case Type::STK_FixedPoint:
7143       return CK_IntegralToFixedPoint;
7144     }
7145     llvm_unreachable("Should have returned before this");
7146 
7147   case Type::STK_Floating:
7148     switch (DestTy->getScalarTypeKind()) {
7149     case Type::STK_Floating:
7150       return CK_FloatingCast;
7151     case Type::STK_Bool:
7152       return CK_FloatingToBoolean;
7153     case Type::STK_Integral:
7154       return CK_FloatingToIntegral;
7155     case Type::STK_FloatingComplex:
7156       Src = ImpCastExprToType(Src.get(),
7157                               DestTy->castAs<ComplexType>()->getElementType(),
7158                               CK_FloatingCast);
7159       return CK_FloatingRealToComplex;
7160     case Type::STK_IntegralComplex:
7161       Src = ImpCastExprToType(Src.get(),
7162                               DestTy->castAs<ComplexType>()->getElementType(),
7163                               CK_FloatingToIntegral);
7164       return CK_IntegralRealToComplex;
7165     case Type::STK_CPointer:
7166     case Type::STK_ObjCObjectPointer:
7167     case Type::STK_BlockPointer:
7168       llvm_unreachable("valid float->pointer cast?");
7169     case Type::STK_MemberPointer:
7170       llvm_unreachable("member pointer type in C");
7171     case Type::STK_FixedPoint:
7172       return CK_FloatingToFixedPoint;
7173     }
7174     llvm_unreachable("Should have returned before this");
7175 
7176   case Type::STK_FloatingComplex:
7177     switch (DestTy->getScalarTypeKind()) {
7178     case Type::STK_FloatingComplex:
7179       return CK_FloatingComplexCast;
7180     case Type::STK_IntegralComplex:
7181       return CK_FloatingComplexToIntegralComplex;
7182     case Type::STK_Floating: {
7183       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7184       if (Context.hasSameType(ET, DestTy))
7185         return CK_FloatingComplexToReal;
7186       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7187       return CK_FloatingCast;
7188     }
7189     case Type::STK_Bool:
7190       return CK_FloatingComplexToBoolean;
7191     case Type::STK_Integral:
7192       Src = ImpCastExprToType(Src.get(),
7193                               SrcTy->castAs<ComplexType>()->getElementType(),
7194                               CK_FloatingComplexToReal);
7195       return CK_FloatingToIntegral;
7196     case Type::STK_CPointer:
7197     case Type::STK_ObjCObjectPointer:
7198     case Type::STK_BlockPointer:
7199       llvm_unreachable("valid complex float->pointer cast?");
7200     case Type::STK_MemberPointer:
7201       llvm_unreachable("member pointer type in C");
7202     case Type::STK_FixedPoint:
7203       Diag(Src.get()->getExprLoc(),
7204            diag::err_unimplemented_conversion_with_fixed_point_type)
7205           << SrcTy;
7206       return CK_IntegralCast;
7207     }
7208     llvm_unreachable("Should have returned before this");
7209 
7210   case Type::STK_IntegralComplex:
7211     switch (DestTy->getScalarTypeKind()) {
7212     case Type::STK_FloatingComplex:
7213       return CK_IntegralComplexToFloatingComplex;
7214     case Type::STK_IntegralComplex:
7215       return CK_IntegralComplexCast;
7216     case Type::STK_Integral: {
7217       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7218       if (Context.hasSameType(ET, DestTy))
7219         return CK_IntegralComplexToReal;
7220       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7221       return CK_IntegralCast;
7222     }
7223     case Type::STK_Bool:
7224       return CK_IntegralComplexToBoolean;
7225     case Type::STK_Floating:
7226       Src = ImpCastExprToType(Src.get(),
7227                               SrcTy->castAs<ComplexType>()->getElementType(),
7228                               CK_IntegralComplexToReal);
7229       return CK_IntegralToFloating;
7230     case Type::STK_CPointer:
7231     case Type::STK_ObjCObjectPointer:
7232     case Type::STK_BlockPointer:
7233       llvm_unreachable("valid complex int->pointer cast?");
7234     case Type::STK_MemberPointer:
7235       llvm_unreachable("member pointer type in C");
7236     case Type::STK_FixedPoint:
7237       Diag(Src.get()->getExprLoc(),
7238            diag::err_unimplemented_conversion_with_fixed_point_type)
7239           << SrcTy;
7240       return CK_IntegralCast;
7241     }
7242     llvm_unreachable("Should have returned before this");
7243   }
7244 
7245   llvm_unreachable("Unhandled scalar cast");
7246 }
7247 
7248 static bool breakDownVectorType(QualType type, uint64_t &len,
7249                                 QualType &eltType) {
7250   // Vectors are simple.
7251   if (const VectorType *vecType = type->getAs<VectorType>()) {
7252     len = vecType->getNumElements();
7253     eltType = vecType->getElementType();
7254     assert(eltType->isScalarType());
7255     return true;
7256   }
7257 
7258   // We allow lax conversion to and from non-vector types, but only if
7259   // they're real types (i.e. non-complex, non-pointer scalar types).
7260   if (!type->isRealType()) return false;
7261 
7262   len = 1;
7263   eltType = type;
7264   return true;
7265 }
7266 
7267 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7268 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7269 /// allowed?
7270 ///
7271 /// This will also return false if the two given types do not make sense from
7272 /// the perspective of SVE bitcasts.
7273 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7274   assert(srcTy->isVectorType() || destTy->isVectorType());
7275 
7276   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7277     if (!FirstType->isSizelessBuiltinType())
7278       return false;
7279 
7280     const auto *VecTy = SecondType->getAs<VectorType>();
7281     return VecTy &&
7282            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7283   };
7284 
7285   return ValidScalableConversion(srcTy, destTy) ||
7286          ValidScalableConversion(destTy, srcTy);
7287 }
7288 
7289 /// Are the two types lax-compatible vector types?  That is, given
7290 /// that one of them is a vector, do they have equal storage sizes,
7291 /// where the storage size is the number of elements times the element
7292 /// size?
7293 ///
7294 /// This will also return false if either of the types is neither a
7295 /// vector nor a real type.
7296 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7297   assert(destTy->isVectorType() || srcTy->isVectorType());
7298 
7299   // Disallow lax conversions between scalars and ExtVectors (these
7300   // conversions are allowed for other vector types because common headers
7301   // depend on them).  Most scalar OP ExtVector cases are handled by the
7302   // splat path anyway, which does what we want (convert, not bitcast).
7303   // What this rules out for ExtVectors is crazy things like char4*float.
7304   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7305   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7306 
7307   uint64_t srcLen, destLen;
7308   QualType srcEltTy, destEltTy;
7309   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7310   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7311 
7312   // ASTContext::getTypeSize will return the size rounded up to a
7313   // power of 2, so instead of using that, we need to use the raw
7314   // element size multiplied by the element count.
7315   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7316   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7317 
7318   return (srcLen * srcEltSize == destLen * destEltSize);
7319 }
7320 
7321 /// Is this a legal conversion between two types, one of which is
7322 /// known to be a vector type?
7323 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7324   assert(destTy->isVectorType() || srcTy->isVectorType());
7325 
7326   switch (Context.getLangOpts().getLaxVectorConversions()) {
7327   case LangOptions::LaxVectorConversionKind::None:
7328     return false;
7329 
7330   case LangOptions::LaxVectorConversionKind::Integer:
7331     if (!srcTy->isIntegralOrEnumerationType()) {
7332       auto *Vec = srcTy->getAs<VectorType>();
7333       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7334         return false;
7335     }
7336     if (!destTy->isIntegralOrEnumerationType()) {
7337       auto *Vec = destTy->getAs<VectorType>();
7338       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7339         return false;
7340     }
7341     // OK, integer (vector) -> integer (vector) bitcast.
7342     break;
7343 
7344     case LangOptions::LaxVectorConversionKind::All:
7345     break;
7346   }
7347 
7348   return areLaxCompatibleVectorTypes(srcTy, destTy);
7349 }
7350 
7351 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7352                            CastKind &Kind) {
7353   assert(VectorTy->isVectorType() && "Not a vector type!");
7354 
7355   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7356     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7357       return Diag(R.getBegin(),
7358                   Ty->isVectorType() ?
7359                   diag::err_invalid_conversion_between_vectors :
7360                   diag::err_invalid_conversion_between_vector_and_integer)
7361         << VectorTy << Ty << R;
7362   } else
7363     return Diag(R.getBegin(),
7364                 diag::err_invalid_conversion_between_vector_and_scalar)
7365       << VectorTy << Ty << R;
7366 
7367   Kind = CK_BitCast;
7368   return false;
7369 }
7370 
7371 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7372   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7373 
7374   if (DestElemTy == SplattedExpr->getType())
7375     return SplattedExpr;
7376 
7377   assert(DestElemTy->isFloatingType() ||
7378          DestElemTy->isIntegralOrEnumerationType());
7379 
7380   CastKind CK;
7381   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7382     // OpenCL requires that we convert `true` boolean expressions to -1, but
7383     // only when splatting vectors.
7384     if (DestElemTy->isFloatingType()) {
7385       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7386       // in two steps: boolean to signed integral, then to floating.
7387       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7388                                                  CK_BooleanToSignedIntegral);
7389       SplattedExpr = CastExprRes.get();
7390       CK = CK_IntegralToFloating;
7391     } else {
7392       CK = CK_BooleanToSignedIntegral;
7393     }
7394   } else {
7395     ExprResult CastExprRes = SplattedExpr;
7396     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7397     if (CastExprRes.isInvalid())
7398       return ExprError();
7399     SplattedExpr = CastExprRes.get();
7400   }
7401   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7402 }
7403 
7404 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7405                                     Expr *CastExpr, CastKind &Kind) {
7406   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7407 
7408   QualType SrcTy = CastExpr->getType();
7409 
7410   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7411   // an ExtVectorType.
7412   // In OpenCL, casts between vectors of different types are not allowed.
7413   // (See OpenCL 6.2).
7414   if (SrcTy->isVectorType()) {
7415     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7416         (getLangOpts().OpenCL &&
7417          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7418       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7419         << DestTy << SrcTy << R;
7420       return ExprError();
7421     }
7422     Kind = CK_BitCast;
7423     return CastExpr;
7424   }
7425 
7426   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7427   // conversion will take place first from scalar to elt type, and then
7428   // splat from elt type to vector.
7429   if (SrcTy->isPointerType())
7430     return Diag(R.getBegin(),
7431                 diag::err_invalid_conversion_between_vector_and_scalar)
7432       << DestTy << SrcTy << R;
7433 
7434   Kind = CK_VectorSplat;
7435   return prepareVectorSplat(DestTy, CastExpr);
7436 }
7437 
7438 ExprResult
7439 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7440                     Declarator &D, ParsedType &Ty,
7441                     SourceLocation RParenLoc, Expr *CastExpr) {
7442   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7443          "ActOnCastExpr(): missing type or expr");
7444 
7445   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7446   if (D.isInvalidType())
7447     return ExprError();
7448 
7449   if (getLangOpts().CPlusPlus) {
7450     // Check that there are no default arguments (C++ only).
7451     CheckExtraCXXDefaultArguments(D);
7452   } else {
7453     // Make sure any TypoExprs have been dealt with.
7454     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7455     if (!Res.isUsable())
7456       return ExprError();
7457     CastExpr = Res.get();
7458   }
7459 
7460   checkUnusedDeclAttributes(D);
7461 
7462   QualType castType = castTInfo->getType();
7463   Ty = CreateParsedType(castType, castTInfo);
7464 
7465   bool isVectorLiteral = false;
7466 
7467   // Check for an altivec or OpenCL literal,
7468   // i.e. all the elements are integer constants.
7469   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7470   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7471   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7472        && castType->isVectorType() && (PE || PLE)) {
7473     if (PLE && PLE->getNumExprs() == 0) {
7474       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7475       return ExprError();
7476     }
7477     if (PE || PLE->getNumExprs() == 1) {
7478       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7479       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7480         isVectorLiteral = true;
7481     }
7482     else
7483       isVectorLiteral = true;
7484   }
7485 
7486   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7487   // then handle it as such.
7488   if (isVectorLiteral)
7489     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7490 
7491   // If the Expr being casted is a ParenListExpr, handle it specially.
7492   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7493   // sequence of BinOp comma operators.
7494   if (isa<ParenListExpr>(CastExpr)) {
7495     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7496     if (Result.isInvalid()) return ExprError();
7497     CastExpr = Result.get();
7498   }
7499 
7500   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7501       !getSourceManager().isInSystemMacro(LParenLoc))
7502     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7503 
7504   CheckTollFreeBridgeCast(castType, CastExpr);
7505 
7506   CheckObjCBridgeRelatedCast(castType, CastExpr);
7507 
7508   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7509 
7510   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7511 }
7512 
7513 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7514                                     SourceLocation RParenLoc, Expr *E,
7515                                     TypeSourceInfo *TInfo) {
7516   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7517          "Expected paren or paren list expression");
7518 
7519   Expr **exprs;
7520   unsigned numExprs;
7521   Expr *subExpr;
7522   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7523   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7524     LiteralLParenLoc = PE->getLParenLoc();
7525     LiteralRParenLoc = PE->getRParenLoc();
7526     exprs = PE->getExprs();
7527     numExprs = PE->getNumExprs();
7528   } else { // isa<ParenExpr> by assertion at function entrance
7529     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7530     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7531     subExpr = cast<ParenExpr>(E)->getSubExpr();
7532     exprs = &subExpr;
7533     numExprs = 1;
7534   }
7535 
7536   QualType Ty = TInfo->getType();
7537   assert(Ty->isVectorType() && "Expected vector type");
7538 
7539   SmallVector<Expr *, 8> initExprs;
7540   const VectorType *VTy = Ty->castAs<VectorType>();
7541   unsigned numElems = VTy->getNumElements();
7542 
7543   // '(...)' form of vector initialization in AltiVec: the number of
7544   // initializers must be one or must match the size of the vector.
7545   // If a single value is specified in the initializer then it will be
7546   // replicated to all the components of the vector
7547   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7548     // The number of initializers must be one or must match the size of the
7549     // vector. If a single value is specified in the initializer then it will
7550     // be replicated to all the components of the vector
7551     if (numExprs == 1) {
7552       QualType ElemTy = VTy->getElementType();
7553       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7554       if (Literal.isInvalid())
7555         return ExprError();
7556       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7557                                   PrepareScalarCast(Literal, ElemTy));
7558       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7559     }
7560     else if (numExprs < numElems) {
7561       Diag(E->getExprLoc(),
7562            diag::err_incorrect_number_of_vector_initializers);
7563       return ExprError();
7564     }
7565     else
7566       initExprs.append(exprs, exprs + numExprs);
7567   }
7568   else {
7569     // For OpenCL, when the number of initializers is a single value,
7570     // it will be replicated to all components of the vector.
7571     if (getLangOpts().OpenCL &&
7572         VTy->getVectorKind() == VectorType::GenericVector &&
7573         numExprs == 1) {
7574         QualType ElemTy = VTy->getElementType();
7575         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7576         if (Literal.isInvalid())
7577           return ExprError();
7578         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7579                                     PrepareScalarCast(Literal, ElemTy));
7580         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7581     }
7582 
7583     initExprs.append(exprs, exprs + numExprs);
7584   }
7585   // FIXME: This means that pretty-printing the final AST will produce curly
7586   // braces instead of the original commas.
7587   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7588                                                    initExprs, LiteralRParenLoc);
7589   initE->setType(Ty);
7590   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7591 }
7592 
7593 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7594 /// the ParenListExpr into a sequence of comma binary operators.
7595 ExprResult
7596 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7597   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7598   if (!E)
7599     return OrigExpr;
7600 
7601   ExprResult Result(E->getExpr(0));
7602 
7603   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7604     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7605                         E->getExpr(i));
7606 
7607   if (Result.isInvalid()) return ExprError();
7608 
7609   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7610 }
7611 
7612 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7613                                     SourceLocation R,
7614                                     MultiExprArg Val) {
7615   return ParenListExpr::Create(Context, L, Val, R);
7616 }
7617 
7618 /// Emit a specialized diagnostic when one expression is a null pointer
7619 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7620 /// emitted.
7621 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7622                                       SourceLocation QuestionLoc) {
7623   Expr *NullExpr = LHSExpr;
7624   Expr *NonPointerExpr = RHSExpr;
7625   Expr::NullPointerConstantKind NullKind =
7626       NullExpr->isNullPointerConstant(Context,
7627                                       Expr::NPC_ValueDependentIsNotNull);
7628 
7629   if (NullKind == Expr::NPCK_NotNull) {
7630     NullExpr = RHSExpr;
7631     NonPointerExpr = LHSExpr;
7632     NullKind =
7633         NullExpr->isNullPointerConstant(Context,
7634                                         Expr::NPC_ValueDependentIsNotNull);
7635   }
7636 
7637   if (NullKind == Expr::NPCK_NotNull)
7638     return false;
7639 
7640   if (NullKind == Expr::NPCK_ZeroExpression)
7641     return false;
7642 
7643   if (NullKind == Expr::NPCK_ZeroLiteral) {
7644     // In this case, check to make sure that we got here from a "NULL"
7645     // string in the source code.
7646     NullExpr = NullExpr->IgnoreParenImpCasts();
7647     SourceLocation loc = NullExpr->getExprLoc();
7648     if (!findMacroSpelling(loc, "NULL"))
7649       return false;
7650   }
7651 
7652   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7653   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7654       << NonPointerExpr->getType() << DiagType
7655       << NonPointerExpr->getSourceRange();
7656   return true;
7657 }
7658 
7659 /// Return false if the condition expression is valid, true otherwise.
7660 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7661   QualType CondTy = Cond->getType();
7662 
7663   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7664   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7665     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7666       << CondTy << Cond->getSourceRange();
7667     return true;
7668   }
7669 
7670   // C99 6.5.15p2
7671   if (CondTy->isScalarType()) return false;
7672 
7673   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7674     << CondTy << Cond->getSourceRange();
7675   return true;
7676 }
7677 
7678 /// Handle when one or both operands are void type.
7679 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7680                                          ExprResult &RHS) {
7681     Expr *LHSExpr = LHS.get();
7682     Expr *RHSExpr = RHS.get();
7683 
7684     if (!LHSExpr->getType()->isVoidType())
7685       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7686           << RHSExpr->getSourceRange();
7687     if (!RHSExpr->getType()->isVoidType())
7688       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7689           << LHSExpr->getSourceRange();
7690     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7691     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7692     return S.Context.VoidTy;
7693 }
7694 
7695 /// Return false if the NullExpr can be promoted to PointerTy,
7696 /// true otherwise.
7697 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7698                                         QualType PointerTy) {
7699   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7700       !NullExpr.get()->isNullPointerConstant(S.Context,
7701                                             Expr::NPC_ValueDependentIsNull))
7702     return true;
7703 
7704   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7705   return false;
7706 }
7707 
7708 /// Checks compatibility between two pointers and return the resulting
7709 /// type.
7710 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7711                                                      ExprResult &RHS,
7712                                                      SourceLocation Loc) {
7713   QualType LHSTy = LHS.get()->getType();
7714   QualType RHSTy = RHS.get()->getType();
7715 
7716   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7717     // Two identical pointers types are always compatible.
7718     return LHSTy;
7719   }
7720 
7721   QualType lhptee, rhptee;
7722 
7723   // Get the pointee types.
7724   bool IsBlockPointer = false;
7725   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7726     lhptee = LHSBTy->getPointeeType();
7727     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7728     IsBlockPointer = true;
7729   } else {
7730     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7731     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7732   }
7733 
7734   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7735   // differently qualified versions of compatible types, the result type is
7736   // a pointer to an appropriately qualified version of the composite
7737   // type.
7738 
7739   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7740   // clause doesn't make sense for our extensions. E.g. address space 2 should
7741   // be incompatible with address space 3: they may live on different devices or
7742   // anything.
7743   Qualifiers lhQual = lhptee.getQualifiers();
7744   Qualifiers rhQual = rhptee.getQualifiers();
7745 
7746   LangAS ResultAddrSpace = LangAS::Default;
7747   LangAS LAddrSpace = lhQual.getAddressSpace();
7748   LangAS RAddrSpace = rhQual.getAddressSpace();
7749 
7750   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7751   // spaces is disallowed.
7752   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7753     ResultAddrSpace = LAddrSpace;
7754   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7755     ResultAddrSpace = RAddrSpace;
7756   else {
7757     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7758         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7759         << RHS.get()->getSourceRange();
7760     return QualType();
7761   }
7762 
7763   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7764   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7765   lhQual.removeCVRQualifiers();
7766   rhQual.removeCVRQualifiers();
7767 
7768   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7769   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7770   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7771   // qual types are compatible iff
7772   //  * corresponded types are compatible
7773   //  * CVR qualifiers are equal
7774   //  * address spaces are equal
7775   // Thus for conditional operator we merge CVR and address space unqualified
7776   // pointees and if there is a composite type we return a pointer to it with
7777   // merged qualifiers.
7778   LHSCastKind =
7779       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7780   RHSCastKind =
7781       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7782   lhQual.removeAddressSpace();
7783   rhQual.removeAddressSpace();
7784 
7785   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7786   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7787 
7788   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7789 
7790   if (CompositeTy.isNull()) {
7791     // In this situation, we assume void* type. No especially good
7792     // reason, but this is what gcc does, and we do have to pick
7793     // to get a consistent AST.
7794     QualType incompatTy;
7795     incompatTy = S.Context.getPointerType(
7796         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7797     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7798     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7799 
7800     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7801     // for casts between types with incompatible address space qualifiers.
7802     // For the following code the compiler produces casts between global and
7803     // local address spaces of the corresponded innermost pointees:
7804     // local int *global *a;
7805     // global int *global *b;
7806     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7807     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7808         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7809         << RHS.get()->getSourceRange();
7810 
7811     return incompatTy;
7812   }
7813 
7814   // The pointer types are compatible.
7815   // In case of OpenCL ResultTy should have the address space qualifier
7816   // which is a superset of address spaces of both the 2nd and the 3rd
7817   // operands of the conditional operator.
7818   QualType ResultTy = [&, ResultAddrSpace]() {
7819     if (S.getLangOpts().OpenCL) {
7820       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7821       CompositeQuals.setAddressSpace(ResultAddrSpace);
7822       return S.Context
7823           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7824           .withCVRQualifiers(MergedCVRQual);
7825     }
7826     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7827   }();
7828   if (IsBlockPointer)
7829     ResultTy = S.Context.getBlockPointerType(ResultTy);
7830   else
7831     ResultTy = S.Context.getPointerType(ResultTy);
7832 
7833   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7834   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7835   return ResultTy;
7836 }
7837 
7838 /// Return the resulting type when the operands are both block pointers.
7839 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7840                                                           ExprResult &LHS,
7841                                                           ExprResult &RHS,
7842                                                           SourceLocation Loc) {
7843   QualType LHSTy = LHS.get()->getType();
7844   QualType RHSTy = RHS.get()->getType();
7845 
7846   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7847     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7848       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7849       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7850       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7851       return destType;
7852     }
7853     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7854       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7855       << RHS.get()->getSourceRange();
7856     return QualType();
7857   }
7858 
7859   // We have 2 block pointer types.
7860   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7861 }
7862 
7863 /// Return the resulting type when the operands are both pointers.
7864 static QualType
7865 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7866                                             ExprResult &RHS,
7867                                             SourceLocation Loc) {
7868   // get the pointer types
7869   QualType LHSTy = LHS.get()->getType();
7870   QualType RHSTy = RHS.get()->getType();
7871 
7872   // get the "pointed to" types
7873   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7874   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7875 
7876   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7877   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7878     // Figure out necessary qualifiers (C99 6.5.15p6)
7879     QualType destPointee
7880       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7881     QualType destType = S.Context.getPointerType(destPointee);
7882     // Add qualifiers if necessary.
7883     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7884     // Promote to void*.
7885     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7886     return destType;
7887   }
7888   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7889     QualType destPointee
7890       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7891     QualType destType = S.Context.getPointerType(destPointee);
7892     // Add qualifiers if necessary.
7893     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7894     // Promote to void*.
7895     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7896     return destType;
7897   }
7898 
7899   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7900 }
7901 
7902 /// Return false if the first expression is not an integer and the second
7903 /// expression is not a pointer, true otherwise.
7904 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7905                                         Expr* PointerExpr, SourceLocation Loc,
7906                                         bool IsIntFirstExpr) {
7907   if (!PointerExpr->getType()->isPointerType() ||
7908       !Int.get()->getType()->isIntegerType())
7909     return false;
7910 
7911   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7912   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7913 
7914   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7915     << Expr1->getType() << Expr2->getType()
7916     << Expr1->getSourceRange() << Expr2->getSourceRange();
7917   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7918                             CK_IntegralToPointer);
7919   return true;
7920 }
7921 
7922 /// Simple conversion between integer and floating point types.
7923 ///
7924 /// Used when handling the OpenCL conditional operator where the
7925 /// condition is a vector while the other operands are scalar.
7926 ///
7927 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7928 /// types are either integer or floating type. Between the two
7929 /// operands, the type with the higher rank is defined as the "result
7930 /// type". The other operand needs to be promoted to the same type. No
7931 /// other type promotion is allowed. We cannot use
7932 /// UsualArithmeticConversions() for this purpose, since it always
7933 /// promotes promotable types.
7934 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7935                                             ExprResult &RHS,
7936                                             SourceLocation QuestionLoc) {
7937   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7938   if (LHS.isInvalid())
7939     return QualType();
7940   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7941   if (RHS.isInvalid())
7942     return QualType();
7943 
7944   // For conversion purposes, we ignore any qualifiers.
7945   // For example, "const float" and "float" are equivalent.
7946   QualType LHSType =
7947     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7948   QualType RHSType =
7949     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7950 
7951   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7952     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7953       << LHSType << LHS.get()->getSourceRange();
7954     return QualType();
7955   }
7956 
7957   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7958     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7959       << RHSType << RHS.get()->getSourceRange();
7960     return QualType();
7961   }
7962 
7963   // If both types are identical, no conversion is needed.
7964   if (LHSType == RHSType)
7965     return LHSType;
7966 
7967   // Now handle "real" floating types (i.e. float, double, long double).
7968   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7969     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7970                                  /*IsCompAssign = */ false);
7971 
7972   // Finally, we have two differing integer types.
7973   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7974   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7975 }
7976 
7977 /// Convert scalar operands to a vector that matches the
7978 ///        condition in length.
7979 ///
7980 /// Used when handling the OpenCL conditional operator where the
7981 /// condition is a vector while the other operands are scalar.
7982 ///
7983 /// We first compute the "result type" for the scalar operands
7984 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7985 /// into a vector of that type where the length matches the condition
7986 /// vector type. s6.11.6 requires that the element types of the result
7987 /// and the condition must have the same number of bits.
7988 static QualType
7989 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7990                               QualType CondTy, SourceLocation QuestionLoc) {
7991   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7992   if (ResTy.isNull()) return QualType();
7993 
7994   const VectorType *CV = CondTy->getAs<VectorType>();
7995   assert(CV);
7996 
7997   // Determine the vector result type
7998   unsigned NumElements = CV->getNumElements();
7999   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8000 
8001   // Ensure that all types have the same number of bits
8002   if (S.Context.getTypeSize(CV->getElementType())
8003       != S.Context.getTypeSize(ResTy)) {
8004     // Since VectorTy is created internally, it does not pretty print
8005     // with an OpenCL name. Instead, we just print a description.
8006     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8007     SmallString<64> Str;
8008     llvm::raw_svector_ostream OS(Str);
8009     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8010     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8011       << CondTy << OS.str();
8012     return QualType();
8013   }
8014 
8015   // Convert operands to the vector result type
8016   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8017   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8018 
8019   return VectorTy;
8020 }
8021 
8022 /// Return false if this is a valid OpenCL condition vector
8023 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8024                                        SourceLocation QuestionLoc) {
8025   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8026   // integral type.
8027   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8028   assert(CondTy);
8029   QualType EleTy = CondTy->getElementType();
8030   if (EleTy->isIntegerType()) return false;
8031 
8032   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8033     << Cond->getType() << Cond->getSourceRange();
8034   return true;
8035 }
8036 
8037 /// Return false if the vector condition type and the vector
8038 ///        result type are compatible.
8039 ///
8040 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8041 /// number of elements, and their element types have the same number
8042 /// of bits.
8043 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8044                               SourceLocation QuestionLoc) {
8045   const VectorType *CV = CondTy->getAs<VectorType>();
8046   const VectorType *RV = VecResTy->getAs<VectorType>();
8047   assert(CV && RV);
8048 
8049   if (CV->getNumElements() != RV->getNumElements()) {
8050     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8051       << CondTy << VecResTy;
8052     return true;
8053   }
8054 
8055   QualType CVE = CV->getElementType();
8056   QualType RVE = RV->getElementType();
8057 
8058   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8059     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8060       << CondTy << VecResTy;
8061     return true;
8062   }
8063 
8064   return false;
8065 }
8066 
8067 /// Return the resulting type for the conditional operator in
8068 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8069 ///        s6.3.i) when the condition is a vector type.
8070 static QualType
8071 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8072                              ExprResult &LHS, ExprResult &RHS,
8073                              SourceLocation QuestionLoc) {
8074   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8075   if (Cond.isInvalid())
8076     return QualType();
8077   QualType CondTy = Cond.get()->getType();
8078 
8079   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8080     return QualType();
8081 
8082   // If either operand is a vector then find the vector type of the
8083   // result as specified in OpenCL v1.1 s6.3.i.
8084   if (LHS.get()->getType()->isVectorType() ||
8085       RHS.get()->getType()->isVectorType()) {
8086     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8087                                               /*isCompAssign*/false,
8088                                               /*AllowBothBool*/true,
8089                                               /*AllowBoolConversions*/false);
8090     if (VecResTy.isNull()) return QualType();
8091     // The result type must match the condition type as specified in
8092     // OpenCL v1.1 s6.11.6.
8093     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8094       return QualType();
8095     return VecResTy;
8096   }
8097 
8098   // Both operands are scalar.
8099   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8100 }
8101 
8102 /// Return true if the Expr is block type
8103 static bool checkBlockType(Sema &S, const Expr *E) {
8104   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8105     QualType Ty = CE->getCallee()->getType();
8106     if (Ty->isBlockPointerType()) {
8107       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8108       return true;
8109     }
8110   }
8111   return false;
8112 }
8113 
8114 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8115 /// In that case, LHS = cond.
8116 /// C99 6.5.15
8117 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8118                                         ExprResult &RHS, ExprValueKind &VK,
8119                                         ExprObjectKind &OK,
8120                                         SourceLocation QuestionLoc) {
8121 
8122   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8123   if (!LHSResult.isUsable()) return QualType();
8124   LHS = LHSResult;
8125 
8126   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8127   if (!RHSResult.isUsable()) return QualType();
8128   RHS = RHSResult;
8129 
8130   // C++ is sufficiently different to merit its own checker.
8131   if (getLangOpts().CPlusPlus)
8132     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8133 
8134   VK = VK_RValue;
8135   OK = OK_Ordinary;
8136 
8137   if (Context.isDependenceAllowed() &&
8138       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8139        RHS.get()->isTypeDependent())) {
8140     assert(!getLangOpts().CPlusPlus);
8141     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8142             RHS.get()->containsErrors()) &&
8143            "should only occur in error-recovery path.");
8144     return Context.DependentTy;
8145   }
8146 
8147   // The OpenCL operator with a vector condition is sufficiently
8148   // different to merit its own checker.
8149   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8150       Cond.get()->getType()->isExtVectorType())
8151     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8152 
8153   // First, check the condition.
8154   Cond = UsualUnaryConversions(Cond.get());
8155   if (Cond.isInvalid())
8156     return QualType();
8157   if (checkCondition(*this, Cond.get(), QuestionLoc))
8158     return QualType();
8159 
8160   // Now check the two expressions.
8161   if (LHS.get()->getType()->isVectorType() ||
8162       RHS.get()->getType()->isVectorType())
8163     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8164                                /*AllowBothBool*/true,
8165                                /*AllowBoolConversions*/false);
8166 
8167   QualType ResTy =
8168       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8169   if (LHS.isInvalid() || RHS.isInvalid())
8170     return QualType();
8171 
8172   QualType LHSTy = LHS.get()->getType();
8173   QualType RHSTy = RHS.get()->getType();
8174 
8175   // Diagnose attempts to convert between __float128 and long double where
8176   // such conversions currently can't be handled.
8177   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8178     Diag(QuestionLoc,
8179          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8180       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8181     return QualType();
8182   }
8183 
8184   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8185   // selection operator (?:).
8186   if (getLangOpts().OpenCL &&
8187       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8188     return QualType();
8189   }
8190 
8191   // If both operands have arithmetic type, do the usual arithmetic conversions
8192   // to find a common type: C99 6.5.15p3,5.
8193   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8194     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8195     // different sizes, or between ExtInts and other types.
8196     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8197       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8198           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8199           << RHS.get()->getSourceRange();
8200       return QualType();
8201     }
8202 
8203     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8204     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8205 
8206     return ResTy;
8207   }
8208 
8209   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8210   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8211     return LHSTy;
8212   }
8213 
8214   // If both operands are the same structure or union type, the result is that
8215   // type.
8216   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8217     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8218       if (LHSRT->getDecl() == RHSRT->getDecl())
8219         // "If both the operands have structure or union type, the result has
8220         // that type."  This implies that CV qualifiers are dropped.
8221         return LHSTy.getUnqualifiedType();
8222     // FIXME: Type of conditional expression must be complete in C mode.
8223   }
8224 
8225   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8226   // The following || allows only one side to be void (a GCC-ism).
8227   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8228     return checkConditionalVoidType(*this, LHS, RHS);
8229   }
8230 
8231   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8232   // the type of the other operand."
8233   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8234   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8235 
8236   // All objective-c pointer type analysis is done here.
8237   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8238                                                         QuestionLoc);
8239   if (LHS.isInvalid() || RHS.isInvalid())
8240     return QualType();
8241   if (!compositeType.isNull())
8242     return compositeType;
8243 
8244 
8245   // Handle block pointer types.
8246   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8247     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8248                                                      QuestionLoc);
8249 
8250   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8251   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8252     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8253                                                        QuestionLoc);
8254 
8255   // GCC compatibility: soften pointer/integer mismatch.  Note that
8256   // null pointers have been filtered out by this point.
8257   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8258       /*IsIntFirstExpr=*/true))
8259     return RHSTy;
8260   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8261       /*IsIntFirstExpr=*/false))
8262     return LHSTy;
8263 
8264   // Allow ?: operations in which both operands have the same
8265   // built-in sizeless type.
8266   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8267     return LHSTy;
8268 
8269   // Emit a better diagnostic if one of the expressions is a null pointer
8270   // constant and the other is not a pointer type. In this case, the user most
8271   // likely forgot to take the address of the other expression.
8272   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8273     return QualType();
8274 
8275   // Otherwise, the operands are not compatible.
8276   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8277     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8278     << RHS.get()->getSourceRange();
8279   return QualType();
8280 }
8281 
8282 /// FindCompositeObjCPointerType - Helper method to find composite type of
8283 /// two objective-c pointer types of the two input expressions.
8284 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8285                                             SourceLocation QuestionLoc) {
8286   QualType LHSTy = LHS.get()->getType();
8287   QualType RHSTy = RHS.get()->getType();
8288 
8289   // Handle things like Class and struct objc_class*.  Here we case the result
8290   // to the pseudo-builtin, because that will be implicitly cast back to the
8291   // redefinition type if an attempt is made to access its fields.
8292   if (LHSTy->isObjCClassType() &&
8293       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8294     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8295     return LHSTy;
8296   }
8297   if (RHSTy->isObjCClassType() &&
8298       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8299     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8300     return RHSTy;
8301   }
8302   // And the same for struct objc_object* / id
8303   if (LHSTy->isObjCIdType() &&
8304       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8305     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8306     return LHSTy;
8307   }
8308   if (RHSTy->isObjCIdType() &&
8309       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8310     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8311     return RHSTy;
8312   }
8313   // And the same for struct objc_selector* / SEL
8314   if (Context.isObjCSelType(LHSTy) &&
8315       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8316     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8317     return LHSTy;
8318   }
8319   if (Context.isObjCSelType(RHSTy) &&
8320       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8321     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8322     return RHSTy;
8323   }
8324   // Check constraints for Objective-C object pointers types.
8325   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8326 
8327     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8328       // Two identical object pointer types are always compatible.
8329       return LHSTy;
8330     }
8331     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8332     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8333     QualType compositeType = LHSTy;
8334 
8335     // If both operands are interfaces and either operand can be
8336     // assigned to the other, use that type as the composite
8337     // type. This allows
8338     //   xxx ? (A*) a : (B*) b
8339     // where B is a subclass of A.
8340     //
8341     // Additionally, as for assignment, if either type is 'id'
8342     // allow silent coercion. Finally, if the types are
8343     // incompatible then make sure to use 'id' as the composite
8344     // type so the result is acceptable for sending messages to.
8345 
8346     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8347     // It could return the composite type.
8348     if (!(compositeType =
8349           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8350       // Nothing more to do.
8351     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8352       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8353     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8354       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8355     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8356                 RHSOPT->isObjCQualifiedIdType()) &&
8357                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8358                                                          true)) {
8359       // Need to handle "id<xx>" explicitly.
8360       // GCC allows qualified id and any Objective-C type to devolve to
8361       // id. Currently localizing to here until clear this should be
8362       // part of ObjCQualifiedIdTypesAreCompatible.
8363       compositeType = Context.getObjCIdType();
8364     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8365       compositeType = Context.getObjCIdType();
8366     } else {
8367       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8368       << LHSTy << RHSTy
8369       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8370       QualType incompatTy = Context.getObjCIdType();
8371       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8372       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8373       return incompatTy;
8374     }
8375     // The object pointer types are compatible.
8376     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8377     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8378     return compositeType;
8379   }
8380   // Check Objective-C object pointer types and 'void *'
8381   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8382     if (getLangOpts().ObjCAutoRefCount) {
8383       // ARC forbids the implicit conversion of object pointers to 'void *',
8384       // so these types are not compatible.
8385       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8386           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8387       LHS = RHS = true;
8388       return QualType();
8389     }
8390     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8391     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8392     QualType destPointee
8393     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8394     QualType destType = Context.getPointerType(destPointee);
8395     // Add qualifiers if necessary.
8396     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8397     // Promote to void*.
8398     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8399     return destType;
8400   }
8401   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8402     if (getLangOpts().ObjCAutoRefCount) {
8403       // ARC forbids the implicit conversion of object pointers to 'void *',
8404       // so these types are not compatible.
8405       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8406           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8407       LHS = RHS = true;
8408       return QualType();
8409     }
8410     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8411     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8412     QualType destPointee
8413     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8414     QualType destType = Context.getPointerType(destPointee);
8415     // Add qualifiers if necessary.
8416     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8417     // Promote to void*.
8418     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8419     return destType;
8420   }
8421   return QualType();
8422 }
8423 
8424 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8425 /// ParenRange in parentheses.
8426 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8427                                const PartialDiagnostic &Note,
8428                                SourceRange ParenRange) {
8429   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8430   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8431       EndLoc.isValid()) {
8432     Self.Diag(Loc, Note)
8433       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8434       << FixItHint::CreateInsertion(EndLoc, ")");
8435   } else {
8436     // We can't display the parentheses, so just show the bare note.
8437     Self.Diag(Loc, Note) << ParenRange;
8438   }
8439 }
8440 
8441 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8442   return BinaryOperator::isAdditiveOp(Opc) ||
8443          BinaryOperator::isMultiplicativeOp(Opc) ||
8444          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8445   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8446   // not any of the logical operators.  Bitwise-xor is commonly used as a
8447   // logical-xor because there is no logical-xor operator.  The logical
8448   // operators, including uses of xor, have a high false positive rate for
8449   // precedence warnings.
8450 }
8451 
8452 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8453 /// expression, either using a built-in or overloaded operator,
8454 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8455 /// expression.
8456 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8457                                    Expr **RHSExprs) {
8458   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8459   E = E->IgnoreImpCasts();
8460   E = E->IgnoreConversionOperatorSingleStep();
8461   E = E->IgnoreImpCasts();
8462   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8463     E = MTE->getSubExpr();
8464     E = E->IgnoreImpCasts();
8465   }
8466 
8467   // Built-in binary operator.
8468   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8469     if (IsArithmeticOp(OP->getOpcode())) {
8470       *Opcode = OP->getOpcode();
8471       *RHSExprs = OP->getRHS();
8472       return true;
8473     }
8474   }
8475 
8476   // Overloaded operator.
8477   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8478     if (Call->getNumArgs() != 2)
8479       return false;
8480 
8481     // Make sure this is really a binary operator that is safe to pass into
8482     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8483     OverloadedOperatorKind OO = Call->getOperator();
8484     if (OO < OO_Plus || OO > OO_Arrow ||
8485         OO == OO_PlusPlus || OO == OO_MinusMinus)
8486       return false;
8487 
8488     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8489     if (IsArithmeticOp(OpKind)) {
8490       *Opcode = OpKind;
8491       *RHSExprs = Call->getArg(1);
8492       return true;
8493     }
8494   }
8495 
8496   return false;
8497 }
8498 
8499 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8500 /// or is a logical expression such as (x==y) which has int type, but is
8501 /// commonly interpreted as boolean.
8502 static bool ExprLooksBoolean(Expr *E) {
8503   E = E->IgnoreParenImpCasts();
8504 
8505   if (E->getType()->isBooleanType())
8506     return true;
8507   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8508     return OP->isComparisonOp() || OP->isLogicalOp();
8509   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8510     return OP->getOpcode() == UO_LNot;
8511   if (E->getType()->isPointerType())
8512     return true;
8513   // FIXME: What about overloaded operator calls returning "unspecified boolean
8514   // type"s (commonly pointer-to-members)?
8515 
8516   return false;
8517 }
8518 
8519 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8520 /// and binary operator are mixed in a way that suggests the programmer assumed
8521 /// the conditional operator has higher precedence, for example:
8522 /// "int x = a + someBinaryCondition ? 1 : 2".
8523 static void DiagnoseConditionalPrecedence(Sema &Self,
8524                                           SourceLocation OpLoc,
8525                                           Expr *Condition,
8526                                           Expr *LHSExpr,
8527                                           Expr *RHSExpr) {
8528   BinaryOperatorKind CondOpcode;
8529   Expr *CondRHS;
8530 
8531   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8532     return;
8533   if (!ExprLooksBoolean(CondRHS))
8534     return;
8535 
8536   // The condition is an arithmetic binary expression, with a right-
8537   // hand side that looks boolean, so warn.
8538 
8539   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8540                         ? diag::warn_precedence_bitwise_conditional
8541                         : diag::warn_precedence_conditional;
8542 
8543   Self.Diag(OpLoc, DiagID)
8544       << Condition->getSourceRange()
8545       << BinaryOperator::getOpcodeStr(CondOpcode);
8546 
8547   SuggestParentheses(
8548       Self, OpLoc,
8549       Self.PDiag(diag::note_precedence_silence)
8550           << BinaryOperator::getOpcodeStr(CondOpcode),
8551       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8552 
8553   SuggestParentheses(Self, OpLoc,
8554                      Self.PDiag(diag::note_precedence_conditional_first),
8555                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8556 }
8557 
8558 /// Compute the nullability of a conditional expression.
8559 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8560                                               QualType LHSTy, QualType RHSTy,
8561                                               ASTContext &Ctx) {
8562   if (!ResTy->isAnyPointerType())
8563     return ResTy;
8564 
8565   auto GetNullability = [&Ctx](QualType Ty) {
8566     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8567     if (Kind) {
8568       // For our purposes, treat _Nullable_result as _Nullable.
8569       if (*Kind == NullabilityKind::NullableResult)
8570         return NullabilityKind::Nullable;
8571       return *Kind;
8572     }
8573     return NullabilityKind::Unspecified;
8574   };
8575 
8576   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8577   NullabilityKind MergedKind;
8578 
8579   // Compute nullability of a binary conditional expression.
8580   if (IsBin) {
8581     if (LHSKind == NullabilityKind::NonNull)
8582       MergedKind = NullabilityKind::NonNull;
8583     else
8584       MergedKind = RHSKind;
8585   // Compute nullability of a normal conditional expression.
8586   } else {
8587     if (LHSKind == NullabilityKind::Nullable ||
8588         RHSKind == NullabilityKind::Nullable)
8589       MergedKind = NullabilityKind::Nullable;
8590     else if (LHSKind == NullabilityKind::NonNull)
8591       MergedKind = RHSKind;
8592     else if (RHSKind == NullabilityKind::NonNull)
8593       MergedKind = LHSKind;
8594     else
8595       MergedKind = NullabilityKind::Unspecified;
8596   }
8597 
8598   // Return if ResTy already has the correct nullability.
8599   if (GetNullability(ResTy) == MergedKind)
8600     return ResTy;
8601 
8602   // Strip all nullability from ResTy.
8603   while (ResTy->getNullability(Ctx))
8604     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8605 
8606   // Create a new AttributedType with the new nullability kind.
8607   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8608   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8609 }
8610 
8611 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8612 /// in the case of a the GNU conditional expr extension.
8613 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8614                                     SourceLocation ColonLoc,
8615                                     Expr *CondExpr, Expr *LHSExpr,
8616                                     Expr *RHSExpr) {
8617   if (!Context.isDependenceAllowed()) {
8618     // C cannot handle TypoExpr nodes in the condition because it
8619     // doesn't handle dependent types properly, so make sure any TypoExprs have
8620     // been dealt with before checking the operands.
8621     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8622     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8623     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8624 
8625     if (!CondResult.isUsable())
8626       return ExprError();
8627 
8628     if (LHSExpr) {
8629       if (!LHSResult.isUsable())
8630         return ExprError();
8631     }
8632 
8633     if (!RHSResult.isUsable())
8634       return ExprError();
8635 
8636     CondExpr = CondResult.get();
8637     LHSExpr = LHSResult.get();
8638     RHSExpr = RHSResult.get();
8639   }
8640 
8641   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8642   // was the condition.
8643   OpaqueValueExpr *opaqueValue = nullptr;
8644   Expr *commonExpr = nullptr;
8645   if (!LHSExpr) {
8646     commonExpr = CondExpr;
8647     // Lower out placeholder types first.  This is important so that we don't
8648     // try to capture a placeholder. This happens in few cases in C++; such
8649     // as Objective-C++'s dictionary subscripting syntax.
8650     if (commonExpr->hasPlaceholderType()) {
8651       ExprResult result = CheckPlaceholderExpr(commonExpr);
8652       if (!result.isUsable()) return ExprError();
8653       commonExpr = result.get();
8654     }
8655     // We usually want to apply unary conversions *before* saving, except
8656     // in the special case of a C++ l-value conditional.
8657     if (!(getLangOpts().CPlusPlus
8658           && !commonExpr->isTypeDependent()
8659           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8660           && commonExpr->isGLValue()
8661           && commonExpr->isOrdinaryOrBitFieldObject()
8662           && RHSExpr->isOrdinaryOrBitFieldObject()
8663           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8664       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8665       if (commonRes.isInvalid())
8666         return ExprError();
8667       commonExpr = commonRes.get();
8668     }
8669 
8670     // If the common expression is a class or array prvalue, materialize it
8671     // so that we can safely refer to it multiple times.
8672     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8673                                    commonExpr->getType()->isArrayType())) {
8674       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8675       if (MatExpr.isInvalid())
8676         return ExprError();
8677       commonExpr = MatExpr.get();
8678     }
8679 
8680     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8681                                                 commonExpr->getType(),
8682                                                 commonExpr->getValueKind(),
8683                                                 commonExpr->getObjectKind(),
8684                                                 commonExpr);
8685     LHSExpr = CondExpr = opaqueValue;
8686   }
8687 
8688   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8689   ExprValueKind VK = VK_RValue;
8690   ExprObjectKind OK = OK_Ordinary;
8691   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8692   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8693                                              VK, OK, QuestionLoc);
8694   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8695       RHS.isInvalid())
8696     return ExprError();
8697 
8698   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8699                                 RHS.get());
8700 
8701   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8702 
8703   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8704                                          Context);
8705 
8706   if (!commonExpr)
8707     return new (Context)
8708         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8709                             RHS.get(), result, VK, OK);
8710 
8711   return new (Context) BinaryConditionalOperator(
8712       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8713       ColonLoc, result, VK, OK);
8714 }
8715 
8716 // Check if we have a conversion between incompatible cmse function pointer
8717 // types, that is, a conversion between a function pointer with the
8718 // cmse_nonsecure_call attribute and one without.
8719 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8720                                           QualType ToType) {
8721   if (const auto *ToFn =
8722           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8723     if (const auto *FromFn =
8724             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8725       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8726       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8727 
8728       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8729     }
8730   }
8731   return false;
8732 }
8733 
8734 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8735 // being closely modeled after the C99 spec:-). The odd characteristic of this
8736 // routine is it effectively iqnores the qualifiers on the top level pointee.
8737 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8738 // FIXME: add a couple examples in this comment.
8739 static Sema::AssignConvertType
8740 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8741   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8742   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8743 
8744   // get the "pointed to" type (ignoring qualifiers at the top level)
8745   const Type *lhptee, *rhptee;
8746   Qualifiers lhq, rhq;
8747   std::tie(lhptee, lhq) =
8748       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8749   std::tie(rhptee, rhq) =
8750       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8751 
8752   Sema::AssignConvertType ConvTy = Sema::Compatible;
8753 
8754   // C99 6.5.16.1p1: This following citation is common to constraints
8755   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8756   // qualifiers of the type *pointed to* by the right;
8757 
8758   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8759   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8760       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8761     // Ignore lifetime for further calculation.
8762     lhq.removeObjCLifetime();
8763     rhq.removeObjCLifetime();
8764   }
8765 
8766   if (!lhq.compatiblyIncludes(rhq)) {
8767     // Treat address-space mismatches as fatal.
8768     if (!lhq.isAddressSpaceSupersetOf(rhq))
8769       return Sema::IncompatiblePointerDiscardsQualifiers;
8770 
8771     // It's okay to add or remove GC or lifetime qualifiers when converting to
8772     // and from void*.
8773     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8774                         .compatiblyIncludes(
8775                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8776              && (lhptee->isVoidType() || rhptee->isVoidType()))
8777       ; // keep old
8778 
8779     // Treat lifetime mismatches as fatal.
8780     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8781       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8782 
8783     // For GCC/MS compatibility, other qualifier mismatches are treated
8784     // as still compatible in C.
8785     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8786   }
8787 
8788   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8789   // incomplete type and the other is a pointer to a qualified or unqualified
8790   // version of void...
8791   if (lhptee->isVoidType()) {
8792     if (rhptee->isIncompleteOrObjectType())
8793       return ConvTy;
8794 
8795     // As an extension, we allow cast to/from void* to function pointer.
8796     assert(rhptee->isFunctionType());
8797     return Sema::FunctionVoidPointer;
8798   }
8799 
8800   if (rhptee->isVoidType()) {
8801     if (lhptee->isIncompleteOrObjectType())
8802       return ConvTy;
8803 
8804     // As an extension, we allow cast to/from void* to function pointer.
8805     assert(lhptee->isFunctionType());
8806     return Sema::FunctionVoidPointer;
8807   }
8808 
8809   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8810   // unqualified versions of compatible types, ...
8811   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8812   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8813     // Check if the pointee types are compatible ignoring the sign.
8814     // We explicitly check for char so that we catch "char" vs
8815     // "unsigned char" on systems where "char" is unsigned.
8816     if (lhptee->isCharType())
8817       ltrans = S.Context.UnsignedCharTy;
8818     else if (lhptee->hasSignedIntegerRepresentation())
8819       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8820 
8821     if (rhptee->isCharType())
8822       rtrans = S.Context.UnsignedCharTy;
8823     else if (rhptee->hasSignedIntegerRepresentation())
8824       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8825 
8826     if (ltrans == rtrans) {
8827       // Types are compatible ignoring the sign. Qualifier incompatibility
8828       // takes priority over sign incompatibility because the sign
8829       // warning can be disabled.
8830       if (ConvTy != Sema::Compatible)
8831         return ConvTy;
8832 
8833       return Sema::IncompatiblePointerSign;
8834     }
8835 
8836     // If we are a multi-level pointer, it's possible that our issue is simply
8837     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8838     // the eventual target type is the same and the pointers have the same
8839     // level of indirection, this must be the issue.
8840     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8841       do {
8842         std::tie(lhptee, lhq) =
8843           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8844         std::tie(rhptee, rhq) =
8845           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8846 
8847         // Inconsistent address spaces at this point is invalid, even if the
8848         // address spaces would be compatible.
8849         // FIXME: This doesn't catch address space mismatches for pointers of
8850         // different nesting levels, like:
8851         //   __local int *** a;
8852         //   int ** b = a;
8853         // It's not clear how to actually determine when such pointers are
8854         // invalidly incompatible.
8855         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8856           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8857 
8858       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8859 
8860       if (lhptee == rhptee)
8861         return Sema::IncompatibleNestedPointerQualifiers;
8862     }
8863 
8864     // General pointer incompatibility takes priority over qualifiers.
8865     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8866       return Sema::IncompatibleFunctionPointer;
8867     return Sema::IncompatiblePointer;
8868   }
8869   if (!S.getLangOpts().CPlusPlus &&
8870       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8871     return Sema::IncompatibleFunctionPointer;
8872   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8873     return Sema::IncompatibleFunctionPointer;
8874   return ConvTy;
8875 }
8876 
8877 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8878 /// block pointer types are compatible or whether a block and normal pointer
8879 /// are compatible. It is more restrict than comparing two function pointer
8880 // types.
8881 static Sema::AssignConvertType
8882 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8883                                     QualType RHSType) {
8884   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8885   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8886 
8887   QualType lhptee, rhptee;
8888 
8889   // get the "pointed to" type (ignoring qualifiers at the top level)
8890   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8891   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8892 
8893   // In C++, the types have to match exactly.
8894   if (S.getLangOpts().CPlusPlus)
8895     return Sema::IncompatibleBlockPointer;
8896 
8897   Sema::AssignConvertType ConvTy = Sema::Compatible;
8898 
8899   // For blocks we enforce that qualifiers are identical.
8900   Qualifiers LQuals = lhptee.getLocalQualifiers();
8901   Qualifiers RQuals = rhptee.getLocalQualifiers();
8902   if (S.getLangOpts().OpenCL) {
8903     LQuals.removeAddressSpace();
8904     RQuals.removeAddressSpace();
8905   }
8906   if (LQuals != RQuals)
8907     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8908 
8909   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8910   // assignment.
8911   // The current behavior is similar to C++ lambdas. A block might be
8912   // assigned to a variable iff its return type and parameters are compatible
8913   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8914   // an assignment. Presumably it should behave in way that a function pointer
8915   // assignment does in C, so for each parameter and return type:
8916   //  * CVR and address space of LHS should be a superset of CVR and address
8917   //  space of RHS.
8918   //  * unqualified types should be compatible.
8919   if (S.getLangOpts().OpenCL) {
8920     if (!S.Context.typesAreBlockPointerCompatible(
8921             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8922             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8923       return Sema::IncompatibleBlockPointer;
8924   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8925     return Sema::IncompatibleBlockPointer;
8926 
8927   return ConvTy;
8928 }
8929 
8930 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8931 /// for assignment compatibility.
8932 static Sema::AssignConvertType
8933 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8934                                    QualType RHSType) {
8935   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8936   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8937 
8938   if (LHSType->isObjCBuiltinType()) {
8939     // Class is not compatible with ObjC object pointers.
8940     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8941         !RHSType->isObjCQualifiedClassType())
8942       return Sema::IncompatiblePointer;
8943     return Sema::Compatible;
8944   }
8945   if (RHSType->isObjCBuiltinType()) {
8946     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8947         !LHSType->isObjCQualifiedClassType())
8948       return Sema::IncompatiblePointer;
8949     return Sema::Compatible;
8950   }
8951   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8952   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8953 
8954   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8955       // make an exception for id<P>
8956       !LHSType->isObjCQualifiedIdType())
8957     return Sema::CompatiblePointerDiscardsQualifiers;
8958 
8959   if (S.Context.typesAreCompatible(LHSType, RHSType))
8960     return Sema::Compatible;
8961   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8962     return Sema::IncompatibleObjCQualifiedId;
8963   return Sema::IncompatiblePointer;
8964 }
8965 
8966 Sema::AssignConvertType
8967 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8968                                  QualType LHSType, QualType RHSType) {
8969   // Fake up an opaque expression.  We don't actually care about what
8970   // cast operations are required, so if CheckAssignmentConstraints
8971   // adds casts to this they'll be wasted, but fortunately that doesn't
8972   // usually happen on valid code.
8973   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8974   ExprResult RHSPtr = &RHSExpr;
8975   CastKind K;
8976 
8977   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8978 }
8979 
8980 /// This helper function returns true if QT is a vector type that has element
8981 /// type ElementType.
8982 static bool isVector(QualType QT, QualType ElementType) {
8983   if (const VectorType *VT = QT->getAs<VectorType>())
8984     return VT->getElementType().getCanonicalType() == ElementType;
8985   return false;
8986 }
8987 
8988 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8989 /// has code to accommodate several GCC extensions when type checking
8990 /// pointers. Here are some objectionable examples that GCC considers warnings:
8991 ///
8992 ///  int a, *pint;
8993 ///  short *pshort;
8994 ///  struct foo *pfoo;
8995 ///
8996 ///  pint = pshort; // warning: assignment from incompatible pointer type
8997 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8998 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8999 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9000 ///
9001 /// As a result, the code for dealing with pointers is more complex than the
9002 /// C99 spec dictates.
9003 ///
9004 /// Sets 'Kind' for any result kind except Incompatible.
9005 Sema::AssignConvertType
9006 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9007                                  CastKind &Kind, bool ConvertRHS) {
9008   QualType RHSType = RHS.get()->getType();
9009   QualType OrigLHSType = LHSType;
9010 
9011   // Get canonical types.  We're not formatting these types, just comparing
9012   // them.
9013   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9014   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9015 
9016   // Common case: no conversion required.
9017   if (LHSType == RHSType) {
9018     Kind = CK_NoOp;
9019     return Compatible;
9020   }
9021 
9022   // If we have an atomic type, try a non-atomic assignment, then just add an
9023   // atomic qualification step.
9024   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9025     Sema::AssignConvertType result =
9026       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9027     if (result != Compatible)
9028       return result;
9029     if (Kind != CK_NoOp && ConvertRHS)
9030       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9031     Kind = CK_NonAtomicToAtomic;
9032     return Compatible;
9033   }
9034 
9035   // If the left-hand side is a reference type, then we are in a
9036   // (rare!) case where we've allowed the use of references in C,
9037   // e.g., as a parameter type in a built-in function. In this case,
9038   // just make sure that the type referenced is compatible with the
9039   // right-hand side type. The caller is responsible for adjusting
9040   // LHSType so that the resulting expression does not have reference
9041   // type.
9042   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9043     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9044       Kind = CK_LValueBitCast;
9045       return Compatible;
9046     }
9047     return Incompatible;
9048   }
9049 
9050   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9051   // to the same ExtVector type.
9052   if (LHSType->isExtVectorType()) {
9053     if (RHSType->isExtVectorType())
9054       return Incompatible;
9055     if (RHSType->isArithmeticType()) {
9056       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9057       if (ConvertRHS)
9058         RHS = prepareVectorSplat(LHSType, RHS.get());
9059       Kind = CK_VectorSplat;
9060       return Compatible;
9061     }
9062   }
9063 
9064   // Conversions to or from vector type.
9065   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9066     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9067       // Allow assignments of an AltiVec vector type to an equivalent GCC
9068       // vector type and vice versa
9069       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9070         Kind = CK_BitCast;
9071         return Compatible;
9072       }
9073 
9074       // If we are allowing lax vector conversions, and LHS and RHS are both
9075       // vectors, the total size only needs to be the same. This is a bitcast;
9076       // no bits are changed but the result type is different.
9077       if (isLaxVectorConversion(RHSType, LHSType)) {
9078         Kind = CK_BitCast;
9079         return IncompatibleVectors;
9080       }
9081     }
9082 
9083     // When the RHS comes from another lax conversion (e.g. binops between
9084     // scalars and vectors) the result is canonicalized as a vector. When the
9085     // LHS is also a vector, the lax is allowed by the condition above. Handle
9086     // the case where LHS is a scalar.
9087     if (LHSType->isScalarType()) {
9088       const VectorType *VecType = RHSType->getAs<VectorType>();
9089       if (VecType && VecType->getNumElements() == 1 &&
9090           isLaxVectorConversion(RHSType, LHSType)) {
9091         ExprResult *VecExpr = &RHS;
9092         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9093         Kind = CK_BitCast;
9094         return Compatible;
9095       }
9096     }
9097 
9098     // Allow assignments between fixed-length and sizeless SVE vectors.
9099     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9100         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9101       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9102           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9103         Kind = CK_BitCast;
9104         return Compatible;
9105       }
9106 
9107     return Incompatible;
9108   }
9109 
9110   // Diagnose attempts to convert between __float128 and long double where
9111   // such conversions currently can't be handled.
9112   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9113     return Incompatible;
9114 
9115   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9116   // discards the imaginary part.
9117   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9118       !LHSType->getAs<ComplexType>())
9119     return Incompatible;
9120 
9121   // Arithmetic conversions.
9122   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9123       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9124     if (ConvertRHS)
9125       Kind = PrepareScalarCast(RHS, LHSType);
9126     return Compatible;
9127   }
9128 
9129   // Conversions to normal pointers.
9130   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9131     // U* -> T*
9132     if (isa<PointerType>(RHSType)) {
9133       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9134       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9135       if (AddrSpaceL != AddrSpaceR)
9136         Kind = CK_AddressSpaceConversion;
9137       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9138         Kind = CK_NoOp;
9139       else
9140         Kind = CK_BitCast;
9141       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9142     }
9143 
9144     // int -> T*
9145     if (RHSType->isIntegerType()) {
9146       Kind = CK_IntegralToPointer; // FIXME: null?
9147       return IntToPointer;
9148     }
9149 
9150     // C pointers are not compatible with ObjC object pointers,
9151     // with two exceptions:
9152     if (isa<ObjCObjectPointerType>(RHSType)) {
9153       //  - conversions to void*
9154       if (LHSPointer->getPointeeType()->isVoidType()) {
9155         Kind = CK_BitCast;
9156         return Compatible;
9157       }
9158 
9159       //  - conversions from 'Class' to the redefinition type
9160       if (RHSType->isObjCClassType() &&
9161           Context.hasSameType(LHSType,
9162                               Context.getObjCClassRedefinitionType())) {
9163         Kind = CK_BitCast;
9164         return Compatible;
9165       }
9166 
9167       Kind = CK_BitCast;
9168       return IncompatiblePointer;
9169     }
9170 
9171     // U^ -> void*
9172     if (RHSType->getAs<BlockPointerType>()) {
9173       if (LHSPointer->getPointeeType()->isVoidType()) {
9174         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9175         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9176                                 ->getPointeeType()
9177                                 .getAddressSpace();
9178         Kind =
9179             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9180         return Compatible;
9181       }
9182     }
9183 
9184     return Incompatible;
9185   }
9186 
9187   // Conversions to block pointers.
9188   if (isa<BlockPointerType>(LHSType)) {
9189     // U^ -> T^
9190     if (RHSType->isBlockPointerType()) {
9191       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9192                               ->getPointeeType()
9193                               .getAddressSpace();
9194       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9195                               ->getPointeeType()
9196                               .getAddressSpace();
9197       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9198       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9199     }
9200 
9201     // int or null -> T^
9202     if (RHSType->isIntegerType()) {
9203       Kind = CK_IntegralToPointer; // FIXME: null
9204       return IntToBlockPointer;
9205     }
9206 
9207     // id -> T^
9208     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9209       Kind = CK_AnyPointerToBlockPointerCast;
9210       return Compatible;
9211     }
9212 
9213     // void* -> T^
9214     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9215       if (RHSPT->getPointeeType()->isVoidType()) {
9216         Kind = CK_AnyPointerToBlockPointerCast;
9217         return Compatible;
9218       }
9219 
9220     return Incompatible;
9221   }
9222 
9223   // Conversions to Objective-C pointers.
9224   if (isa<ObjCObjectPointerType>(LHSType)) {
9225     // A* -> B*
9226     if (RHSType->isObjCObjectPointerType()) {
9227       Kind = CK_BitCast;
9228       Sema::AssignConvertType result =
9229         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9230       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9231           result == Compatible &&
9232           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9233         result = IncompatibleObjCWeakRef;
9234       return result;
9235     }
9236 
9237     // int or null -> A*
9238     if (RHSType->isIntegerType()) {
9239       Kind = CK_IntegralToPointer; // FIXME: null
9240       return IntToPointer;
9241     }
9242 
9243     // In general, C pointers are not compatible with ObjC object pointers,
9244     // with two exceptions:
9245     if (isa<PointerType>(RHSType)) {
9246       Kind = CK_CPointerToObjCPointerCast;
9247 
9248       //  - conversions from 'void*'
9249       if (RHSType->isVoidPointerType()) {
9250         return Compatible;
9251       }
9252 
9253       //  - conversions to 'Class' from its redefinition type
9254       if (LHSType->isObjCClassType() &&
9255           Context.hasSameType(RHSType,
9256                               Context.getObjCClassRedefinitionType())) {
9257         return Compatible;
9258       }
9259 
9260       return IncompatiblePointer;
9261     }
9262 
9263     // Only under strict condition T^ is compatible with an Objective-C pointer.
9264     if (RHSType->isBlockPointerType() &&
9265         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9266       if (ConvertRHS)
9267         maybeExtendBlockObject(RHS);
9268       Kind = CK_BlockPointerToObjCPointerCast;
9269       return Compatible;
9270     }
9271 
9272     return Incompatible;
9273   }
9274 
9275   // Conversions from pointers that are not covered by the above.
9276   if (isa<PointerType>(RHSType)) {
9277     // T* -> _Bool
9278     if (LHSType == Context.BoolTy) {
9279       Kind = CK_PointerToBoolean;
9280       return Compatible;
9281     }
9282 
9283     // T* -> int
9284     if (LHSType->isIntegerType()) {
9285       Kind = CK_PointerToIntegral;
9286       return PointerToInt;
9287     }
9288 
9289     return Incompatible;
9290   }
9291 
9292   // Conversions from Objective-C pointers that are not covered by the above.
9293   if (isa<ObjCObjectPointerType>(RHSType)) {
9294     // T* -> _Bool
9295     if (LHSType == Context.BoolTy) {
9296       Kind = CK_PointerToBoolean;
9297       return Compatible;
9298     }
9299 
9300     // T* -> int
9301     if (LHSType->isIntegerType()) {
9302       Kind = CK_PointerToIntegral;
9303       return PointerToInt;
9304     }
9305 
9306     return Incompatible;
9307   }
9308 
9309   // struct A -> struct B
9310   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9311     if (Context.typesAreCompatible(LHSType, RHSType)) {
9312       Kind = CK_NoOp;
9313       return Compatible;
9314     }
9315   }
9316 
9317   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9318     Kind = CK_IntToOCLSampler;
9319     return Compatible;
9320   }
9321 
9322   return Incompatible;
9323 }
9324 
9325 /// Constructs a transparent union from an expression that is
9326 /// used to initialize the transparent union.
9327 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9328                                       ExprResult &EResult, QualType UnionType,
9329                                       FieldDecl *Field) {
9330   // Build an initializer list that designates the appropriate member
9331   // of the transparent union.
9332   Expr *E = EResult.get();
9333   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9334                                                    E, SourceLocation());
9335   Initializer->setType(UnionType);
9336   Initializer->setInitializedFieldInUnion(Field);
9337 
9338   // Build a compound literal constructing a value of the transparent
9339   // union type from this initializer list.
9340   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9341   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9342                                         VK_RValue, Initializer, false);
9343 }
9344 
9345 Sema::AssignConvertType
9346 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9347                                                ExprResult &RHS) {
9348   QualType RHSType = RHS.get()->getType();
9349 
9350   // If the ArgType is a Union type, we want to handle a potential
9351   // transparent_union GCC extension.
9352   const RecordType *UT = ArgType->getAsUnionType();
9353   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9354     return Incompatible;
9355 
9356   // The field to initialize within the transparent union.
9357   RecordDecl *UD = UT->getDecl();
9358   FieldDecl *InitField = nullptr;
9359   // It's compatible if the expression matches any of the fields.
9360   for (auto *it : UD->fields()) {
9361     if (it->getType()->isPointerType()) {
9362       // If the transparent union contains a pointer type, we allow:
9363       // 1) void pointer
9364       // 2) null pointer constant
9365       if (RHSType->isPointerType())
9366         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9367           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9368           InitField = it;
9369           break;
9370         }
9371 
9372       if (RHS.get()->isNullPointerConstant(Context,
9373                                            Expr::NPC_ValueDependentIsNull)) {
9374         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9375                                 CK_NullToPointer);
9376         InitField = it;
9377         break;
9378       }
9379     }
9380 
9381     CastKind Kind;
9382     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9383           == Compatible) {
9384       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9385       InitField = it;
9386       break;
9387     }
9388   }
9389 
9390   if (!InitField)
9391     return Incompatible;
9392 
9393   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9394   return Compatible;
9395 }
9396 
9397 Sema::AssignConvertType
9398 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9399                                        bool Diagnose,
9400                                        bool DiagnoseCFAudited,
9401                                        bool ConvertRHS) {
9402   // We need to be able to tell the caller whether we diagnosed a problem, if
9403   // they ask us to issue diagnostics.
9404   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9405 
9406   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9407   // we can't avoid *all* modifications at the moment, so we need some somewhere
9408   // to put the updated value.
9409   ExprResult LocalRHS = CallerRHS;
9410   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9411 
9412   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9413     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9414       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9415           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9416         Diag(RHS.get()->getExprLoc(),
9417              diag::warn_noderef_to_dereferenceable_pointer)
9418             << RHS.get()->getSourceRange();
9419       }
9420     }
9421   }
9422 
9423   if (getLangOpts().CPlusPlus) {
9424     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9425       // C++ 5.17p3: If the left operand is not of class type, the
9426       // expression is implicitly converted (C++ 4) to the
9427       // cv-unqualified type of the left operand.
9428       QualType RHSType = RHS.get()->getType();
9429       if (Diagnose) {
9430         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9431                                         AA_Assigning);
9432       } else {
9433         ImplicitConversionSequence ICS =
9434             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9435                                   /*SuppressUserConversions=*/false,
9436                                   AllowedExplicit::None,
9437                                   /*InOverloadResolution=*/false,
9438                                   /*CStyle=*/false,
9439                                   /*AllowObjCWritebackConversion=*/false);
9440         if (ICS.isFailure())
9441           return Incompatible;
9442         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9443                                         ICS, AA_Assigning);
9444       }
9445       if (RHS.isInvalid())
9446         return Incompatible;
9447       Sema::AssignConvertType result = Compatible;
9448       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9449           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9450         result = IncompatibleObjCWeakRef;
9451       return result;
9452     }
9453 
9454     // FIXME: Currently, we fall through and treat C++ classes like C
9455     // structures.
9456     // FIXME: We also fall through for atomics; not sure what should
9457     // happen there, though.
9458   } else if (RHS.get()->getType() == Context.OverloadTy) {
9459     // As a set of extensions to C, we support overloading on functions. These
9460     // functions need to be resolved here.
9461     DeclAccessPair DAP;
9462     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9463             RHS.get(), LHSType, /*Complain=*/false, DAP))
9464       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9465     else
9466       return Incompatible;
9467   }
9468 
9469   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9470   // a null pointer constant.
9471   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9472        LHSType->isBlockPointerType()) &&
9473       RHS.get()->isNullPointerConstant(Context,
9474                                        Expr::NPC_ValueDependentIsNull)) {
9475     if (Diagnose || ConvertRHS) {
9476       CastKind Kind;
9477       CXXCastPath Path;
9478       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9479                              /*IgnoreBaseAccess=*/false, Diagnose);
9480       if (ConvertRHS)
9481         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9482     }
9483     return Compatible;
9484   }
9485 
9486   // OpenCL queue_t type assignment.
9487   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9488                                  Context, Expr::NPC_ValueDependentIsNull)) {
9489     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9490     return Compatible;
9491   }
9492 
9493   // This check seems unnatural, however it is necessary to ensure the proper
9494   // conversion of functions/arrays. If the conversion were done for all
9495   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9496   // expressions that suppress this implicit conversion (&, sizeof).
9497   //
9498   // Suppress this for references: C++ 8.5.3p5.
9499   if (!LHSType->isReferenceType()) {
9500     // FIXME: We potentially allocate here even if ConvertRHS is false.
9501     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9502     if (RHS.isInvalid())
9503       return Incompatible;
9504   }
9505   CastKind Kind;
9506   Sema::AssignConvertType result =
9507     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9508 
9509   // C99 6.5.16.1p2: The value of the right operand is converted to the
9510   // type of the assignment expression.
9511   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9512   // so that we can use references in built-in functions even in C.
9513   // The getNonReferenceType() call makes sure that the resulting expression
9514   // does not have reference type.
9515   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9516     QualType Ty = LHSType.getNonLValueExprType(Context);
9517     Expr *E = RHS.get();
9518 
9519     // Check for various Objective-C errors. If we are not reporting
9520     // diagnostics and just checking for errors, e.g., during overload
9521     // resolution, return Incompatible to indicate the failure.
9522     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9523         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9524                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9525       if (!Diagnose)
9526         return Incompatible;
9527     }
9528     if (getLangOpts().ObjC &&
9529         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9530                                            E->getType(), E, Diagnose) ||
9531          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9532       if (!Diagnose)
9533         return Incompatible;
9534       // Replace the expression with a corrected version and continue so we
9535       // can find further errors.
9536       RHS = E;
9537       return Compatible;
9538     }
9539 
9540     if (ConvertRHS)
9541       RHS = ImpCastExprToType(E, Ty, Kind);
9542   }
9543 
9544   return result;
9545 }
9546 
9547 namespace {
9548 /// The original operand to an operator, prior to the application of the usual
9549 /// arithmetic conversions and converting the arguments of a builtin operator
9550 /// candidate.
9551 struct OriginalOperand {
9552   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9553     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9554       Op = MTE->getSubExpr();
9555     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9556       Op = BTE->getSubExpr();
9557     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9558       Orig = ICE->getSubExprAsWritten();
9559       Conversion = ICE->getConversionFunction();
9560     }
9561   }
9562 
9563   QualType getType() const { return Orig->getType(); }
9564 
9565   Expr *Orig;
9566   NamedDecl *Conversion;
9567 };
9568 }
9569 
9570 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9571                                ExprResult &RHS) {
9572   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9573 
9574   Diag(Loc, diag::err_typecheck_invalid_operands)
9575     << OrigLHS.getType() << OrigRHS.getType()
9576     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9577 
9578   // If a user-defined conversion was applied to either of the operands prior
9579   // to applying the built-in operator rules, tell the user about it.
9580   if (OrigLHS.Conversion) {
9581     Diag(OrigLHS.Conversion->getLocation(),
9582          diag::note_typecheck_invalid_operands_converted)
9583       << 0 << LHS.get()->getType();
9584   }
9585   if (OrigRHS.Conversion) {
9586     Diag(OrigRHS.Conversion->getLocation(),
9587          diag::note_typecheck_invalid_operands_converted)
9588       << 1 << RHS.get()->getType();
9589   }
9590 
9591   return QualType();
9592 }
9593 
9594 // Diagnose cases where a scalar was implicitly converted to a vector and
9595 // diagnose the underlying types. Otherwise, diagnose the error
9596 // as invalid vector logical operands for non-C++ cases.
9597 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9598                                             ExprResult &RHS) {
9599   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9600   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9601 
9602   bool LHSNatVec = LHSType->isVectorType();
9603   bool RHSNatVec = RHSType->isVectorType();
9604 
9605   if (!(LHSNatVec && RHSNatVec)) {
9606     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9607     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9608     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9609         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9610         << Vector->getSourceRange();
9611     return QualType();
9612   }
9613 
9614   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9615       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9616       << RHS.get()->getSourceRange();
9617 
9618   return QualType();
9619 }
9620 
9621 /// Try to convert a value of non-vector type to a vector type by converting
9622 /// the type to the element type of the vector and then performing a splat.
9623 /// If the language is OpenCL, we only use conversions that promote scalar
9624 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9625 /// for float->int.
9626 ///
9627 /// OpenCL V2.0 6.2.6.p2:
9628 /// An error shall occur if any scalar operand type has greater rank
9629 /// than the type of the vector element.
9630 ///
9631 /// \param scalar - if non-null, actually perform the conversions
9632 /// \return true if the operation fails (but without diagnosing the failure)
9633 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9634                                      QualType scalarTy,
9635                                      QualType vectorEltTy,
9636                                      QualType vectorTy,
9637                                      unsigned &DiagID) {
9638   // The conversion to apply to the scalar before splatting it,
9639   // if necessary.
9640   CastKind scalarCast = CK_NoOp;
9641 
9642   if (vectorEltTy->isIntegralType(S.Context)) {
9643     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9644         (scalarTy->isIntegerType() &&
9645          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9646       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9647       return true;
9648     }
9649     if (!scalarTy->isIntegralType(S.Context))
9650       return true;
9651     scalarCast = CK_IntegralCast;
9652   } else if (vectorEltTy->isRealFloatingType()) {
9653     if (scalarTy->isRealFloatingType()) {
9654       if (S.getLangOpts().OpenCL &&
9655           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9656         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9657         return true;
9658       }
9659       scalarCast = CK_FloatingCast;
9660     }
9661     else if (scalarTy->isIntegralType(S.Context))
9662       scalarCast = CK_IntegralToFloating;
9663     else
9664       return true;
9665   } else {
9666     return true;
9667   }
9668 
9669   // Adjust scalar if desired.
9670   if (scalar) {
9671     if (scalarCast != CK_NoOp)
9672       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9673     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9674   }
9675   return false;
9676 }
9677 
9678 /// Convert vector E to a vector with the same number of elements but different
9679 /// element type.
9680 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9681   const auto *VecTy = E->getType()->getAs<VectorType>();
9682   assert(VecTy && "Expression E must be a vector");
9683   QualType NewVecTy = S.Context.getVectorType(ElementType,
9684                                               VecTy->getNumElements(),
9685                                               VecTy->getVectorKind());
9686 
9687   // Look through the implicit cast. Return the subexpression if its type is
9688   // NewVecTy.
9689   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9690     if (ICE->getSubExpr()->getType() == NewVecTy)
9691       return ICE->getSubExpr();
9692 
9693   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9694   return S.ImpCastExprToType(E, NewVecTy, Cast);
9695 }
9696 
9697 /// Test if a (constant) integer Int can be casted to another integer type
9698 /// IntTy without losing precision.
9699 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9700                                       QualType OtherIntTy) {
9701   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9702 
9703   // Reject cases where the value of the Int is unknown as that would
9704   // possibly cause truncation, but accept cases where the scalar can be
9705   // demoted without loss of precision.
9706   Expr::EvalResult EVResult;
9707   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9708   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9709   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9710   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9711 
9712   if (CstInt) {
9713     // If the scalar is constant and is of a higher order and has more active
9714     // bits that the vector element type, reject it.
9715     llvm::APSInt Result = EVResult.Val.getInt();
9716     unsigned NumBits = IntSigned
9717                            ? (Result.isNegative() ? Result.getMinSignedBits()
9718                                                   : Result.getActiveBits())
9719                            : Result.getActiveBits();
9720     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9721       return true;
9722 
9723     // If the signedness of the scalar type and the vector element type
9724     // differs and the number of bits is greater than that of the vector
9725     // element reject it.
9726     return (IntSigned != OtherIntSigned &&
9727             NumBits > S.Context.getIntWidth(OtherIntTy));
9728   }
9729 
9730   // Reject cases where the value of the scalar is not constant and it's
9731   // order is greater than that of the vector element type.
9732   return (Order < 0);
9733 }
9734 
9735 /// Test if a (constant) integer Int can be casted to floating point type
9736 /// FloatTy without losing precision.
9737 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9738                                      QualType FloatTy) {
9739   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9740 
9741   // Determine if the integer constant can be expressed as a floating point
9742   // number of the appropriate type.
9743   Expr::EvalResult EVResult;
9744   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9745 
9746   uint64_t Bits = 0;
9747   if (CstInt) {
9748     // Reject constants that would be truncated if they were converted to
9749     // the floating point type. Test by simple to/from conversion.
9750     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9751     //        could be avoided if there was a convertFromAPInt method
9752     //        which could signal back if implicit truncation occurred.
9753     llvm::APSInt Result = EVResult.Val.getInt();
9754     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9755     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9756                            llvm::APFloat::rmTowardZero);
9757     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9758                              !IntTy->hasSignedIntegerRepresentation());
9759     bool Ignored = false;
9760     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9761                            &Ignored);
9762     if (Result != ConvertBack)
9763       return true;
9764   } else {
9765     // Reject types that cannot be fully encoded into the mantissa of
9766     // the float.
9767     Bits = S.Context.getTypeSize(IntTy);
9768     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9769         S.Context.getFloatTypeSemantics(FloatTy));
9770     if (Bits > FloatPrec)
9771       return true;
9772   }
9773 
9774   return false;
9775 }
9776 
9777 /// Attempt to convert and splat Scalar into a vector whose types matches
9778 /// Vector following GCC conversion rules. The rule is that implicit
9779 /// conversion can occur when Scalar can be casted to match Vector's element
9780 /// type without causing truncation of Scalar.
9781 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9782                                         ExprResult *Vector) {
9783   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9784   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9785   const VectorType *VT = VectorTy->getAs<VectorType>();
9786 
9787   assert(!isa<ExtVectorType>(VT) &&
9788          "ExtVectorTypes should not be handled here!");
9789 
9790   QualType VectorEltTy = VT->getElementType();
9791 
9792   // Reject cases where the vector element type or the scalar element type are
9793   // not integral or floating point types.
9794   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9795     return true;
9796 
9797   // The conversion to apply to the scalar before splatting it,
9798   // if necessary.
9799   CastKind ScalarCast = CK_NoOp;
9800 
9801   // Accept cases where the vector elements are integers and the scalar is
9802   // an integer.
9803   // FIXME: Notionally if the scalar was a floating point value with a precise
9804   //        integral representation, we could cast it to an appropriate integer
9805   //        type and then perform the rest of the checks here. GCC will perform
9806   //        this conversion in some cases as determined by the input language.
9807   //        We should accept it on a language independent basis.
9808   if (VectorEltTy->isIntegralType(S.Context) &&
9809       ScalarTy->isIntegralType(S.Context) &&
9810       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9811 
9812     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9813       return true;
9814 
9815     ScalarCast = CK_IntegralCast;
9816   } else if (VectorEltTy->isIntegralType(S.Context) &&
9817              ScalarTy->isRealFloatingType()) {
9818     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9819       ScalarCast = CK_FloatingToIntegral;
9820     else
9821       return true;
9822   } else if (VectorEltTy->isRealFloatingType()) {
9823     if (ScalarTy->isRealFloatingType()) {
9824 
9825       // Reject cases where the scalar type is not a constant and has a higher
9826       // Order than the vector element type.
9827       llvm::APFloat Result(0.0);
9828 
9829       // Determine whether this is a constant scalar. In the event that the
9830       // value is dependent (and thus cannot be evaluated by the constant
9831       // evaluator), skip the evaluation. This will then diagnose once the
9832       // expression is instantiated.
9833       bool CstScalar = Scalar->get()->isValueDependent() ||
9834                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9835       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9836       if (!CstScalar && Order < 0)
9837         return true;
9838 
9839       // If the scalar cannot be safely casted to the vector element type,
9840       // reject it.
9841       if (CstScalar) {
9842         bool Truncated = false;
9843         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9844                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9845         if (Truncated)
9846           return true;
9847       }
9848 
9849       ScalarCast = CK_FloatingCast;
9850     } else if (ScalarTy->isIntegralType(S.Context)) {
9851       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9852         return true;
9853 
9854       ScalarCast = CK_IntegralToFloating;
9855     } else
9856       return true;
9857   } else if (ScalarTy->isEnumeralType())
9858     return true;
9859 
9860   // Adjust scalar if desired.
9861   if (Scalar) {
9862     if (ScalarCast != CK_NoOp)
9863       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9864     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9865   }
9866   return false;
9867 }
9868 
9869 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9870                                    SourceLocation Loc, bool IsCompAssign,
9871                                    bool AllowBothBool,
9872                                    bool AllowBoolConversions) {
9873   if (!IsCompAssign) {
9874     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9875     if (LHS.isInvalid())
9876       return QualType();
9877   }
9878   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9879   if (RHS.isInvalid())
9880     return QualType();
9881 
9882   // For conversion purposes, we ignore any qualifiers.
9883   // For example, "const float" and "float" are equivalent.
9884   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9885   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9886 
9887   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9888   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9889   assert(LHSVecType || RHSVecType);
9890 
9891   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9892       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9893     return InvalidOperands(Loc, LHS, RHS);
9894 
9895   // AltiVec-style "vector bool op vector bool" combinations are allowed
9896   // for some operators but not others.
9897   if (!AllowBothBool &&
9898       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9899       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9900     return InvalidOperands(Loc, LHS, RHS);
9901 
9902   // If the vector types are identical, return.
9903   if (Context.hasSameType(LHSType, RHSType))
9904     return LHSType;
9905 
9906   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9907   if (LHSVecType && RHSVecType &&
9908       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9909     if (isa<ExtVectorType>(LHSVecType)) {
9910       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9911       return LHSType;
9912     }
9913 
9914     if (!IsCompAssign)
9915       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9916     return RHSType;
9917   }
9918 
9919   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9920   // can be mixed, with the result being the non-bool type.  The non-bool
9921   // operand must have integer element type.
9922   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9923       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9924       (Context.getTypeSize(LHSVecType->getElementType()) ==
9925        Context.getTypeSize(RHSVecType->getElementType()))) {
9926     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9927         LHSVecType->getElementType()->isIntegerType() &&
9928         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9929       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9930       return LHSType;
9931     }
9932     if (!IsCompAssign &&
9933         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9934         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9935         RHSVecType->getElementType()->isIntegerType()) {
9936       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9937       return RHSType;
9938     }
9939   }
9940 
9941   // Expressions containing fixed-length and sizeless SVE vectors are invalid
9942   // since the ambiguity can affect the ABI.
9943   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9944     const VectorType *VecType = SecondType->getAs<VectorType>();
9945     return FirstType->isSizelessBuiltinType() && VecType &&
9946            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9947             VecType->getVectorKind() ==
9948                 VectorType::SveFixedLengthPredicateVector);
9949   };
9950 
9951   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9952     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9953     return QualType();
9954   }
9955 
9956   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9957   // since the ambiguity can affect the ABI.
9958   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9959     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9960     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9961 
9962     if (FirstVecType && SecondVecType)
9963       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9964              (SecondVecType->getVectorKind() ==
9965                   VectorType::SveFixedLengthDataVector ||
9966               SecondVecType->getVectorKind() ==
9967                   VectorType::SveFixedLengthPredicateVector);
9968 
9969     return FirstType->isSizelessBuiltinType() && SecondVecType &&
9970            SecondVecType->getVectorKind() == VectorType::GenericVector;
9971   };
9972 
9973   if (IsSveGnuConversion(LHSType, RHSType) ||
9974       IsSveGnuConversion(RHSType, LHSType)) {
9975     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9976     return QualType();
9977   }
9978 
9979   // If there's a vector type and a scalar, try to convert the scalar to
9980   // the vector element type and splat.
9981   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9982   if (!RHSVecType) {
9983     if (isa<ExtVectorType>(LHSVecType)) {
9984       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9985                                     LHSVecType->getElementType(), LHSType,
9986                                     DiagID))
9987         return LHSType;
9988     } else {
9989       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9990         return LHSType;
9991     }
9992   }
9993   if (!LHSVecType) {
9994     if (isa<ExtVectorType>(RHSVecType)) {
9995       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9996                                     LHSType, RHSVecType->getElementType(),
9997                                     RHSType, DiagID))
9998         return RHSType;
9999     } else {
10000       if (LHS.get()->getValueKind() == VK_LValue ||
10001           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10002         return RHSType;
10003     }
10004   }
10005 
10006   // FIXME: The code below also handles conversion between vectors and
10007   // non-scalars, we should break this down into fine grained specific checks
10008   // and emit proper diagnostics.
10009   QualType VecType = LHSVecType ? LHSType : RHSType;
10010   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10011   QualType OtherType = LHSVecType ? RHSType : LHSType;
10012   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10013   if (isLaxVectorConversion(OtherType, VecType)) {
10014     // If we're allowing lax vector conversions, only the total (data) size
10015     // needs to be the same. For non compound assignment, if one of the types is
10016     // scalar, the result is always the vector type.
10017     if (!IsCompAssign) {
10018       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10019       return VecType;
10020     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10021     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10022     // type. Note that this is already done by non-compound assignments in
10023     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10024     // <1 x T> -> T. The result is also a vector type.
10025     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10026                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10027       ExprResult *RHSExpr = &RHS;
10028       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10029       return VecType;
10030     }
10031   }
10032 
10033   // Okay, the expression is invalid.
10034 
10035   // If there's a non-vector, non-real operand, diagnose that.
10036   if ((!RHSVecType && !RHSType->isRealType()) ||
10037       (!LHSVecType && !LHSType->isRealType())) {
10038     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10039       << LHSType << RHSType
10040       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10041     return QualType();
10042   }
10043 
10044   // OpenCL V1.1 6.2.6.p1:
10045   // If the operands are of more than one vector type, then an error shall
10046   // occur. Implicit conversions between vector types are not permitted, per
10047   // section 6.2.1.
10048   if (getLangOpts().OpenCL &&
10049       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10050       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10051     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10052                                                            << RHSType;
10053     return QualType();
10054   }
10055 
10056 
10057   // If there is a vector type that is not a ExtVector and a scalar, we reach
10058   // this point if scalar could not be converted to the vector's element type
10059   // without truncation.
10060   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10061       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10062     QualType Scalar = LHSVecType ? RHSType : LHSType;
10063     QualType Vector = LHSVecType ? LHSType : RHSType;
10064     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10065     Diag(Loc,
10066          diag::err_typecheck_vector_not_convertable_implict_truncation)
10067         << ScalarOrVector << Scalar << Vector;
10068 
10069     return QualType();
10070   }
10071 
10072   // Otherwise, use the generic diagnostic.
10073   Diag(Loc, DiagID)
10074     << LHSType << RHSType
10075     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10076   return QualType();
10077 }
10078 
10079 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10080 // expression.  These are mainly cases where the null pointer is used as an
10081 // integer instead of a pointer.
10082 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10083                                 SourceLocation Loc, bool IsCompare) {
10084   // The canonical way to check for a GNU null is with isNullPointerConstant,
10085   // but we use a bit of a hack here for speed; this is a relatively
10086   // hot path, and isNullPointerConstant is slow.
10087   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10088   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10089 
10090   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10091 
10092   // Avoid analyzing cases where the result will either be invalid (and
10093   // diagnosed as such) or entirely valid and not something to warn about.
10094   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10095       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10096     return;
10097 
10098   // Comparison operations would not make sense with a null pointer no matter
10099   // what the other expression is.
10100   if (!IsCompare) {
10101     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10102         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10103         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10104     return;
10105   }
10106 
10107   // The rest of the operations only make sense with a null pointer
10108   // if the other expression is a pointer.
10109   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10110       NonNullType->canDecayToPointerType())
10111     return;
10112 
10113   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10114       << LHSNull /* LHS is NULL */ << NonNullType
10115       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10116 }
10117 
10118 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10119                                           SourceLocation Loc) {
10120   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10121   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10122   if (!LUE || !RUE)
10123     return;
10124   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10125       RUE->getKind() != UETT_SizeOf)
10126     return;
10127 
10128   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10129   QualType LHSTy = LHSArg->getType();
10130   QualType RHSTy;
10131 
10132   if (RUE->isArgumentType())
10133     RHSTy = RUE->getArgumentType().getNonReferenceType();
10134   else
10135     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10136 
10137   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10138     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10139       return;
10140 
10141     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10142     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10143       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10144         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10145             << LHSArgDecl;
10146     }
10147   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10148     QualType ArrayElemTy = ArrayTy->getElementType();
10149     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10150         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10151         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10152         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10153       return;
10154     S.Diag(Loc, diag::warn_division_sizeof_array)
10155         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10156     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10157       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10158         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10159             << LHSArgDecl;
10160     }
10161 
10162     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10163   }
10164 }
10165 
10166 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10167                                                ExprResult &RHS,
10168                                                SourceLocation Loc, bool IsDiv) {
10169   // Check for division/remainder by zero.
10170   Expr::EvalResult RHSValue;
10171   if (!RHS.get()->isValueDependent() &&
10172       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10173       RHSValue.Val.getInt() == 0)
10174     S.DiagRuntimeBehavior(Loc, RHS.get(),
10175                           S.PDiag(diag::warn_remainder_division_by_zero)
10176                             << IsDiv << RHS.get()->getSourceRange());
10177 }
10178 
10179 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10180                                            SourceLocation Loc,
10181                                            bool IsCompAssign, bool IsDiv) {
10182   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10183 
10184   if (LHS.get()->getType()->isVectorType() ||
10185       RHS.get()->getType()->isVectorType())
10186     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10187                                /*AllowBothBool*/getLangOpts().AltiVec,
10188                                /*AllowBoolConversions*/false);
10189   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10190                  RHS.get()->getType()->isConstantMatrixType()))
10191     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10192 
10193   QualType compType = UsualArithmeticConversions(
10194       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10195   if (LHS.isInvalid() || RHS.isInvalid())
10196     return QualType();
10197 
10198 
10199   if (compType.isNull() || !compType->isArithmeticType())
10200     return InvalidOperands(Loc, LHS, RHS);
10201   if (IsDiv) {
10202     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10203     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10204   }
10205   return compType;
10206 }
10207 
10208 QualType Sema::CheckRemainderOperands(
10209   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10210   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10211 
10212   if (LHS.get()->getType()->isVectorType() ||
10213       RHS.get()->getType()->isVectorType()) {
10214     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10215         RHS.get()->getType()->hasIntegerRepresentation())
10216       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10217                                  /*AllowBothBool*/getLangOpts().AltiVec,
10218                                  /*AllowBoolConversions*/false);
10219     return InvalidOperands(Loc, LHS, RHS);
10220   }
10221 
10222   QualType compType = UsualArithmeticConversions(
10223       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10224   if (LHS.isInvalid() || RHS.isInvalid())
10225     return QualType();
10226 
10227   if (compType.isNull() || !compType->isIntegerType())
10228     return InvalidOperands(Loc, LHS, RHS);
10229   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10230   return compType;
10231 }
10232 
10233 /// Diagnose invalid arithmetic on two void pointers.
10234 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10235                                                 Expr *LHSExpr, Expr *RHSExpr) {
10236   S.Diag(Loc, S.getLangOpts().CPlusPlus
10237                 ? diag::err_typecheck_pointer_arith_void_type
10238                 : diag::ext_gnu_void_ptr)
10239     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10240                             << RHSExpr->getSourceRange();
10241 }
10242 
10243 /// Diagnose invalid arithmetic on a void pointer.
10244 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10245                                             Expr *Pointer) {
10246   S.Diag(Loc, S.getLangOpts().CPlusPlus
10247                 ? diag::err_typecheck_pointer_arith_void_type
10248                 : diag::ext_gnu_void_ptr)
10249     << 0 /* one pointer */ << Pointer->getSourceRange();
10250 }
10251 
10252 /// Diagnose invalid arithmetic on a null pointer.
10253 ///
10254 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10255 /// idiom, which we recognize as a GNU extension.
10256 ///
10257 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10258                                             Expr *Pointer, bool IsGNUIdiom) {
10259   if (IsGNUIdiom)
10260     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10261       << Pointer->getSourceRange();
10262   else
10263     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10264       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10265 }
10266 
10267 /// Diagnose invalid arithmetic on two function pointers.
10268 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10269                                                     Expr *LHS, Expr *RHS) {
10270   assert(LHS->getType()->isAnyPointerType());
10271   assert(RHS->getType()->isAnyPointerType());
10272   S.Diag(Loc, S.getLangOpts().CPlusPlus
10273                 ? diag::err_typecheck_pointer_arith_function_type
10274                 : diag::ext_gnu_ptr_func_arith)
10275     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10276     // We only show the second type if it differs from the first.
10277     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10278                                                    RHS->getType())
10279     << RHS->getType()->getPointeeType()
10280     << LHS->getSourceRange() << RHS->getSourceRange();
10281 }
10282 
10283 /// Diagnose invalid arithmetic on a function pointer.
10284 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10285                                                 Expr *Pointer) {
10286   assert(Pointer->getType()->isAnyPointerType());
10287   S.Diag(Loc, S.getLangOpts().CPlusPlus
10288                 ? diag::err_typecheck_pointer_arith_function_type
10289                 : diag::ext_gnu_ptr_func_arith)
10290     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10291     << 0 /* one pointer, so only one type */
10292     << Pointer->getSourceRange();
10293 }
10294 
10295 /// Emit error if Operand is incomplete pointer type
10296 ///
10297 /// \returns True if pointer has incomplete type
10298 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10299                                                  Expr *Operand) {
10300   QualType ResType = Operand->getType();
10301   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10302     ResType = ResAtomicType->getValueType();
10303 
10304   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10305   QualType PointeeTy = ResType->getPointeeType();
10306   return S.RequireCompleteSizedType(
10307       Loc, PointeeTy,
10308       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10309       Operand->getSourceRange());
10310 }
10311 
10312 /// Check the validity of an arithmetic pointer operand.
10313 ///
10314 /// If the operand has pointer type, this code will check for pointer types
10315 /// which are invalid in arithmetic operations. These will be diagnosed
10316 /// appropriately, including whether or not the use is supported as an
10317 /// extension.
10318 ///
10319 /// \returns True when the operand is valid to use (even if as an extension).
10320 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10321                                             Expr *Operand) {
10322   QualType ResType = Operand->getType();
10323   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10324     ResType = ResAtomicType->getValueType();
10325 
10326   if (!ResType->isAnyPointerType()) return true;
10327 
10328   QualType PointeeTy = ResType->getPointeeType();
10329   if (PointeeTy->isVoidType()) {
10330     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10331     return !S.getLangOpts().CPlusPlus;
10332   }
10333   if (PointeeTy->isFunctionType()) {
10334     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10335     return !S.getLangOpts().CPlusPlus;
10336   }
10337 
10338   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10339 
10340   return true;
10341 }
10342 
10343 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10344 /// operands.
10345 ///
10346 /// This routine will diagnose any invalid arithmetic on pointer operands much
10347 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10348 /// for emitting a single diagnostic even for operations where both LHS and RHS
10349 /// are (potentially problematic) pointers.
10350 ///
10351 /// \returns True when the operand is valid to use (even if as an extension).
10352 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10353                                                 Expr *LHSExpr, Expr *RHSExpr) {
10354   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10355   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10356   if (!isLHSPointer && !isRHSPointer) return true;
10357 
10358   QualType LHSPointeeTy, RHSPointeeTy;
10359   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10360   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10361 
10362   // if both are pointers check if operation is valid wrt address spaces
10363   if (isLHSPointer && isRHSPointer) {
10364     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10365       S.Diag(Loc,
10366              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10367           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10368           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10369       return false;
10370     }
10371   }
10372 
10373   // Check for arithmetic on pointers to incomplete types.
10374   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10375   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10376   if (isLHSVoidPtr || isRHSVoidPtr) {
10377     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10378     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10379     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10380 
10381     return !S.getLangOpts().CPlusPlus;
10382   }
10383 
10384   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10385   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10386   if (isLHSFuncPtr || isRHSFuncPtr) {
10387     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10388     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10389                                                                 RHSExpr);
10390     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10391 
10392     return !S.getLangOpts().CPlusPlus;
10393   }
10394 
10395   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10396     return false;
10397   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10398     return false;
10399 
10400   return true;
10401 }
10402 
10403 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10404 /// literal.
10405 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10406                                   Expr *LHSExpr, Expr *RHSExpr) {
10407   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10408   Expr* IndexExpr = RHSExpr;
10409   if (!StrExpr) {
10410     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10411     IndexExpr = LHSExpr;
10412   }
10413 
10414   bool IsStringPlusInt = StrExpr &&
10415       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10416   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10417     return;
10418 
10419   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10420   Self.Diag(OpLoc, diag::warn_string_plus_int)
10421       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10422 
10423   // Only print a fixit for "str" + int, not for int + "str".
10424   if (IndexExpr == RHSExpr) {
10425     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10426     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10427         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10428         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10429         << FixItHint::CreateInsertion(EndLoc, "]");
10430   } else
10431     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10432 }
10433 
10434 /// Emit a warning when adding a char literal to a string.
10435 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10436                                    Expr *LHSExpr, Expr *RHSExpr) {
10437   const Expr *StringRefExpr = LHSExpr;
10438   const CharacterLiteral *CharExpr =
10439       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10440 
10441   if (!CharExpr) {
10442     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10443     StringRefExpr = RHSExpr;
10444   }
10445 
10446   if (!CharExpr || !StringRefExpr)
10447     return;
10448 
10449   const QualType StringType = StringRefExpr->getType();
10450 
10451   // Return if not a PointerType.
10452   if (!StringType->isAnyPointerType())
10453     return;
10454 
10455   // Return if not a CharacterType.
10456   if (!StringType->getPointeeType()->isAnyCharacterType())
10457     return;
10458 
10459   ASTContext &Ctx = Self.getASTContext();
10460   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10461 
10462   const QualType CharType = CharExpr->getType();
10463   if (!CharType->isAnyCharacterType() &&
10464       CharType->isIntegerType() &&
10465       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10466     Self.Diag(OpLoc, diag::warn_string_plus_char)
10467         << DiagRange << Ctx.CharTy;
10468   } else {
10469     Self.Diag(OpLoc, diag::warn_string_plus_char)
10470         << DiagRange << CharExpr->getType();
10471   }
10472 
10473   // Only print a fixit for str + char, not for char + str.
10474   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10475     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10476     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10477         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10478         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10479         << FixItHint::CreateInsertion(EndLoc, "]");
10480   } else {
10481     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10482   }
10483 }
10484 
10485 /// Emit error when two pointers are incompatible.
10486 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10487                                            Expr *LHSExpr, Expr *RHSExpr) {
10488   assert(LHSExpr->getType()->isAnyPointerType());
10489   assert(RHSExpr->getType()->isAnyPointerType());
10490   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10491     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10492     << RHSExpr->getSourceRange();
10493 }
10494 
10495 // C99 6.5.6
10496 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10497                                      SourceLocation Loc, BinaryOperatorKind Opc,
10498                                      QualType* CompLHSTy) {
10499   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10500 
10501   if (LHS.get()->getType()->isVectorType() ||
10502       RHS.get()->getType()->isVectorType()) {
10503     QualType compType = CheckVectorOperands(
10504         LHS, RHS, Loc, CompLHSTy,
10505         /*AllowBothBool*/getLangOpts().AltiVec,
10506         /*AllowBoolConversions*/getLangOpts().ZVector);
10507     if (CompLHSTy) *CompLHSTy = compType;
10508     return compType;
10509   }
10510 
10511   if (LHS.get()->getType()->isConstantMatrixType() ||
10512       RHS.get()->getType()->isConstantMatrixType()) {
10513     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10514   }
10515 
10516   QualType compType = UsualArithmeticConversions(
10517       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10518   if (LHS.isInvalid() || RHS.isInvalid())
10519     return QualType();
10520 
10521   // Diagnose "string literal" '+' int and string '+' "char literal".
10522   if (Opc == BO_Add) {
10523     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10524     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10525   }
10526 
10527   // handle the common case first (both operands are arithmetic).
10528   if (!compType.isNull() && compType->isArithmeticType()) {
10529     if (CompLHSTy) *CompLHSTy = compType;
10530     return compType;
10531   }
10532 
10533   // Type-checking.  Ultimately the pointer's going to be in PExp;
10534   // note that we bias towards the LHS being the pointer.
10535   Expr *PExp = LHS.get(), *IExp = RHS.get();
10536 
10537   bool isObjCPointer;
10538   if (PExp->getType()->isPointerType()) {
10539     isObjCPointer = false;
10540   } else if (PExp->getType()->isObjCObjectPointerType()) {
10541     isObjCPointer = true;
10542   } else {
10543     std::swap(PExp, IExp);
10544     if (PExp->getType()->isPointerType()) {
10545       isObjCPointer = false;
10546     } else if (PExp->getType()->isObjCObjectPointerType()) {
10547       isObjCPointer = true;
10548     } else {
10549       return InvalidOperands(Loc, LHS, RHS);
10550     }
10551   }
10552   assert(PExp->getType()->isAnyPointerType());
10553 
10554   if (!IExp->getType()->isIntegerType())
10555     return InvalidOperands(Loc, LHS, RHS);
10556 
10557   // Adding to a null pointer results in undefined behavior.
10558   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10559           Context, Expr::NPC_ValueDependentIsNotNull)) {
10560     // In C++ adding zero to a null pointer is defined.
10561     Expr::EvalResult KnownVal;
10562     if (!getLangOpts().CPlusPlus ||
10563         (!IExp->isValueDependent() &&
10564          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10565           KnownVal.Val.getInt() != 0))) {
10566       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10567       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10568           Context, BO_Add, PExp, IExp);
10569       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10570     }
10571   }
10572 
10573   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10574     return QualType();
10575 
10576   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10577     return QualType();
10578 
10579   // Check array bounds for pointer arithemtic
10580   CheckArrayAccess(PExp, IExp);
10581 
10582   if (CompLHSTy) {
10583     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10584     if (LHSTy.isNull()) {
10585       LHSTy = LHS.get()->getType();
10586       if (LHSTy->isPromotableIntegerType())
10587         LHSTy = Context.getPromotedIntegerType(LHSTy);
10588     }
10589     *CompLHSTy = LHSTy;
10590   }
10591 
10592   return PExp->getType();
10593 }
10594 
10595 // C99 6.5.6
10596 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10597                                         SourceLocation Loc,
10598                                         QualType* CompLHSTy) {
10599   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10600 
10601   if (LHS.get()->getType()->isVectorType() ||
10602       RHS.get()->getType()->isVectorType()) {
10603     QualType compType = CheckVectorOperands(
10604         LHS, RHS, Loc, CompLHSTy,
10605         /*AllowBothBool*/getLangOpts().AltiVec,
10606         /*AllowBoolConversions*/getLangOpts().ZVector);
10607     if (CompLHSTy) *CompLHSTy = compType;
10608     return compType;
10609   }
10610 
10611   if (LHS.get()->getType()->isConstantMatrixType() ||
10612       RHS.get()->getType()->isConstantMatrixType()) {
10613     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10614   }
10615 
10616   QualType compType = UsualArithmeticConversions(
10617       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10618   if (LHS.isInvalid() || RHS.isInvalid())
10619     return QualType();
10620 
10621   // Enforce type constraints: C99 6.5.6p3.
10622 
10623   // Handle the common case first (both operands are arithmetic).
10624   if (!compType.isNull() && compType->isArithmeticType()) {
10625     if (CompLHSTy) *CompLHSTy = compType;
10626     return compType;
10627   }
10628 
10629   // Either ptr - int   or   ptr - ptr.
10630   if (LHS.get()->getType()->isAnyPointerType()) {
10631     QualType lpointee = LHS.get()->getType()->getPointeeType();
10632 
10633     // Diagnose bad cases where we step over interface counts.
10634     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10635         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10636       return QualType();
10637 
10638     // The result type of a pointer-int computation is the pointer type.
10639     if (RHS.get()->getType()->isIntegerType()) {
10640       // Subtracting from a null pointer should produce a warning.
10641       // The last argument to the diagnose call says this doesn't match the
10642       // GNU int-to-pointer idiom.
10643       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10644                                            Expr::NPC_ValueDependentIsNotNull)) {
10645         // In C++ adding zero to a null pointer is defined.
10646         Expr::EvalResult KnownVal;
10647         if (!getLangOpts().CPlusPlus ||
10648             (!RHS.get()->isValueDependent() &&
10649              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10650               KnownVal.Val.getInt() != 0))) {
10651           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10652         }
10653       }
10654 
10655       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10656         return QualType();
10657 
10658       // Check array bounds for pointer arithemtic
10659       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10660                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10661 
10662       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10663       return LHS.get()->getType();
10664     }
10665 
10666     // Handle pointer-pointer subtractions.
10667     if (const PointerType *RHSPTy
10668           = RHS.get()->getType()->getAs<PointerType>()) {
10669       QualType rpointee = RHSPTy->getPointeeType();
10670 
10671       if (getLangOpts().CPlusPlus) {
10672         // Pointee types must be the same: C++ [expr.add]
10673         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10674           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10675         }
10676       } else {
10677         // Pointee types must be compatible C99 6.5.6p3
10678         if (!Context.typesAreCompatible(
10679                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10680                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10681           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10682           return QualType();
10683         }
10684       }
10685 
10686       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10687                                                LHS.get(), RHS.get()))
10688         return QualType();
10689 
10690       // FIXME: Add warnings for nullptr - ptr.
10691 
10692       // The pointee type may have zero size.  As an extension, a structure or
10693       // union may have zero size or an array may have zero length.  In this
10694       // case subtraction does not make sense.
10695       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10696         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10697         if (ElementSize.isZero()) {
10698           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10699             << rpointee.getUnqualifiedType()
10700             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10701         }
10702       }
10703 
10704       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10705       return Context.getPointerDiffType();
10706     }
10707   }
10708 
10709   return InvalidOperands(Loc, LHS, RHS);
10710 }
10711 
10712 static bool isScopedEnumerationType(QualType T) {
10713   if (const EnumType *ET = T->getAs<EnumType>())
10714     return ET->getDecl()->isScoped();
10715   return false;
10716 }
10717 
10718 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10719                                    SourceLocation Loc, BinaryOperatorKind Opc,
10720                                    QualType LHSType) {
10721   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10722   // so skip remaining warnings as we don't want to modify values within Sema.
10723   if (S.getLangOpts().OpenCL)
10724     return;
10725 
10726   // Check right/shifter operand
10727   Expr::EvalResult RHSResult;
10728   if (RHS.get()->isValueDependent() ||
10729       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10730     return;
10731   llvm::APSInt Right = RHSResult.Val.getInt();
10732 
10733   if (Right.isNegative()) {
10734     S.DiagRuntimeBehavior(Loc, RHS.get(),
10735                           S.PDiag(diag::warn_shift_negative)
10736                             << RHS.get()->getSourceRange());
10737     return;
10738   }
10739 
10740   QualType LHSExprType = LHS.get()->getType();
10741   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10742   if (LHSExprType->isExtIntType())
10743     LeftSize = S.Context.getIntWidth(LHSExprType);
10744   else if (LHSExprType->isFixedPointType()) {
10745     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10746     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10747   }
10748   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10749   if (Right.uge(LeftBits)) {
10750     S.DiagRuntimeBehavior(Loc, RHS.get(),
10751                           S.PDiag(diag::warn_shift_gt_typewidth)
10752                             << RHS.get()->getSourceRange());
10753     return;
10754   }
10755 
10756   // FIXME: We probably need to handle fixed point types specially here.
10757   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10758     return;
10759 
10760   // When left shifting an ICE which is signed, we can check for overflow which
10761   // according to C++ standards prior to C++2a has undefined behavior
10762   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10763   // more than the maximum value representable in the result type, so never
10764   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10765   // expression is still probably a bug.)
10766   Expr::EvalResult LHSResult;
10767   if (LHS.get()->isValueDependent() ||
10768       LHSType->hasUnsignedIntegerRepresentation() ||
10769       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10770     return;
10771   llvm::APSInt Left = LHSResult.Val.getInt();
10772 
10773   // If LHS does not have a signed type and non-negative value
10774   // then, the behavior is undefined before C++2a. Warn about it.
10775   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10776       !S.getLangOpts().CPlusPlus20) {
10777     S.DiagRuntimeBehavior(Loc, LHS.get(),
10778                           S.PDiag(diag::warn_shift_lhs_negative)
10779                             << LHS.get()->getSourceRange());
10780     return;
10781   }
10782 
10783   llvm::APInt ResultBits =
10784       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10785   if (LeftBits.uge(ResultBits))
10786     return;
10787   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10788   Result = Result.shl(Right);
10789 
10790   // Print the bit representation of the signed integer as an unsigned
10791   // hexadecimal number.
10792   SmallString<40> HexResult;
10793   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10794 
10795   // If we are only missing a sign bit, this is less likely to result in actual
10796   // bugs -- if the result is cast back to an unsigned type, it will have the
10797   // expected value. Thus we place this behind a different warning that can be
10798   // turned off separately if needed.
10799   if (LeftBits == ResultBits - 1) {
10800     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10801         << HexResult << LHSType
10802         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10803     return;
10804   }
10805 
10806   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10807     << HexResult.str() << Result.getMinSignedBits() << LHSType
10808     << Left.getBitWidth() << LHS.get()->getSourceRange()
10809     << RHS.get()->getSourceRange();
10810 }
10811 
10812 /// Return the resulting type when a vector is shifted
10813 ///        by a scalar or vector shift amount.
10814 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10815                                  SourceLocation Loc, bool IsCompAssign) {
10816   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10817   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10818       !LHS.get()->getType()->isVectorType()) {
10819     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10820       << RHS.get()->getType() << LHS.get()->getType()
10821       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10822     return QualType();
10823   }
10824 
10825   if (!IsCompAssign) {
10826     LHS = S.UsualUnaryConversions(LHS.get());
10827     if (LHS.isInvalid()) return QualType();
10828   }
10829 
10830   RHS = S.UsualUnaryConversions(RHS.get());
10831   if (RHS.isInvalid()) return QualType();
10832 
10833   QualType LHSType = LHS.get()->getType();
10834   // Note that LHS might be a scalar because the routine calls not only in
10835   // OpenCL case.
10836   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10837   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10838 
10839   // Note that RHS might not be a vector.
10840   QualType RHSType = RHS.get()->getType();
10841   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10842   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10843 
10844   // The operands need to be integers.
10845   if (!LHSEleType->isIntegerType()) {
10846     S.Diag(Loc, diag::err_typecheck_expect_int)
10847       << LHS.get()->getType() << LHS.get()->getSourceRange();
10848     return QualType();
10849   }
10850 
10851   if (!RHSEleType->isIntegerType()) {
10852     S.Diag(Loc, diag::err_typecheck_expect_int)
10853       << RHS.get()->getType() << RHS.get()->getSourceRange();
10854     return QualType();
10855   }
10856 
10857   if (!LHSVecTy) {
10858     assert(RHSVecTy);
10859     if (IsCompAssign)
10860       return RHSType;
10861     if (LHSEleType != RHSEleType) {
10862       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10863       LHSEleType = RHSEleType;
10864     }
10865     QualType VecTy =
10866         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10867     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10868     LHSType = VecTy;
10869   } else if (RHSVecTy) {
10870     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10871     // are applied component-wise. So if RHS is a vector, then ensure
10872     // that the number of elements is the same as LHS...
10873     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10874       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10875         << LHS.get()->getType() << RHS.get()->getType()
10876         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10877       return QualType();
10878     }
10879     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10880       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10881       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10882       if (LHSBT != RHSBT &&
10883           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10884         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10885             << LHS.get()->getType() << RHS.get()->getType()
10886             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10887       }
10888     }
10889   } else {
10890     // ...else expand RHS to match the number of elements in LHS.
10891     QualType VecTy =
10892       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10893     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10894   }
10895 
10896   return LHSType;
10897 }
10898 
10899 // C99 6.5.7
10900 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10901                                   SourceLocation Loc, BinaryOperatorKind Opc,
10902                                   bool IsCompAssign) {
10903   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10904 
10905   // Vector shifts promote their scalar inputs to vector type.
10906   if (LHS.get()->getType()->isVectorType() ||
10907       RHS.get()->getType()->isVectorType()) {
10908     if (LangOpts.ZVector) {
10909       // The shift operators for the z vector extensions work basically
10910       // like general shifts, except that neither the LHS nor the RHS is
10911       // allowed to be a "vector bool".
10912       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10913         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10914           return InvalidOperands(Loc, LHS, RHS);
10915       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10916         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10917           return InvalidOperands(Loc, LHS, RHS);
10918     }
10919     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10920   }
10921 
10922   // Shifts don't perform usual arithmetic conversions, they just do integer
10923   // promotions on each operand. C99 6.5.7p3
10924 
10925   // For the LHS, do usual unary conversions, but then reset them away
10926   // if this is a compound assignment.
10927   ExprResult OldLHS = LHS;
10928   LHS = UsualUnaryConversions(LHS.get());
10929   if (LHS.isInvalid())
10930     return QualType();
10931   QualType LHSType = LHS.get()->getType();
10932   if (IsCompAssign) LHS = OldLHS;
10933 
10934   // The RHS is simpler.
10935   RHS = UsualUnaryConversions(RHS.get());
10936   if (RHS.isInvalid())
10937     return QualType();
10938   QualType RHSType = RHS.get()->getType();
10939 
10940   // C99 6.5.7p2: Each of the operands shall have integer type.
10941   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10942   if ((!LHSType->isFixedPointOrIntegerType() &&
10943        !LHSType->hasIntegerRepresentation()) ||
10944       !RHSType->hasIntegerRepresentation())
10945     return InvalidOperands(Loc, LHS, RHS);
10946 
10947   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10948   // hasIntegerRepresentation() above instead of this.
10949   if (isScopedEnumerationType(LHSType) ||
10950       isScopedEnumerationType(RHSType)) {
10951     return InvalidOperands(Loc, LHS, RHS);
10952   }
10953   // Sanity-check shift operands
10954   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10955 
10956   // "The type of the result is that of the promoted left operand."
10957   return LHSType;
10958 }
10959 
10960 /// Diagnose bad pointer comparisons.
10961 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10962                                               ExprResult &LHS, ExprResult &RHS,
10963                                               bool IsError) {
10964   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10965                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10966     << LHS.get()->getType() << RHS.get()->getType()
10967     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10968 }
10969 
10970 /// Returns false if the pointers are converted to a composite type,
10971 /// true otherwise.
10972 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10973                                            ExprResult &LHS, ExprResult &RHS) {
10974   // C++ [expr.rel]p2:
10975   //   [...] Pointer conversions (4.10) and qualification
10976   //   conversions (4.4) are performed on pointer operands (or on
10977   //   a pointer operand and a null pointer constant) to bring
10978   //   them to their composite pointer type. [...]
10979   //
10980   // C++ [expr.eq]p1 uses the same notion for (in)equality
10981   // comparisons of pointers.
10982 
10983   QualType LHSType = LHS.get()->getType();
10984   QualType RHSType = RHS.get()->getType();
10985   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10986          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10987 
10988   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10989   if (T.isNull()) {
10990     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10991         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10992       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10993     else
10994       S.InvalidOperands(Loc, LHS, RHS);
10995     return true;
10996   }
10997 
10998   return false;
10999 }
11000 
11001 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11002                                                     ExprResult &LHS,
11003                                                     ExprResult &RHS,
11004                                                     bool IsError) {
11005   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11006                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11007     << LHS.get()->getType() << RHS.get()->getType()
11008     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11009 }
11010 
11011 static bool isObjCObjectLiteral(ExprResult &E) {
11012   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11013   case Stmt::ObjCArrayLiteralClass:
11014   case Stmt::ObjCDictionaryLiteralClass:
11015   case Stmt::ObjCStringLiteralClass:
11016   case Stmt::ObjCBoxedExprClass:
11017     return true;
11018   default:
11019     // Note that ObjCBoolLiteral is NOT an object literal!
11020     return false;
11021   }
11022 }
11023 
11024 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11025   const ObjCObjectPointerType *Type =
11026     LHS->getType()->getAs<ObjCObjectPointerType>();
11027 
11028   // If this is not actually an Objective-C object, bail out.
11029   if (!Type)
11030     return false;
11031 
11032   // Get the LHS object's interface type.
11033   QualType InterfaceType = Type->getPointeeType();
11034 
11035   // If the RHS isn't an Objective-C object, bail out.
11036   if (!RHS->getType()->isObjCObjectPointerType())
11037     return false;
11038 
11039   // Try to find the -isEqual: method.
11040   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11041   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11042                                                       InterfaceType,
11043                                                       /*IsInstance=*/true);
11044   if (!Method) {
11045     if (Type->isObjCIdType()) {
11046       // For 'id', just check the global pool.
11047       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11048                                                   /*receiverId=*/true);
11049     } else {
11050       // Check protocols.
11051       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11052                                              /*IsInstance=*/true);
11053     }
11054   }
11055 
11056   if (!Method)
11057     return false;
11058 
11059   QualType T = Method->parameters()[0]->getType();
11060   if (!T->isObjCObjectPointerType())
11061     return false;
11062 
11063   QualType R = Method->getReturnType();
11064   if (!R->isScalarType())
11065     return false;
11066 
11067   return true;
11068 }
11069 
11070 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11071   FromE = FromE->IgnoreParenImpCasts();
11072   switch (FromE->getStmtClass()) {
11073     default:
11074       break;
11075     case Stmt::ObjCStringLiteralClass:
11076       // "string literal"
11077       return LK_String;
11078     case Stmt::ObjCArrayLiteralClass:
11079       // "array literal"
11080       return LK_Array;
11081     case Stmt::ObjCDictionaryLiteralClass:
11082       // "dictionary literal"
11083       return LK_Dictionary;
11084     case Stmt::BlockExprClass:
11085       return LK_Block;
11086     case Stmt::ObjCBoxedExprClass: {
11087       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11088       switch (Inner->getStmtClass()) {
11089         case Stmt::IntegerLiteralClass:
11090         case Stmt::FloatingLiteralClass:
11091         case Stmt::CharacterLiteralClass:
11092         case Stmt::ObjCBoolLiteralExprClass:
11093         case Stmt::CXXBoolLiteralExprClass:
11094           // "numeric literal"
11095           return LK_Numeric;
11096         case Stmt::ImplicitCastExprClass: {
11097           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11098           // Boolean literals can be represented by implicit casts.
11099           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11100             return LK_Numeric;
11101           break;
11102         }
11103         default:
11104           break;
11105       }
11106       return LK_Boxed;
11107     }
11108   }
11109   return LK_None;
11110 }
11111 
11112 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11113                                           ExprResult &LHS, ExprResult &RHS,
11114                                           BinaryOperator::Opcode Opc){
11115   Expr *Literal;
11116   Expr *Other;
11117   if (isObjCObjectLiteral(LHS)) {
11118     Literal = LHS.get();
11119     Other = RHS.get();
11120   } else {
11121     Literal = RHS.get();
11122     Other = LHS.get();
11123   }
11124 
11125   // Don't warn on comparisons against nil.
11126   Other = Other->IgnoreParenCasts();
11127   if (Other->isNullPointerConstant(S.getASTContext(),
11128                                    Expr::NPC_ValueDependentIsNotNull))
11129     return;
11130 
11131   // This should be kept in sync with warn_objc_literal_comparison.
11132   // LK_String should always be after the other literals, since it has its own
11133   // warning flag.
11134   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11135   assert(LiteralKind != Sema::LK_Block);
11136   if (LiteralKind == Sema::LK_None) {
11137     llvm_unreachable("Unknown Objective-C object literal kind");
11138   }
11139 
11140   if (LiteralKind == Sema::LK_String)
11141     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11142       << Literal->getSourceRange();
11143   else
11144     S.Diag(Loc, diag::warn_objc_literal_comparison)
11145       << LiteralKind << Literal->getSourceRange();
11146 
11147   if (BinaryOperator::isEqualityOp(Opc) &&
11148       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11149     SourceLocation Start = LHS.get()->getBeginLoc();
11150     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11151     CharSourceRange OpRange =
11152       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11153 
11154     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11155       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11156       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11157       << FixItHint::CreateInsertion(End, "]");
11158   }
11159 }
11160 
11161 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11162 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11163                                            ExprResult &RHS, SourceLocation Loc,
11164                                            BinaryOperatorKind Opc) {
11165   // Check that left hand side is !something.
11166   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11167   if (!UO || UO->getOpcode() != UO_LNot) return;
11168 
11169   // Only check if the right hand side is non-bool arithmetic type.
11170   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11171 
11172   // Make sure that the something in !something is not bool.
11173   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11174   if (SubExpr->isKnownToHaveBooleanValue()) return;
11175 
11176   // Emit warning.
11177   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11178   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11179       << Loc << IsBitwiseOp;
11180 
11181   // First note suggest !(x < y)
11182   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11183   SourceLocation FirstClose = RHS.get()->getEndLoc();
11184   FirstClose = S.getLocForEndOfToken(FirstClose);
11185   if (FirstClose.isInvalid())
11186     FirstOpen = SourceLocation();
11187   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11188       << IsBitwiseOp
11189       << FixItHint::CreateInsertion(FirstOpen, "(")
11190       << FixItHint::CreateInsertion(FirstClose, ")");
11191 
11192   // Second note suggests (!x) < y
11193   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11194   SourceLocation SecondClose = LHS.get()->getEndLoc();
11195   SecondClose = S.getLocForEndOfToken(SecondClose);
11196   if (SecondClose.isInvalid())
11197     SecondOpen = SourceLocation();
11198   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11199       << FixItHint::CreateInsertion(SecondOpen, "(")
11200       << FixItHint::CreateInsertion(SecondClose, ")");
11201 }
11202 
11203 // Returns true if E refers to a non-weak array.
11204 static bool checkForArray(const Expr *E) {
11205   const ValueDecl *D = nullptr;
11206   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11207     D = DR->getDecl();
11208   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11209     if (Mem->isImplicitAccess())
11210       D = Mem->getMemberDecl();
11211   }
11212   if (!D)
11213     return false;
11214   return D->getType()->isArrayType() && !D->isWeak();
11215 }
11216 
11217 /// Diagnose some forms of syntactically-obvious tautological comparison.
11218 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11219                                            Expr *LHS, Expr *RHS,
11220                                            BinaryOperatorKind Opc) {
11221   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11222   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11223 
11224   QualType LHSType = LHS->getType();
11225   QualType RHSType = RHS->getType();
11226   if (LHSType->hasFloatingRepresentation() ||
11227       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11228       S.inTemplateInstantiation())
11229     return;
11230 
11231   // Comparisons between two array types are ill-formed for operator<=>, so
11232   // we shouldn't emit any additional warnings about it.
11233   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11234     return;
11235 
11236   // For non-floating point types, check for self-comparisons of the form
11237   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11238   // often indicate logic errors in the program.
11239   //
11240   // NOTE: Don't warn about comparison expressions resulting from macro
11241   // expansion. Also don't warn about comparisons which are only self
11242   // comparisons within a template instantiation. The warnings should catch
11243   // obvious cases in the definition of the template anyways. The idea is to
11244   // warn when the typed comparison operator will always evaluate to the same
11245   // result.
11246 
11247   // Used for indexing into %select in warn_comparison_always
11248   enum {
11249     AlwaysConstant,
11250     AlwaysTrue,
11251     AlwaysFalse,
11252     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11253   };
11254 
11255   // C++2a [depr.array.comp]:
11256   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11257   //   operands of array type are deprecated.
11258   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11259       RHSStripped->getType()->isArrayType()) {
11260     S.Diag(Loc, diag::warn_depr_array_comparison)
11261         << LHS->getSourceRange() << RHS->getSourceRange()
11262         << LHSStripped->getType() << RHSStripped->getType();
11263     // Carry on to produce the tautological comparison warning, if this
11264     // expression is potentially-evaluated, we can resolve the array to a
11265     // non-weak declaration, and so on.
11266   }
11267 
11268   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11269     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11270       unsigned Result;
11271       switch (Opc) {
11272       case BO_EQ:
11273       case BO_LE:
11274       case BO_GE:
11275         Result = AlwaysTrue;
11276         break;
11277       case BO_NE:
11278       case BO_LT:
11279       case BO_GT:
11280         Result = AlwaysFalse;
11281         break;
11282       case BO_Cmp:
11283         Result = AlwaysEqual;
11284         break;
11285       default:
11286         Result = AlwaysConstant;
11287         break;
11288       }
11289       S.DiagRuntimeBehavior(Loc, nullptr,
11290                             S.PDiag(diag::warn_comparison_always)
11291                                 << 0 /*self-comparison*/
11292                                 << Result);
11293     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11294       // What is it always going to evaluate to?
11295       unsigned Result;
11296       switch (Opc) {
11297       case BO_EQ: // e.g. array1 == array2
11298         Result = AlwaysFalse;
11299         break;
11300       case BO_NE: // e.g. array1 != array2
11301         Result = AlwaysTrue;
11302         break;
11303       default: // e.g. array1 <= array2
11304         // The best we can say is 'a constant'
11305         Result = AlwaysConstant;
11306         break;
11307       }
11308       S.DiagRuntimeBehavior(Loc, nullptr,
11309                             S.PDiag(diag::warn_comparison_always)
11310                                 << 1 /*array comparison*/
11311                                 << Result);
11312     }
11313   }
11314 
11315   if (isa<CastExpr>(LHSStripped))
11316     LHSStripped = LHSStripped->IgnoreParenCasts();
11317   if (isa<CastExpr>(RHSStripped))
11318     RHSStripped = RHSStripped->IgnoreParenCasts();
11319 
11320   // Warn about comparisons against a string constant (unless the other
11321   // operand is null); the user probably wants string comparison function.
11322   Expr *LiteralString = nullptr;
11323   Expr *LiteralStringStripped = nullptr;
11324   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11325       !RHSStripped->isNullPointerConstant(S.Context,
11326                                           Expr::NPC_ValueDependentIsNull)) {
11327     LiteralString = LHS;
11328     LiteralStringStripped = LHSStripped;
11329   } else if ((isa<StringLiteral>(RHSStripped) ||
11330               isa<ObjCEncodeExpr>(RHSStripped)) &&
11331              !LHSStripped->isNullPointerConstant(S.Context,
11332                                           Expr::NPC_ValueDependentIsNull)) {
11333     LiteralString = RHS;
11334     LiteralStringStripped = RHSStripped;
11335   }
11336 
11337   if (LiteralString) {
11338     S.DiagRuntimeBehavior(Loc, nullptr,
11339                           S.PDiag(diag::warn_stringcompare)
11340                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11341                               << LiteralString->getSourceRange());
11342   }
11343 }
11344 
11345 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11346   switch (CK) {
11347   default: {
11348 #ifndef NDEBUG
11349     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11350                  << "\n";
11351 #endif
11352     llvm_unreachable("unhandled cast kind");
11353   }
11354   case CK_UserDefinedConversion:
11355     return ICK_Identity;
11356   case CK_LValueToRValue:
11357     return ICK_Lvalue_To_Rvalue;
11358   case CK_ArrayToPointerDecay:
11359     return ICK_Array_To_Pointer;
11360   case CK_FunctionToPointerDecay:
11361     return ICK_Function_To_Pointer;
11362   case CK_IntegralCast:
11363     return ICK_Integral_Conversion;
11364   case CK_FloatingCast:
11365     return ICK_Floating_Conversion;
11366   case CK_IntegralToFloating:
11367   case CK_FloatingToIntegral:
11368     return ICK_Floating_Integral;
11369   case CK_IntegralComplexCast:
11370   case CK_FloatingComplexCast:
11371   case CK_FloatingComplexToIntegralComplex:
11372   case CK_IntegralComplexToFloatingComplex:
11373     return ICK_Complex_Conversion;
11374   case CK_FloatingComplexToReal:
11375   case CK_FloatingRealToComplex:
11376   case CK_IntegralComplexToReal:
11377   case CK_IntegralRealToComplex:
11378     return ICK_Complex_Real;
11379   }
11380 }
11381 
11382 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11383                                              QualType FromType,
11384                                              SourceLocation Loc) {
11385   // Check for a narrowing implicit conversion.
11386   StandardConversionSequence SCS;
11387   SCS.setAsIdentityConversion();
11388   SCS.setToType(0, FromType);
11389   SCS.setToType(1, ToType);
11390   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11391     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11392 
11393   APValue PreNarrowingValue;
11394   QualType PreNarrowingType;
11395   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11396                                PreNarrowingType,
11397                                /*IgnoreFloatToIntegralConversion*/ true)) {
11398   case NK_Dependent_Narrowing:
11399     // Implicit conversion to a narrower type, but the expression is
11400     // value-dependent so we can't tell whether it's actually narrowing.
11401   case NK_Not_Narrowing:
11402     return false;
11403 
11404   case NK_Constant_Narrowing:
11405     // Implicit conversion to a narrower type, and the value is not a constant
11406     // expression.
11407     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11408         << /*Constant*/ 1
11409         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11410     return true;
11411 
11412   case NK_Variable_Narrowing:
11413     // Implicit conversion to a narrower type, and the value is not a constant
11414     // expression.
11415   case NK_Type_Narrowing:
11416     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11417         << /*Constant*/ 0 << FromType << ToType;
11418     // TODO: It's not a constant expression, but what if the user intended it
11419     // to be? Can we produce notes to help them figure out why it isn't?
11420     return true;
11421   }
11422   llvm_unreachable("unhandled case in switch");
11423 }
11424 
11425 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11426                                                          ExprResult &LHS,
11427                                                          ExprResult &RHS,
11428                                                          SourceLocation Loc) {
11429   QualType LHSType = LHS.get()->getType();
11430   QualType RHSType = RHS.get()->getType();
11431   // Dig out the original argument type and expression before implicit casts
11432   // were applied. These are the types/expressions we need to check the
11433   // [expr.spaceship] requirements against.
11434   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11435   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11436   QualType LHSStrippedType = LHSStripped.get()->getType();
11437   QualType RHSStrippedType = RHSStripped.get()->getType();
11438 
11439   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11440   // other is not, the program is ill-formed.
11441   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11442     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11443     return QualType();
11444   }
11445 
11446   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11447   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11448                     RHSStrippedType->isEnumeralType();
11449   if (NumEnumArgs == 1) {
11450     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11451     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11452     if (OtherTy->hasFloatingRepresentation()) {
11453       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11454       return QualType();
11455     }
11456   }
11457   if (NumEnumArgs == 2) {
11458     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11459     // type E, the operator yields the result of converting the operands
11460     // to the underlying type of E and applying <=> to the converted operands.
11461     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11462       S.InvalidOperands(Loc, LHS, RHS);
11463       return QualType();
11464     }
11465     QualType IntType =
11466         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11467     assert(IntType->isArithmeticType());
11468 
11469     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11470     // promote the boolean type, and all other promotable integer types, to
11471     // avoid this.
11472     if (IntType->isPromotableIntegerType())
11473       IntType = S.Context.getPromotedIntegerType(IntType);
11474 
11475     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11476     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11477     LHSType = RHSType = IntType;
11478   }
11479 
11480   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11481   // usual arithmetic conversions are applied to the operands.
11482   QualType Type =
11483       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11484   if (LHS.isInvalid() || RHS.isInvalid())
11485     return QualType();
11486   if (Type.isNull())
11487     return S.InvalidOperands(Loc, LHS, RHS);
11488 
11489   Optional<ComparisonCategoryType> CCT =
11490       getComparisonCategoryForBuiltinCmp(Type);
11491   if (!CCT)
11492     return S.InvalidOperands(Loc, LHS, RHS);
11493 
11494   bool HasNarrowing = checkThreeWayNarrowingConversion(
11495       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11496   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11497                                                    RHS.get()->getBeginLoc());
11498   if (HasNarrowing)
11499     return QualType();
11500 
11501   assert(!Type.isNull() && "composite type for <=> has not been set");
11502 
11503   return S.CheckComparisonCategoryType(
11504       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11505 }
11506 
11507 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11508                                                  ExprResult &RHS,
11509                                                  SourceLocation Loc,
11510                                                  BinaryOperatorKind Opc) {
11511   if (Opc == BO_Cmp)
11512     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11513 
11514   // C99 6.5.8p3 / C99 6.5.9p4
11515   QualType Type =
11516       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11517   if (LHS.isInvalid() || RHS.isInvalid())
11518     return QualType();
11519   if (Type.isNull())
11520     return S.InvalidOperands(Loc, LHS, RHS);
11521   assert(Type->isArithmeticType() || Type->isEnumeralType());
11522 
11523   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11524     return S.InvalidOperands(Loc, LHS, RHS);
11525 
11526   // Check for comparisons of floating point operands using != and ==.
11527   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11528     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11529 
11530   // The result of comparisons is 'bool' in C++, 'int' in C.
11531   return S.Context.getLogicalOperationType();
11532 }
11533 
11534 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11535   if (!NullE.get()->getType()->isAnyPointerType())
11536     return;
11537   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11538   if (!E.get()->getType()->isAnyPointerType() &&
11539       E.get()->isNullPointerConstant(Context,
11540                                      Expr::NPC_ValueDependentIsNotNull) ==
11541         Expr::NPCK_ZeroExpression) {
11542     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11543       if (CL->getValue() == 0)
11544         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11545             << NullValue
11546             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11547                                             NullValue ? "NULL" : "(void *)0");
11548     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11549         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11550         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11551         if (T == Context.CharTy)
11552           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11553               << NullValue
11554               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11555                                               NullValue ? "NULL" : "(void *)0");
11556       }
11557   }
11558 }
11559 
11560 // C99 6.5.8, C++ [expr.rel]
11561 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11562                                     SourceLocation Loc,
11563                                     BinaryOperatorKind Opc) {
11564   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11565   bool IsThreeWay = Opc == BO_Cmp;
11566   bool IsOrdered = IsRelational || IsThreeWay;
11567   auto IsAnyPointerType = [](ExprResult E) {
11568     QualType Ty = E.get()->getType();
11569     return Ty->isPointerType() || Ty->isMemberPointerType();
11570   };
11571 
11572   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11573   // type, array-to-pointer, ..., conversions are performed on both operands to
11574   // bring them to their composite type.
11575   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11576   // any type-related checks.
11577   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11578     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11579     if (LHS.isInvalid())
11580       return QualType();
11581     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11582     if (RHS.isInvalid())
11583       return QualType();
11584   } else {
11585     LHS = DefaultLvalueConversion(LHS.get());
11586     if (LHS.isInvalid())
11587       return QualType();
11588     RHS = DefaultLvalueConversion(RHS.get());
11589     if (RHS.isInvalid())
11590       return QualType();
11591   }
11592 
11593   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11594   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11595     CheckPtrComparisonWithNullChar(LHS, RHS);
11596     CheckPtrComparisonWithNullChar(RHS, LHS);
11597   }
11598 
11599   // Handle vector comparisons separately.
11600   if (LHS.get()->getType()->isVectorType() ||
11601       RHS.get()->getType()->isVectorType())
11602     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11603 
11604   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11605   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11606 
11607   QualType LHSType = LHS.get()->getType();
11608   QualType RHSType = RHS.get()->getType();
11609   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11610       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11611     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11612 
11613   const Expr::NullPointerConstantKind LHSNullKind =
11614       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11615   const Expr::NullPointerConstantKind RHSNullKind =
11616       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11617   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11618   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11619 
11620   auto computeResultTy = [&]() {
11621     if (Opc != BO_Cmp)
11622       return Context.getLogicalOperationType();
11623     assert(getLangOpts().CPlusPlus);
11624     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11625 
11626     QualType CompositeTy = LHS.get()->getType();
11627     assert(!CompositeTy->isReferenceType());
11628 
11629     Optional<ComparisonCategoryType> CCT =
11630         getComparisonCategoryForBuiltinCmp(CompositeTy);
11631     if (!CCT)
11632       return InvalidOperands(Loc, LHS, RHS);
11633 
11634     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11635       // P0946R0: Comparisons between a null pointer constant and an object
11636       // pointer result in std::strong_equality, which is ill-formed under
11637       // P1959R0.
11638       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11639           << (LHSIsNull ? LHS.get()->getSourceRange()
11640                         : RHS.get()->getSourceRange());
11641       return QualType();
11642     }
11643 
11644     return CheckComparisonCategoryType(
11645         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11646   };
11647 
11648   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11649     bool IsEquality = Opc == BO_EQ;
11650     if (RHSIsNull)
11651       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11652                                    RHS.get()->getSourceRange());
11653     else
11654       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11655                                    LHS.get()->getSourceRange());
11656   }
11657 
11658   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11659       (RHSType->isIntegerType() && !RHSIsNull)) {
11660     // Skip normal pointer conversion checks in this case; we have better
11661     // diagnostics for this below.
11662   } else if (getLangOpts().CPlusPlus) {
11663     // Equality comparison of a function pointer to a void pointer is invalid,
11664     // but we allow it as an extension.
11665     // FIXME: If we really want to allow this, should it be part of composite
11666     // pointer type computation so it works in conditionals too?
11667     if (!IsOrdered &&
11668         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11669          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11670       // This is a gcc extension compatibility comparison.
11671       // In a SFINAE context, we treat this as a hard error to maintain
11672       // conformance with the C++ standard.
11673       diagnoseFunctionPointerToVoidComparison(
11674           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11675 
11676       if (isSFINAEContext())
11677         return QualType();
11678 
11679       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11680       return computeResultTy();
11681     }
11682 
11683     // C++ [expr.eq]p2:
11684     //   If at least one operand is a pointer [...] bring them to their
11685     //   composite pointer type.
11686     // C++ [expr.spaceship]p6
11687     //  If at least one of the operands is of pointer type, [...] bring them
11688     //  to their composite pointer type.
11689     // C++ [expr.rel]p2:
11690     //   If both operands are pointers, [...] bring them to their composite
11691     //   pointer type.
11692     // For <=>, the only valid non-pointer types are arrays and functions, and
11693     // we already decayed those, so this is really the same as the relational
11694     // comparison rule.
11695     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11696             (IsOrdered ? 2 : 1) &&
11697         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11698                                          RHSType->isObjCObjectPointerType()))) {
11699       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11700         return QualType();
11701       return computeResultTy();
11702     }
11703   } else if (LHSType->isPointerType() &&
11704              RHSType->isPointerType()) { // C99 6.5.8p2
11705     // All of the following pointer-related warnings are GCC extensions, except
11706     // when handling null pointer constants.
11707     QualType LCanPointeeTy =
11708       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11709     QualType RCanPointeeTy =
11710       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11711 
11712     // C99 6.5.9p2 and C99 6.5.8p2
11713     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11714                                    RCanPointeeTy.getUnqualifiedType())) {
11715       if (IsRelational) {
11716         // Pointers both need to point to complete or incomplete types
11717         if ((LCanPointeeTy->isIncompleteType() !=
11718              RCanPointeeTy->isIncompleteType()) &&
11719             !getLangOpts().C11) {
11720           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11721               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11722               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11723               << RCanPointeeTy->isIncompleteType();
11724         }
11725         if (LCanPointeeTy->isFunctionType()) {
11726           // Valid unless a relational comparison of function pointers
11727           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11728               << LHSType << RHSType << LHS.get()->getSourceRange()
11729               << RHS.get()->getSourceRange();
11730         }
11731       }
11732     } else if (!IsRelational &&
11733                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11734       // Valid unless comparison between non-null pointer and function pointer
11735       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11736           && !LHSIsNull && !RHSIsNull)
11737         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11738                                                 /*isError*/false);
11739     } else {
11740       // Invalid
11741       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11742     }
11743     if (LCanPointeeTy != RCanPointeeTy) {
11744       // Treat NULL constant as a special case in OpenCL.
11745       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11746         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11747           Diag(Loc,
11748                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11749               << LHSType << RHSType << 0 /* comparison */
11750               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11751         }
11752       }
11753       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11754       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11755       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11756                                                : CK_BitCast;
11757       if (LHSIsNull && !RHSIsNull)
11758         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11759       else
11760         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11761     }
11762     return computeResultTy();
11763   }
11764 
11765   if (getLangOpts().CPlusPlus) {
11766     // C++ [expr.eq]p4:
11767     //   Two operands of type std::nullptr_t or one operand of type
11768     //   std::nullptr_t and the other a null pointer constant compare equal.
11769     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11770       if (LHSType->isNullPtrType()) {
11771         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11772         return computeResultTy();
11773       }
11774       if (RHSType->isNullPtrType()) {
11775         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11776         return computeResultTy();
11777       }
11778     }
11779 
11780     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11781     // These aren't covered by the composite pointer type rules.
11782     if (!IsOrdered && RHSType->isNullPtrType() &&
11783         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11784       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11785       return computeResultTy();
11786     }
11787     if (!IsOrdered && LHSType->isNullPtrType() &&
11788         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11789       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11790       return computeResultTy();
11791     }
11792 
11793     if (IsRelational &&
11794         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11795          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11796       // HACK: Relational comparison of nullptr_t against a pointer type is
11797       // invalid per DR583, but we allow it within std::less<> and friends,
11798       // since otherwise common uses of it break.
11799       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11800       // friends to have std::nullptr_t overload candidates.
11801       DeclContext *DC = CurContext;
11802       if (isa<FunctionDecl>(DC))
11803         DC = DC->getParent();
11804       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11805         if (CTSD->isInStdNamespace() &&
11806             llvm::StringSwitch<bool>(CTSD->getName())
11807                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11808                 .Default(false)) {
11809           if (RHSType->isNullPtrType())
11810             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11811           else
11812             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11813           return computeResultTy();
11814         }
11815       }
11816     }
11817 
11818     // C++ [expr.eq]p2:
11819     //   If at least one operand is a pointer to member, [...] bring them to
11820     //   their composite pointer type.
11821     if (!IsOrdered &&
11822         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11823       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11824         return QualType();
11825       else
11826         return computeResultTy();
11827     }
11828   }
11829 
11830   // Handle block pointer types.
11831   if (!IsOrdered && LHSType->isBlockPointerType() &&
11832       RHSType->isBlockPointerType()) {
11833     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11834     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11835 
11836     if (!LHSIsNull && !RHSIsNull &&
11837         !Context.typesAreCompatible(lpointee, rpointee)) {
11838       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11839         << LHSType << RHSType << LHS.get()->getSourceRange()
11840         << RHS.get()->getSourceRange();
11841     }
11842     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11843     return computeResultTy();
11844   }
11845 
11846   // Allow block pointers to be compared with null pointer constants.
11847   if (!IsOrdered
11848       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11849           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11850     if (!LHSIsNull && !RHSIsNull) {
11851       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11852              ->getPointeeType()->isVoidType())
11853             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11854                 ->getPointeeType()->isVoidType())))
11855         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11856           << LHSType << RHSType << LHS.get()->getSourceRange()
11857           << RHS.get()->getSourceRange();
11858     }
11859     if (LHSIsNull && !RHSIsNull)
11860       LHS = ImpCastExprToType(LHS.get(), RHSType,
11861                               RHSType->isPointerType() ? CK_BitCast
11862                                 : CK_AnyPointerToBlockPointerCast);
11863     else
11864       RHS = ImpCastExprToType(RHS.get(), LHSType,
11865                               LHSType->isPointerType() ? CK_BitCast
11866                                 : CK_AnyPointerToBlockPointerCast);
11867     return computeResultTy();
11868   }
11869 
11870   if (LHSType->isObjCObjectPointerType() ||
11871       RHSType->isObjCObjectPointerType()) {
11872     const PointerType *LPT = LHSType->getAs<PointerType>();
11873     const PointerType *RPT = RHSType->getAs<PointerType>();
11874     if (LPT || RPT) {
11875       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11876       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11877 
11878       if (!LPtrToVoid && !RPtrToVoid &&
11879           !Context.typesAreCompatible(LHSType, RHSType)) {
11880         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11881                                           /*isError*/false);
11882       }
11883       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11884       // the RHS, but we have test coverage for this behavior.
11885       // FIXME: Consider using convertPointersToCompositeType in C++.
11886       if (LHSIsNull && !RHSIsNull) {
11887         Expr *E = LHS.get();
11888         if (getLangOpts().ObjCAutoRefCount)
11889           CheckObjCConversion(SourceRange(), RHSType, E,
11890                               CCK_ImplicitConversion);
11891         LHS = ImpCastExprToType(E, RHSType,
11892                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11893       }
11894       else {
11895         Expr *E = RHS.get();
11896         if (getLangOpts().ObjCAutoRefCount)
11897           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11898                               /*Diagnose=*/true,
11899                               /*DiagnoseCFAudited=*/false, Opc);
11900         RHS = ImpCastExprToType(E, LHSType,
11901                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11902       }
11903       return computeResultTy();
11904     }
11905     if (LHSType->isObjCObjectPointerType() &&
11906         RHSType->isObjCObjectPointerType()) {
11907       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11908         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11909                                           /*isError*/false);
11910       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11911         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11912 
11913       if (LHSIsNull && !RHSIsNull)
11914         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11915       else
11916         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11917       return computeResultTy();
11918     }
11919 
11920     if (!IsOrdered && LHSType->isBlockPointerType() &&
11921         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11922       LHS = ImpCastExprToType(LHS.get(), RHSType,
11923                               CK_BlockPointerToObjCPointerCast);
11924       return computeResultTy();
11925     } else if (!IsOrdered &&
11926                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11927                RHSType->isBlockPointerType()) {
11928       RHS = ImpCastExprToType(RHS.get(), LHSType,
11929                               CK_BlockPointerToObjCPointerCast);
11930       return computeResultTy();
11931     }
11932   }
11933   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11934       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11935     unsigned DiagID = 0;
11936     bool isError = false;
11937     if (LangOpts.DebuggerSupport) {
11938       // Under a debugger, allow the comparison of pointers to integers,
11939       // since users tend to want to compare addresses.
11940     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11941                (RHSIsNull && RHSType->isIntegerType())) {
11942       if (IsOrdered) {
11943         isError = getLangOpts().CPlusPlus;
11944         DiagID =
11945           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11946                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11947       }
11948     } else if (getLangOpts().CPlusPlus) {
11949       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11950       isError = true;
11951     } else if (IsOrdered)
11952       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11953     else
11954       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11955 
11956     if (DiagID) {
11957       Diag(Loc, DiagID)
11958         << LHSType << RHSType << LHS.get()->getSourceRange()
11959         << RHS.get()->getSourceRange();
11960       if (isError)
11961         return QualType();
11962     }
11963 
11964     if (LHSType->isIntegerType())
11965       LHS = ImpCastExprToType(LHS.get(), RHSType,
11966                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11967     else
11968       RHS = ImpCastExprToType(RHS.get(), LHSType,
11969                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11970     return computeResultTy();
11971   }
11972 
11973   // Handle block pointers.
11974   if (!IsOrdered && RHSIsNull
11975       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11976     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11977     return computeResultTy();
11978   }
11979   if (!IsOrdered && LHSIsNull
11980       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11981     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11982     return computeResultTy();
11983   }
11984 
11985   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11986     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11987       return computeResultTy();
11988     }
11989 
11990     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11991       return computeResultTy();
11992     }
11993 
11994     if (LHSIsNull && RHSType->isQueueT()) {
11995       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11996       return computeResultTy();
11997     }
11998 
11999     if (LHSType->isQueueT() && RHSIsNull) {
12000       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12001       return computeResultTy();
12002     }
12003   }
12004 
12005   return InvalidOperands(Loc, LHS, RHS);
12006 }
12007 
12008 // Return a signed ext_vector_type that is of identical size and number of
12009 // elements. For floating point vectors, return an integer type of identical
12010 // size and number of elements. In the non ext_vector_type case, search from
12011 // the largest type to the smallest type to avoid cases where long long == long,
12012 // where long gets picked over long long.
12013 QualType Sema::GetSignedVectorType(QualType V) {
12014   const VectorType *VTy = V->castAs<VectorType>();
12015   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12016 
12017   if (isa<ExtVectorType>(VTy)) {
12018     if (TypeSize == Context.getTypeSize(Context.CharTy))
12019       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12020     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12021       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12022     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12023       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12024     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12025       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12026     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12027            "Unhandled vector element size in vector compare");
12028     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12029   }
12030 
12031   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12032     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12033                                  VectorType::GenericVector);
12034   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12035     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12036                                  VectorType::GenericVector);
12037   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12038     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12039                                  VectorType::GenericVector);
12040   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12041     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12042                                  VectorType::GenericVector);
12043   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12044          "Unhandled vector element size in vector compare");
12045   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12046                                VectorType::GenericVector);
12047 }
12048 
12049 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12050 /// operates on extended vector types.  Instead of producing an IntTy result,
12051 /// like a scalar comparison, a vector comparison produces a vector of integer
12052 /// types.
12053 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12054                                           SourceLocation Loc,
12055                                           BinaryOperatorKind Opc) {
12056   if (Opc == BO_Cmp) {
12057     Diag(Loc, diag::err_three_way_vector_comparison);
12058     return QualType();
12059   }
12060 
12061   // Check to make sure we're operating on vectors of the same type and width,
12062   // Allowing one side to be a scalar of element type.
12063   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12064                               /*AllowBothBool*/true,
12065                               /*AllowBoolConversions*/getLangOpts().ZVector);
12066   if (vType.isNull())
12067     return vType;
12068 
12069   QualType LHSType = LHS.get()->getType();
12070 
12071   // If AltiVec, the comparison results in a numeric type, i.e.
12072   // bool for C++, int for C
12073   if (getLangOpts().AltiVec &&
12074       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12075     return Context.getLogicalOperationType();
12076 
12077   // For non-floating point types, check for self-comparisons of the form
12078   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12079   // often indicate logic errors in the program.
12080   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12081 
12082   // Check for comparisons of floating point operands using != and ==.
12083   if (BinaryOperator::isEqualityOp(Opc) &&
12084       LHSType->hasFloatingRepresentation()) {
12085     assert(RHS.get()->getType()->hasFloatingRepresentation());
12086     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12087   }
12088 
12089   // Return a signed type for the vector.
12090   return GetSignedVectorType(vType);
12091 }
12092 
12093 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12094                                     const ExprResult &XorRHS,
12095                                     const SourceLocation Loc) {
12096   // Do not diagnose macros.
12097   if (Loc.isMacroID())
12098     return;
12099 
12100   bool Negative = false;
12101   bool ExplicitPlus = false;
12102   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12103   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12104 
12105   if (!LHSInt)
12106     return;
12107   if (!RHSInt) {
12108     // Check negative literals.
12109     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12110       UnaryOperatorKind Opc = UO->getOpcode();
12111       if (Opc != UO_Minus && Opc != UO_Plus)
12112         return;
12113       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12114       if (!RHSInt)
12115         return;
12116       Negative = (Opc == UO_Minus);
12117       ExplicitPlus = !Negative;
12118     } else {
12119       return;
12120     }
12121   }
12122 
12123   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12124   llvm::APInt RightSideValue = RHSInt->getValue();
12125   if (LeftSideValue != 2 && LeftSideValue != 10)
12126     return;
12127 
12128   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12129     return;
12130 
12131   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12132       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12133   llvm::StringRef ExprStr =
12134       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12135 
12136   CharSourceRange XorRange =
12137       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12138   llvm::StringRef XorStr =
12139       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12140   // Do not diagnose if xor keyword/macro is used.
12141   if (XorStr == "xor")
12142     return;
12143 
12144   std::string LHSStr = std::string(Lexer::getSourceText(
12145       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12146       S.getSourceManager(), S.getLangOpts()));
12147   std::string RHSStr = std::string(Lexer::getSourceText(
12148       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12149       S.getSourceManager(), S.getLangOpts()));
12150 
12151   if (Negative) {
12152     RightSideValue = -RightSideValue;
12153     RHSStr = "-" + RHSStr;
12154   } else if (ExplicitPlus) {
12155     RHSStr = "+" + RHSStr;
12156   }
12157 
12158   StringRef LHSStrRef = LHSStr;
12159   StringRef RHSStrRef = RHSStr;
12160   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12161   // literals.
12162   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12163       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12164       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12165       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12166       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12167       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12168       LHSStrRef.find('\'') != StringRef::npos ||
12169       RHSStrRef.find('\'') != StringRef::npos)
12170     return;
12171 
12172   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12173   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12174   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12175   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12176     std::string SuggestedExpr = "1 << " + RHSStr;
12177     bool Overflow = false;
12178     llvm::APInt One = (LeftSideValue - 1);
12179     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12180     if (Overflow) {
12181       if (RightSideIntValue < 64)
12182         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12183             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12184             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12185       else if (RightSideIntValue == 64)
12186         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12187       else
12188         return;
12189     } else {
12190       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12191           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12192           << PowValue.toString(10, true)
12193           << FixItHint::CreateReplacement(
12194                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12195     }
12196 
12197     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12198   } else if (LeftSideValue == 10) {
12199     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12200     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12201         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12202         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12203     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12204   }
12205 }
12206 
12207 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12208                                           SourceLocation Loc) {
12209   // Ensure that either both operands are of the same vector type, or
12210   // one operand is of a vector type and the other is of its element type.
12211   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12212                                        /*AllowBothBool*/true,
12213                                        /*AllowBoolConversions*/false);
12214   if (vType.isNull())
12215     return InvalidOperands(Loc, LHS, RHS);
12216   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12217       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12218     return InvalidOperands(Loc, LHS, RHS);
12219   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12220   //        usage of the logical operators && and || with vectors in C. This
12221   //        check could be notionally dropped.
12222   if (!getLangOpts().CPlusPlus &&
12223       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12224     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12225 
12226   return GetSignedVectorType(LHS.get()->getType());
12227 }
12228 
12229 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12230                                               SourceLocation Loc,
12231                                               bool IsCompAssign) {
12232   if (!IsCompAssign) {
12233     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12234     if (LHS.isInvalid())
12235       return QualType();
12236   }
12237   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12238   if (RHS.isInvalid())
12239     return QualType();
12240 
12241   // For conversion purposes, we ignore any qualifiers.
12242   // For example, "const float" and "float" are equivalent.
12243   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12244   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12245 
12246   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12247   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12248   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12249 
12250   if (Context.hasSameType(LHSType, RHSType))
12251     return LHSType;
12252 
12253   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12254   // case we have to return InvalidOperands.
12255   ExprResult OriginalLHS = LHS;
12256   ExprResult OriginalRHS = RHS;
12257   if (LHSMatType && !RHSMatType) {
12258     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12259     if (!RHS.isInvalid())
12260       return LHSType;
12261 
12262     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12263   }
12264 
12265   if (!LHSMatType && RHSMatType) {
12266     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12267     if (!LHS.isInvalid())
12268       return RHSType;
12269     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12270   }
12271 
12272   return InvalidOperands(Loc, LHS, RHS);
12273 }
12274 
12275 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12276                                            SourceLocation Loc,
12277                                            bool IsCompAssign) {
12278   if (!IsCompAssign) {
12279     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12280     if (LHS.isInvalid())
12281       return QualType();
12282   }
12283   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12284   if (RHS.isInvalid())
12285     return QualType();
12286 
12287   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12288   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12289   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12290 
12291   if (LHSMatType && RHSMatType) {
12292     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12293       return InvalidOperands(Loc, LHS, RHS);
12294 
12295     if (!Context.hasSameType(LHSMatType->getElementType(),
12296                              RHSMatType->getElementType()))
12297       return InvalidOperands(Loc, LHS, RHS);
12298 
12299     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12300                                          LHSMatType->getNumRows(),
12301                                          RHSMatType->getNumColumns());
12302   }
12303   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12304 }
12305 
12306 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12307                                            SourceLocation Loc,
12308                                            BinaryOperatorKind Opc) {
12309   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12310 
12311   bool IsCompAssign =
12312       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12313 
12314   if (LHS.get()->getType()->isVectorType() ||
12315       RHS.get()->getType()->isVectorType()) {
12316     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12317         RHS.get()->getType()->hasIntegerRepresentation())
12318       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12319                         /*AllowBothBool*/true,
12320                         /*AllowBoolConversions*/getLangOpts().ZVector);
12321     return InvalidOperands(Loc, LHS, RHS);
12322   }
12323 
12324   if (Opc == BO_And)
12325     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12326 
12327   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12328       RHS.get()->getType()->hasFloatingRepresentation())
12329     return InvalidOperands(Loc, LHS, RHS);
12330 
12331   ExprResult LHSResult = LHS, RHSResult = RHS;
12332   QualType compType = UsualArithmeticConversions(
12333       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12334   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12335     return QualType();
12336   LHS = LHSResult.get();
12337   RHS = RHSResult.get();
12338 
12339   if (Opc == BO_Xor)
12340     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12341 
12342   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12343     return compType;
12344   return InvalidOperands(Loc, LHS, RHS);
12345 }
12346 
12347 // C99 6.5.[13,14]
12348 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12349                                            SourceLocation Loc,
12350                                            BinaryOperatorKind Opc) {
12351   // Check vector operands differently.
12352   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12353     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12354 
12355   bool EnumConstantInBoolContext = false;
12356   for (const ExprResult &HS : {LHS, RHS}) {
12357     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12358       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12359       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12360         EnumConstantInBoolContext = true;
12361     }
12362   }
12363 
12364   if (EnumConstantInBoolContext)
12365     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12366 
12367   // Diagnose cases where the user write a logical and/or but probably meant a
12368   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12369   // is a constant.
12370   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12371       !LHS.get()->getType()->isBooleanType() &&
12372       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12373       // Don't warn in macros or template instantiations.
12374       !Loc.isMacroID() && !inTemplateInstantiation()) {
12375     // If the RHS can be constant folded, and if it constant folds to something
12376     // that isn't 0 or 1 (which indicate a potential logical operation that
12377     // happened to fold to true/false) then warn.
12378     // Parens on the RHS are ignored.
12379     Expr::EvalResult EVResult;
12380     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12381       llvm::APSInt Result = EVResult.Val.getInt();
12382       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12383            !RHS.get()->getExprLoc().isMacroID()) ||
12384           (Result != 0 && Result != 1)) {
12385         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12386           << RHS.get()->getSourceRange()
12387           << (Opc == BO_LAnd ? "&&" : "||");
12388         // Suggest replacing the logical operator with the bitwise version
12389         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12390             << (Opc == BO_LAnd ? "&" : "|")
12391             << FixItHint::CreateReplacement(SourceRange(
12392                                                  Loc, getLocForEndOfToken(Loc)),
12393                                             Opc == BO_LAnd ? "&" : "|");
12394         if (Opc == BO_LAnd)
12395           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12396           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12397               << FixItHint::CreateRemoval(
12398                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12399                                  RHS.get()->getEndLoc()));
12400       }
12401     }
12402   }
12403 
12404   if (!Context.getLangOpts().CPlusPlus) {
12405     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12406     // not operate on the built-in scalar and vector float types.
12407     if (Context.getLangOpts().OpenCL &&
12408         Context.getLangOpts().OpenCLVersion < 120) {
12409       if (LHS.get()->getType()->isFloatingType() ||
12410           RHS.get()->getType()->isFloatingType())
12411         return InvalidOperands(Loc, LHS, RHS);
12412     }
12413 
12414     LHS = UsualUnaryConversions(LHS.get());
12415     if (LHS.isInvalid())
12416       return QualType();
12417 
12418     RHS = UsualUnaryConversions(RHS.get());
12419     if (RHS.isInvalid())
12420       return QualType();
12421 
12422     if (!LHS.get()->getType()->isScalarType() ||
12423         !RHS.get()->getType()->isScalarType())
12424       return InvalidOperands(Loc, LHS, RHS);
12425 
12426     return Context.IntTy;
12427   }
12428 
12429   // The following is safe because we only use this method for
12430   // non-overloadable operands.
12431 
12432   // C++ [expr.log.and]p1
12433   // C++ [expr.log.or]p1
12434   // The operands are both contextually converted to type bool.
12435   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12436   if (LHSRes.isInvalid())
12437     return InvalidOperands(Loc, LHS, RHS);
12438   LHS = LHSRes;
12439 
12440   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12441   if (RHSRes.isInvalid())
12442     return InvalidOperands(Loc, LHS, RHS);
12443   RHS = RHSRes;
12444 
12445   // C++ [expr.log.and]p2
12446   // C++ [expr.log.or]p2
12447   // The result is a bool.
12448   return Context.BoolTy;
12449 }
12450 
12451 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12452   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12453   if (!ME) return false;
12454   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12455   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12456       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12457   if (!Base) return false;
12458   return Base->getMethodDecl() != nullptr;
12459 }
12460 
12461 /// Is the given expression (which must be 'const') a reference to a
12462 /// variable which was originally non-const, but which has become
12463 /// 'const' due to being captured within a block?
12464 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12465 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12466   assert(E->isLValue() && E->getType().isConstQualified());
12467   E = E->IgnoreParens();
12468 
12469   // Must be a reference to a declaration from an enclosing scope.
12470   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12471   if (!DRE) return NCCK_None;
12472   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12473 
12474   // The declaration must be a variable which is not declared 'const'.
12475   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12476   if (!var) return NCCK_None;
12477   if (var->getType().isConstQualified()) return NCCK_None;
12478   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12479 
12480   // Decide whether the first capture was for a block or a lambda.
12481   DeclContext *DC = S.CurContext, *Prev = nullptr;
12482   // Decide whether the first capture was for a block or a lambda.
12483   while (DC) {
12484     // For init-capture, it is possible that the variable belongs to the
12485     // template pattern of the current context.
12486     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12487       if (var->isInitCapture() &&
12488           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12489         break;
12490     if (DC == var->getDeclContext())
12491       break;
12492     Prev = DC;
12493     DC = DC->getParent();
12494   }
12495   // Unless we have an init-capture, we've gone one step too far.
12496   if (!var->isInitCapture())
12497     DC = Prev;
12498   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12499 }
12500 
12501 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12502   Ty = Ty.getNonReferenceType();
12503   if (IsDereference && Ty->isPointerType())
12504     Ty = Ty->getPointeeType();
12505   return !Ty.isConstQualified();
12506 }
12507 
12508 // Update err_typecheck_assign_const and note_typecheck_assign_const
12509 // when this enum is changed.
12510 enum {
12511   ConstFunction,
12512   ConstVariable,
12513   ConstMember,
12514   ConstMethod,
12515   NestedConstMember,
12516   ConstUnknown,  // Keep as last element
12517 };
12518 
12519 /// Emit the "read-only variable not assignable" error and print notes to give
12520 /// more information about why the variable is not assignable, such as pointing
12521 /// to the declaration of a const variable, showing that a method is const, or
12522 /// that the function is returning a const reference.
12523 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12524                                     SourceLocation Loc) {
12525   SourceRange ExprRange = E->getSourceRange();
12526 
12527   // Only emit one error on the first const found.  All other consts will emit
12528   // a note to the error.
12529   bool DiagnosticEmitted = false;
12530 
12531   // Track if the current expression is the result of a dereference, and if the
12532   // next checked expression is the result of a dereference.
12533   bool IsDereference = false;
12534   bool NextIsDereference = false;
12535 
12536   // Loop to process MemberExpr chains.
12537   while (true) {
12538     IsDereference = NextIsDereference;
12539 
12540     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12541     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12542       NextIsDereference = ME->isArrow();
12543       const ValueDecl *VD = ME->getMemberDecl();
12544       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12545         // Mutable fields can be modified even if the class is const.
12546         if (Field->isMutable()) {
12547           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12548           break;
12549         }
12550 
12551         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12552           if (!DiagnosticEmitted) {
12553             S.Diag(Loc, diag::err_typecheck_assign_const)
12554                 << ExprRange << ConstMember << false /*static*/ << Field
12555                 << Field->getType();
12556             DiagnosticEmitted = true;
12557           }
12558           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12559               << ConstMember << false /*static*/ << Field << Field->getType()
12560               << Field->getSourceRange();
12561         }
12562         E = ME->getBase();
12563         continue;
12564       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12565         if (VDecl->getType().isConstQualified()) {
12566           if (!DiagnosticEmitted) {
12567             S.Diag(Loc, diag::err_typecheck_assign_const)
12568                 << ExprRange << ConstMember << true /*static*/ << VDecl
12569                 << VDecl->getType();
12570             DiagnosticEmitted = true;
12571           }
12572           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12573               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12574               << VDecl->getSourceRange();
12575         }
12576         // Static fields do not inherit constness from parents.
12577         break;
12578       }
12579       break; // End MemberExpr
12580     } else if (const ArraySubscriptExpr *ASE =
12581                    dyn_cast<ArraySubscriptExpr>(E)) {
12582       E = ASE->getBase()->IgnoreParenImpCasts();
12583       continue;
12584     } else if (const ExtVectorElementExpr *EVE =
12585                    dyn_cast<ExtVectorElementExpr>(E)) {
12586       E = EVE->getBase()->IgnoreParenImpCasts();
12587       continue;
12588     }
12589     break;
12590   }
12591 
12592   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12593     // Function calls
12594     const FunctionDecl *FD = CE->getDirectCallee();
12595     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12596       if (!DiagnosticEmitted) {
12597         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12598                                                       << ConstFunction << FD;
12599         DiagnosticEmitted = true;
12600       }
12601       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12602              diag::note_typecheck_assign_const)
12603           << ConstFunction << FD << FD->getReturnType()
12604           << FD->getReturnTypeSourceRange();
12605     }
12606   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12607     // Point to variable declaration.
12608     if (const ValueDecl *VD = DRE->getDecl()) {
12609       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12610         if (!DiagnosticEmitted) {
12611           S.Diag(Loc, diag::err_typecheck_assign_const)
12612               << ExprRange << ConstVariable << VD << VD->getType();
12613           DiagnosticEmitted = true;
12614         }
12615         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12616             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12617       }
12618     }
12619   } else if (isa<CXXThisExpr>(E)) {
12620     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12621       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12622         if (MD->isConst()) {
12623           if (!DiagnosticEmitted) {
12624             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12625                                                           << ConstMethod << MD;
12626             DiagnosticEmitted = true;
12627           }
12628           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12629               << ConstMethod << MD << MD->getSourceRange();
12630         }
12631       }
12632     }
12633   }
12634 
12635   if (DiagnosticEmitted)
12636     return;
12637 
12638   // Can't determine a more specific message, so display the generic error.
12639   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12640 }
12641 
12642 enum OriginalExprKind {
12643   OEK_Variable,
12644   OEK_Member,
12645   OEK_LValue
12646 };
12647 
12648 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12649                                          const RecordType *Ty,
12650                                          SourceLocation Loc, SourceRange Range,
12651                                          OriginalExprKind OEK,
12652                                          bool &DiagnosticEmitted) {
12653   std::vector<const RecordType *> RecordTypeList;
12654   RecordTypeList.push_back(Ty);
12655   unsigned NextToCheckIndex = 0;
12656   // We walk the record hierarchy breadth-first to ensure that we print
12657   // diagnostics in field nesting order.
12658   while (RecordTypeList.size() > NextToCheckIndex) {
12659     bool IsNested = NextToCheckIndex > 0;
12660     for (const FieldDecl *Field :
12661          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12662       // First, check every field for constness.
12663       QualType FieldTy = Field->getType();
12664       if (FieldTy.isConstQualified()) {
12665         if (!DiagnosticEmitted) {
12666           S.Diag(Loc, diag::err_typecheck_assign_const)
12667               << Range << NestedConstMember << OEK << VD
12668               << IsNested << Field;
12669           DiagnosticEmitted = true;
12670         }
12671         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12672             << NestedConstMember << IsNested << Field
12673             << FieldTy << Field->getSourceRange();
12674       }
12675 
12676       // Then we append it to the list to check next in order.
12677       FieldTy = FieldTy.getCanonicalType();
12678       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12679         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12680           RecordTypeList.push_back(FieldRecTy);
12681       }
12682     }
12683     ++NextToCheckIndex;
12684   }
12685 }
12686 
12687 /// Emit an error for the case where a record we are trying to assign to has a
12688 /// const-qualified field somewhere in its hierarchy.
12689 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12690                                          SourceLocation Loc) {
12691   QualType Ty = E->getType();
12692   assert(Ty->isRecordType() && "lvalue was not record?");
12693   SourceRange Range = E->getSourceRange();
12694   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12695   bool DiagEmitted = false;
12696 
12697   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12698     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12699             Range, OEK_Member, DiagEmitted);
12700   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12701     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12702             Range, OEK_Variable, DiagEmitted);
12703   else
12704     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12705             Range, OEK_LValue, DiagEmitted);
12706   if (!DiagEmitted)
12707     DiagnoseConstAssignment(S, E, Loc);
12708 }
12709 
12710 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12711 /// emit an error and return true.  If so, return false.
12712 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12713   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12714 
12715   S.CheckShadowingDeclModification(E, Loc);
12716 
12717   SourceLocation OrigLoc = Loc;
12718   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12719                                                               &Loc);
12720   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12721     IsLV = Expr::MLV_InvalidMessageExpression;
12722   if (IsLV == Expr::MLV_Valid)
12723     return false;
12724 
12725   unsigned DiagID = 0;
12726   bool NeedType = false;
12727   switch (IsLV) { // C99 6.5.16p2
12728   case Expr::MLV_ConstQualified:
12729     // Use a specialized diagnostic when we're assigning to an object
12730     // from an enclosing function or block.
12731     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12732       if (NCCK == NCCK_Block)
12733         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12734       else
12735         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12736       break;
12737     }
12738 
12739     // In ARC, use some specialized diagnostics for occasions where we
12740     // infer 'const'.  These are always pseudo-strong variables.
12741     if (S.getLangOpts().ObjCAutoRefCount) {
12742       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12743       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12744         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12745 
12746         // Use the normal diagnostic if it's pseudo-__strong but the
12747         // user actually wrote 'const'.
12748         if (var->isARCPseudoStrong() &&
12749             (!var->getTypeSourceInfo() ||
12750              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12751           // There are three pseudo-strong cases:
12752           //  - self
12753           ObjCMethodDecl *method = S.getCurMethodDecl();
12754           if (method && var == method->getSelfDecl()) {
12755             DiagID = method->isClassMethod()
12756               ? diag::err_typecheck_arc_assign_self_class_method
12757               : diag::err_typecheck_arc_assign_self;
12758 
12759           //  - Objective-C externally_retained attribute.
12760           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12761                      isa<ParmVarDecl>(var)) {
12762             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12763 
12764           //  - fast enumeration variables
12765           } else {
12766             DiagID = diag::err_typecheck_arr_assign_enumeration;
12767           }
12768 
12769           SourceRange Assign;
12770           if (Loc != OrigLoc)
12771             Assign = SourceRange(OrigLoc, OrigLoc);
12772           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12773           // We need to preserve the AST regardless, so migration tool
12774           // can do its job.
12775           return false;
12776         }
12777       }
12778     }
12779 
12780     // If none of the special cases above are triggered, then this is a
12781     // simple const assignment.
12782     if (DiagID == 0) {
12783       DiagnoseConstAssignment(S, E, Loc);
12784       return true;
12785     }
12786 
12787     break;
12788   case Expr::MLV_ConstAddrSpace:
12789     DiagnoseConstAssignment(S, E, Loc);
12790     return true;
12791   case Expr::MLV_ConstQualifiedField:
12792     DiagnoseRecursiveConstFields(S, E, Loc);
12793     return true;
12794   case Expr::MLV_ArrayType:
12795   case Expr::MLV_ArrayTemporary:
12796     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12797     NeedType = true;
12798     break;
12799   case Expr::MLV_NotObjectType:
12800     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12801     NeedType = true;
12802     break;
12803   case Expr::MLV_LValueCast:
12804     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12805     break;
12806   case Expr::MLV_Valid:
12807     llvm_unreachable("did not take early return for MLV_Valid");
12808   case Expr::MLV_InvalidExpression:
12809   case Expr::MLV_MemberFunction:
12810   case Expr::MLV_ClassTemporary:
12811     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12812     break;
12813   case Expr::MLV_IncompleteType:
12814   case Expr::MLV_IncompleteVoidType:
12815     return S.RequireCompleteType(Loc, E->getType(),
12816              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12817   case Expr::MLV_DuplicateVectorComponents:
12818     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12819     break;
12820   case Expr::MLV_NoSetterProperty:
12821     llvm_unreachable("readonly properties should be processed differently");
12822   case Expr::MLV_InvalidMessageExpression:
12823     DiagID = diag::err_readonly_message_assignment;
12824     break;
12825   case Expr::MLV_SubObjCPropertySetting:
12826     DiagID = diag::err_no_subobject_property_setting;
12827     break;
12828   }
12829 
12830   SourceRange Assign;
12831   if (Loc != OrigLoc)
12832     Assign = SourceRange(OrigLoc, OrigLoc);
12833   if (NeedType)
12834     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12835   else
12836     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12837   return true;
12838 }
12839 
12840 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12841                                          SourceLocation Loc,
12842                                          Sema &Sema) {
12843   if (Sema.inTemplateInstantiation())
12844     return;
12845   if (Sema.isUnevaluatedContext())
12846     return;
12847   if (Loc.isInvalid() || Loc.isMacroID())
12848     return;
12849   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12850     return;
12851 
12852   // C / C++ fields
12853   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12854   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12855   if (ML && MR) {
12856     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12857       return;
12858     const ValueDecl *LHSDecl =
12859         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12860     const ValueDecl *RHSDecl =
12861         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12862     if (LHSDecl != RHSDecl)
12863       return;
12864     if (LHSDecl->getType().isVolatileQualified())
12865       return;
12866     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12867       if (RefTy->getPointeeType().isVolatileQualified())
12868         return;
12869 
12870     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12871   }
12872 
12873   // Objective-C instance variables
12874   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12875   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12876   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12877     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12878     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12879     if (RL && RR && RL->getDecl() == RR->getDecl())
12880       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12881   }
12882 }
12883 
12884 // C99 6.5.16.1
12885 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12886                                        SourceLocation Loc,
12887                                        QualType CompoundType) {
12888   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12889 
12890   // Verify that LHS is a modifiable lvalue, and emit error if not.
12891   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12892     return QualType();
12893 
12894   QualType LHSType = LHSExpr->getType();
12895   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12896                                              CompoundType;
12897   // OpenCL v1.2 s6.1.1.1 p2:
12898   // The half data type can only be used to declare a pointer to a buffer that
12899   // contains half values
12900   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12901     LHSType->isHalfType()) {
12902     Diag(Loc, diag::err_opencl_half_load_store) << 1
12903         << LHSType.getUnqualifiedType();
12904     return QualType();
12905   }
12906 
12907   AssignConvertType ConvTy;
12908   if (CompoundType.isNull()) {
12909     Expr *RHSCheck = RHS.get();
12910 
12911     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12912 
12913     QualType LHSTy(LHSType);
12914     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12915     if (RHS.isInvalid())
12916       return QualType();
12917     // Special case of NSObject attributes on c-style pointer types.
12918     if (ConvTy == IncompatiblePointer &&
12919         ((Context.isObjCNSObjectType(LHSType) &&
12920           RHSType->isObjCObjectPointerType()) ||
12921          (Context.isObjCNSObjectType(RHSType) &&
12922           LHSType->isObjCObjectPointerType())))
12923       ConvTy = Compatible;
12924 
12925     if (ConvTy == Compatible &&
12926         LHSType->isObjCObjectType())
12927         Diag(Loc, diag::err_objc_object_assignment)
12928           << LHSType;
12929 
12930     // If the RHS is a unary plus or minus, check to see if they = and + are
12931     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12932     // instead of "x += 4".
12933     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12934       RHSCheck = ICE->getSubExpr();
12935     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12936       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12937           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12938           // Only if the two operators are exactly adjacent.
12939           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12940           // And there is a space or other character before the subexpr of the
12941           // unary +/-.  We don't want to warn on "x=-1".
12942           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12943           UO->getSubExpr()->getBeginLoc().isFileID()) {
12944         Diag(Loc, diag::warn_not_compound_assign)
12945           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12946           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12947       }
12948     }
12949 
12950     if (ConvTy == Compatible) {
12951       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12952         // Warn about retain cycles where a block captures the LHS, but
12953         // not if the LHS is a simple variable into which the block is
12954         // being stored...unless that variable can be captured by reference!
12955         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12956         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12957         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12958           checkRetainCycles(LHSExpr, RHS.get());
12959       }
12960 
12961       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12962           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12963         // It is safe to assign a weak reference into a strong variable.
12964         // Although this code can still have problems:
12965         //   id x = self.weakProp;
12966         //   id y = self.weakProp;
12967         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12968         // paths through the function. This should be revisited if
12969         // -Wrepeated-use-of-weak is made flow-sensitive.
12970         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12971         // variable, which will be valid for the current autorelease scope.
12972         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12973                              RHS.get()->getBeginLoc()))
12974           getCurFunction()->markSafeWeakUse(RHS.get());
12975 
12976       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12977         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12978       }
12979     }
12980   } else {
12981     // Compound assignment "x += y"
12982     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12983   }
12984 
12985   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12986                                RHS.get(), AA_Assigning))
12987     return QualType();
12988 
12989   CheckForNullPointerDereference(*this, LHSExpr);
12990 
12991   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12992     if (CompoundType.isNull()) {
12993       // C++2a [expr.ass]p5:
12994       //   A simple-assignment whose left operand is of a volatile-qualified
12995       //   type is deprecated unless the assignment is either a discarded-value
12996       //   expression or an unevaluated operand
12997       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12998     } else {
12999       // C++2a [expr.ass]p6:
13000       //   [Compound-assignment] expressions are deprecated if E1 has
13001       //   volatile-qualified type
13002       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13003     }
13004   }
13005 
13006   // C99 6.5.16p3: The type of an assignment expression is the type of the
13007   // left operand unless the left operand has qualified type, in which case
13008   // it is the unqualified version of the type of the left operand.
13009   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13010   // is converted to the type of the assignment expression (above).
13011   // C++ 5.17p1: the type of the assignment expression is that of its left
13012   // operand.
13013   return (getLangOpts().CPlusPlus
13014           ? LHSType : LHSType.getUnqualifiedType());
13015 }
13016 
13017 // Only ignore explicit casts to void.
13018 static bool IgnoreCommaOperand(const Expr *E) {
13019   E = E->IgnoreParens();
13020 
13021   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13022     if (CE->getCastKind() == CK_ToVoid) {
13023       return true;
13024     }
13025 
13026     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13027     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13028         CE->getSubExpr()->getType()->isDependentType()) {
13029       return true;
13030     }
13031   }
13032 
13033   return false;
13034 }
13035 
13036 // Look for instances where it is likely the comma operator is confused with
13037 // another operator.  There is an explicit list of acceptable expressions for
13038 // the left hand side of the comma operator, otherwise emit a warning.
13039 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13040   // No warnings in macros
13041   if (Loc.isMacroID())
13042     return;
13043 
13044   // Don't warn in template instantiations.
13045   if (inTemplateInstantiation())
13046     return;
13047 
13048   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13049   // instead, skip more than needed, then call back into here with the
13050   // CommaVisitor in SemaStmt.cpp.
13051   // The listed locations are the initialization and increment portions
13052   // of a for loop.  The additional checks are on the condition of
13053   // if statements, do/while loops, and for loops.
13054   // Differences in scope flags for C89 mode requires the extra logic.
13055   const unsigned ForIncrementFlags =
13056       getLangOpts().C99 || getLangOpts().CPlusPlus
13057           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13058           : Scope::ContinueScope | Scope::BreakScope;
13059   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13060   const unsigned ScopeFlags = getCurScope()->getFlags();
13061   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13062       (ScopeFlags & ForInitFlags) == ForInitFlags)
13063     return;
13064 
13065   // If there are multiple comma operators used together, get the RHS of the
13066   // of the comma operator as the LHS.
13067   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13068     if (BO->getOpcode() != BO_Comma)
13069       break;
13070     LHS = BO->getRHS();
13071   }
13072 
13073   // Only allow some expressions on LHS to not warn.
13074   if (IgnoreCommaOperand(LHS))
13075     return;
13076 
13077   Diag(Loc, diag::warn_comma_operator);
13078   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13079       << LHS->getSourceRange()
13080       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13081                                     LangOpts.CPlusPlus ? "static_cast<void>("
13082                                                        : "(void)(")
13083       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13084                                     ")");
13085 }
13086 
13087 // C99 6.5.17
13088 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13089                                    SourceLocation Loc) {
13090   LHS = S.CheckPlaceholderExpr(LHS.get());
13091   RHS = S.CheckPlaceholderExpr(RHS.get());
13092   if (LHS.isInvalid() || RHS.isInvalid())
13093     return QualType();
13094 
13095   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13096   // operands, but not unary promotions.
13097   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13098 
13099   // So we treat the LHS as a ignored value, and in C++ we allow the
13100   // containing site to determine what should be done with the RHS.
13101   LHS = S.IgnoredValueConversions(LHS.get());
13102   if (LHS.isInvalid())
13103     return QualType();
13104 
13105   S.DiagnoseUnusedExprResult(LHS.get());
13106 
13107   if (!S.getLangOpts().CPlusPlus) {
13108     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13109     if (RHS.isInvalid())
13110       return QualType();
13111     if (!RHS.get()->getType()->isVoidType())
13112       S.RequireCompleteType(Loc, RHS.get()->getType(),
13113                             diag::err_incomplete_type);
13114   }
13115 
13116   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13117     S.DiagnoseCommaOperator(LHS.get(), Loc);
13118 
13119   return RHS.get()->getType();
13120 }
13121 
13122 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13123 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13124 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13125                                                ExprValueKind &VK,
13126                                                ExprObjectKind &OK,
13127                                                SourceLocation OpLoc,
13128                                                bool IsInc, bool IsPrefix) {
13129   if (Op->isTypeDependent())
13130     return S.Context.DependentTy;
13131 
13132   QualType ResType = Op->getType();
13133   // Atomic types can be used for increment / decrement where the non-atomic
13134   // versions can, so ignore the _Atomic() specifier for the purpose of
13135   // checking.
13136   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13137     ResType = ResAtomicType->getValueType();
13138 
13139   assert(!ResType.isNull() && "no type for increment/decrement expression");
13140 
13141   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13142     // Decrement of bool is not allowed.
13143     if (!IsInc) {
13144       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13145       return QualType();
13146     }
13147     // Increment of bool sets it to true, but is deprecated.
13148     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13149                                               : diag::warn_increment_bool)
13150       << Op->getSourceRange();
13151   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13152     // Error on enum increments and decrements in C++ mode
13153     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13154     return QualType();
13155   } else if (ResType->isRealType()) {
13156     // OK!
13157   } else if (ResType->isPointerType()) {
13158     // C99 6.5.2.4p2, 6.5.6p2
13159     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13160       return QualType();
13161   } else if (ResType->isObjCObjectPointerType()) {
13162     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13163     // Otherwise, we just need a complete type.
13164     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13165         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13166       return QualType();
13167   } else if (ResType->isAnyComplexType()) {
13168     // C99 does not support ++/-- on complex types, we allow as an extension.
13169     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13170       << ResType << Op->getSourceRange();
13171   } else if (ResType->isPlaceholderType()) {
13172     ExprResult PR = S.CheckPlaceholderExpr(Op);
13173     if (PR.isInvalid()) return QualType();
13174     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13175                                           IsInc, IsPrefix);
13176   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13177     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13178   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13179              (ResType->castAs<VectorType>()->getVectorKind() !=
13180               VectorType::AltiVecBool)) {
13181     // The z vector extensions allow ++ and -- for non-bool vectors.
13182   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13183             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13184     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13185   } else {
13186     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13187       << ResType << int(IsInc) << Op->getSourceRange();
13188     return QualType();
13189   }
13190   // At this point, we know we have a real, complex or pointer type.
13191   // Now make sure the operand is a modifiable lvalue.
13192   if (CheckForModifiableLvalue(Op, OpLoc, S))
13193     return QualType();
13194   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13195     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13196     //   An operand with volatile-qualified type is deprecated
13197     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13198         << IsInc << ResType;
13199   }
13200   // In C++, a prefix increment is the same type as the operand. Otherwise
13201   // (in C or with postfix), the increment is the unqualified type of the
13202   // operand.
13203   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13204     VK = VK_LValue;
13205     OK = Op->getObjectKind();
13206     return ResType;
13207   } else {
13208     VK = VK_RValue;
13209     return ResType.getUnqualifiedType();
13210   }
13211 }
13212 
13213 
13214 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13215 /// This routine allows us to typecheck complex/recursive expressions
13216 /// where the declaration is needed for type checking. We only need to
13217 /// handle cases when the expression references a function designator
13218 /// or is an lvalue. Here are some examples:
13219 ///  - &(x) => x
13220 ///  - &*****f => f for f a function designator.
13221 ///  - &s.xx => s
13222 ///  - &s.zz[1].yy -> s, if zz is an array
13223 ///  - *(x + 1) -> x, if x is an array
13224 ///  - &"123"[2] -> 0
13225 ///  - & __real__ x -> x
13226 ///
13227 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13228 /// members.
13229 static ValueDecl *getPrimaryDecl(Expr *E) {
13230   switch (E->getStmtClass()) {
13231   case Stmt::DeclRefExprClass:
13232     return cast<DeclRefExpr>(E)->getDecl();
13233   case Stmt::MemberExprClass:
13234     // If this is an arrow operator, the address is an offset from
13235     // the base's value, so the object the base refers to is
13236     // irrelevant.
13237     if (cast<MemberExpr>(E)->isArrow())
13238       return nullptr;
13239     // Otherwise, the expression refers to a part of the base
13240     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13241   case Stmt::ArraySubscriptExprClass: {
13242     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13243     // promotion of register arrays earlier.
13244     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13245     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13246       if (ICE->getSubExpr()->getType()->isArrayType())
13247         return getPrimaryDecl(ICE->getSubExpr());
13248     }
13249     return nullptr;
13250   }
13251   case Stmt::UnaryOperatorClass: {
13252     UnaryOperator *UO = cast<UnaryOperator>(E);
13253 
13254     switch(UO->getOpcode()) {
13255     case UO_Real:
13256     case UO_Imag:
13257     case UO_Extension:
13258       return getPrimaryDecl(UO->getSubExpr());
13259     default:
13260       return nullptr;
13261     }
13262   }
13263   case Stmt::ParenExprClass:
13264     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13265   case Stmt::ImplicitCastExprClass:
13266     // If the result of an implicit cast is an l-value, we care about
13267     // the sub-expression; otherwise, the result here doesn't matter.
13268     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13269   case Stmt::CXXUuidofExprClass:
13270     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13271   default:
13272     return nullptr;
13273   }
13274 }
13275 
13276 namespace {
13277 enum {
13278   AO_Bit_Field = 0,
13279   AO_Vector_Element = 1,
13280   AO_Property_Expansion = 2,
13281   AO_Register_Variable = 3,
13282   AO_Matrix_Element = 4,
13283   AO_No_Error = 5
13284 };
13285 }
13286 /// Diagnose invalid operand for address of operations.
13287 ///
13288 /// \param Type The type of operand which cannot have its address taken.
13289 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13290                                          Expr *E, unsigned Type) {
13291   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13292 }
13293 
13294 /// CheckAddressOfOperand - The operand of & must be either a function
13295 /// designator or an lvalue designating an object. If it is an lvalue, the
13296 /// object cannot be declared with storage class register or be a bit field.
13297 /// Note: The usual conversions are *not* applied to the operand of the &
13298 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13299 /// In C++, the operand might be an overloaded function name, in which case
13300 /// we allow the '&' but retain the overloaded-function type.
13301 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13302   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13303     if (PTy->getKind() == BuiltinType::Overload) {
13304       Expr *E = OrigOp.get()->IgnoreParens();
13305       if (!isa<OverloadExpr>(E)) {
13306         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13307         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13308           << OrigOp.get()->getSourceRange();
13309         return QualType();
13310       }
13311 
13312       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13313       if (isa<UnresolvedMemberExpr>(Ovl))
13314         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13315           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13316             << OrigOp.get()->getSourceRange();
13317           return QualType();
13318         }
13319 
13320       return Context.OverloadTy;
13321     }
13322 
13323     if (PTy->getKind() == BuiltinType::UnknownAny)
13324       return Context.UnknownAnyTy;
13325 
13326     if (PTy->getKind() == BuiltinType::BoundMember) {
13327       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13328         << OrigOp.get()->getSourceRange();
13329       return QualType();
13330     }
13331 
13332     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13333     if (OrigOp.isInvalid()) return QualType();
13334   }
13335 
13336   if (OrigOp.get()->isTypeDependent())
13337     return Context.DependentTy;
13338 
13339   assert(!OrigOp.get()->getType()->isPlaceholderType());
13340 
13341   // Make sure to ignore parentheses in subsequent checks
13342   Expr *op = OrigOp.get()->IgnoreParens();
13343 
13344   // In OpenCL captures for blocks called as lambda functions
13345   // are located in the private address space. Blocks used in
13346   // enqueue_kernel can be located in a different address space
13347   // depending on a vendor implementation. Thus preventing
13348   // taking an address of the capture to avoid invalid AS casts.
13349   if (LangOpts.OpenCL) {
13350     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13351     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13352       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13353       return QualType();
13354     }
13355   }
13356 
13357   if (getLangOpts().C99) {
13358     // Implement C99-only parts of addressof rules.
13359     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13360       if (uOp->getOpcode() == UO_Deref)
13361         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13362         // (assuming the deref expression is valid).
13363         return uOp->getSubExpr()->getType();
13364     }
13365     // Technically, there should be a check for array subscript
13366     // expressions here, but the result of one is always an lvalue anyway.
13367   }
13368   ValueDecl *dcl = getPrimaryDecl(op);
13369 
13370   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13371     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13372                                            op->getBeginLoc()))
13373       return QualType();
13374 
13375   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13376   unsigned AddressOfError = AO_No_Error;
13377 
13378   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13379     bool sfinae = (bool)isSFINAEContext();
13380     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13381                                   : diag::ext_typecheck_addrof_temporary)
13382       << op->getType() << op->getSourceRange();
13383     if (sfinae)
13384       return QualType();
13385     // Materialize the temporary as an lvalue so that we can take its address.
13386     OrigOp = op =
13387         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13388   } else if (isa<ObjCSelectorExpr>(op)) {
13389     return Context.getPointerType(op->getType());
13390   } else if (lval == Expr::LV_MemberFunction) {
13391     // If it's an instance method, make a member pointer.
13392     // The expression must have exactly the form &A::foo.
13393 
13394     // If the underlying expression isn't a decl ref, give up.
13395     if (!isa<DeclRefExpr>(op)) {
13396       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13397         << OrigOp.get()->getSourceRange();
13398       return QualType();
13399     }
13400     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13401     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13402 
13403     // The id-expression was parenthesized.
13404     if (OrigOp.get() != DRE) {
13405       Diag(OpLoc, diag::err_parens_pointer_member_function)
13406         << OrigOp.get()->getSourceRange();
13407 
13408     // The method was named without a qualifier.
13409     } else if (!DRE->getQualifier()) {
13410       if (MD->getParent()->getName().empty())
13411         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13412           << op->getSourceRange();
13413       else {
13414         SmallString<32> Str;
13415         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13416         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13417           << op->getSourceRange()
13418           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13419       }
13420     }
13421 
13422     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13423     if (isa<CXXDestructorDecl>(MD))
13424       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13425 
13426     QualType MPTy = Context.getMemberPointerType(
13427         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13428     // Under the MS ABI, lock down the inheritance model now.
13429     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13430       (void)isCompleteType(OpLoc, MPTy);
13431     return MPTy;
13432   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13433     // C99 6.5.3.2p1
13434     // The operand must be either an l-value or a function designator
13435     if (!op->getType()->isFunctionType()) {
13436       // Use a special diagnostic for loads from property references.
13437       if (isa<PseudoObjectExpr>(op)) {
13438         AddressOfError = AO_Property_Expansion;
13439       } else {
13440         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13441           << op->getType() << op->getSourceRange();
13442         return QualType();
13443       }
13444     }
13445   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13446     // The operand cannot be a bit-field
13447     AddressOfError = AO_Bit_Field;
13448   } else if (op->getObjectKind() == OK_VectorComponent) {
13449     // The operand cannot be an element of a vector
13450     AddressOfError = AO_Vector_Element;
13451   } else if (op->getObjectKind() == OK_MatrixComponent) {
13452     // The operand cannot be an element of a matrix.
13453     AddressOfError = AO_Matrix_Element;
13454   } else if (dcl) { // C99 6.5.3.2p1
13455     // We have an lvalue with a decl. Make sure the decl is not declared
13456     // with the register storage-class specifier.
13457     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13458       // in C++ it is not error to take address of a register
13459       // variable (c++03 7.1.1P3)
13460       if (vd->getStorageClass() == SC_Register &&
13461           !getLangOpts().CPlusPlus) {
13462         AddressOfError = AO_Register_Variable;
13463       }
13464     } else if (isa<MSPropertyDecl>(dcl)) {
13465       AddressOfError = AO_Property_Expansion;
13466     } else if (isa<FunctionTemplateDecl>(dcl)) {
13467       return Context.OverloadTy;
13468     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13469       // Okay: we can take the address of a field.
13470       // Could be a pointer to member, though, if there is an explicit
13471       // scope qualifier for the class.
13472       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13473         DeclContext *Ctx = dcl->getDeclContext();
13474         if (Ctx && Ctx->isRecord()) {
13475           if (dcl->getType()->isReferenceType()) {
13476             Diag(OpLoc,
13477                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13478               << dcl->getDeclName() << dcl->getType();
13479             return QualType();
13480           }
13481 
13482           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13483             Ctx = Ctx->getParent();
13484 
13485           QualType MPTy = Context.getMemberPointerType(
13486               op->getType(),
13487               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13488           // Under the MS ABI, lock down the inheritance model now.
13489           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13490             (void)isCompleteType(OpLoc, MPTy);
13491           return MPTy;
13492         }
13493       }
13494     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13495                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13496       llvm_unreachable("Unknown/unexpected decl type");
13497   }
13498 
13499   if (AddressOfError != AO_No_Error) {
13500     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13501     return QualType();
13502   }
13503 
13504   if (lval == Expr::LV_IncompleteVoidType) {
13505     // Taking the address of a void variable is technically illegal, but we
13506     // allow it in cases which are otherwise valid.
13507     // Example: "extern void x; void* y = &x;".
13508     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13509   }
13510 
13511   // If the operand has type "type", the result has type "pointer to type".
13512   if (op->getType()->isObjCObjectType())
13513     return Context.getObjCObjectPointerType(op->getType());
13514 
13515   CheckAddressOfPackedMember(op);
13516 
13517   return Context.getPointerType(op->getType());
13518 }
13519 
13520 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13521   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13522   if (!DRE)
13523     return;
13524   const Decl *D = DRE->getDecl();
13525   if (!D)
13526     return;
13527   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13528   if (!Param)
13529     return;
13530   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13531     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13532       return;
13533   if (FunctionScopeInfo *FD = S.getCurFunction())
13534     if (!FD->ModifiedNonNullParams.count(Param))
13535       FD->ModifiedNonNullParams.insert(Param);
13536 }
13537 
13538 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13539 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13540                                         SourceLocation OpLoc) {
13541   if (Op->isTypeDependent())
13542     return S.Context.DependentTy;
13543 
13544   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13545   if (ConvResult.isInvalid())
13546     return QualType();
13547   Op = ConvResult.get();
13548   QualType OpTy = Op->getType();
13549   QualType Result;
13550 
13551   if (isa<CXXReinterpretCastExpr>(Op)) {
13552     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13553     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13554                                      Op->getSourceRange());
13555   }
13556 
13557   if (const PointerType *PT = OpTy->getAs<PointerType>())
13558   {
13559     Result = PT->getPointeeType();
13560   }
13561   else if (const ObjCObjectPointerType *OPT =
13562              OpTy->getAs<ObjCObjectPointerType>())
13563     Result = OPT->getPointeeType();
13564   else {
13565     ExprResult PR = S.CheckPlaceholderExpr(Op);
13566     if (PR.isInvalid()) return QualType();
13567     if (PR.get() != Op)
13568       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13569   }
13570 
13571   if (Result.isNull()) {
13572     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13573       << OpTy << Op->getSourceRange();
13574     return QualType();
13575   }
13576 
13577   // Note that per both C89 and C99, indirection is always legal, even if Result
13578   // is an incomplete type or void.  It would be possible to warn about
13579   // dereferencing a void pointer, but it's completely well-defined, and such a
13580   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13581   // for pointers to 'void' but is fine for any other pointer type:
13582   //
13583   // C++ [expr.unary.op]p1:
13584   //   [...] the expression to which [the unary * operator] is applied shall
13585   //   be a pointer to an object type, or a pointer to a function type
13586   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13587     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13588       << OpTy << Op->getSourceRange();
13589 
13590   // Dereferences are usually l-values...
13591   VK = VK_LValue;
13592 
13593   // ...except that certain expressions are never l-values in C.
13594   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13595     VK = VK_RValue;
13596 
13597   return Result;
13598 }
13599 
13600 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13601   BinaryOperatorKind Opc;
13602   switch (Kind) {
13603   default: llvm_unreachable("Unknown binop!");
13604   case tok::periodstar:           Opc = BO_PtrMemD; break;
13605   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13606   case tok::star:                 Opc = BO_Mul; break;
13607   case tok::slash:                Opc = BO_Div; break;
13608   case tok::percent:              Opc = BO_Rem; break;
13609   case tok::plus:                 Opc = BO_Add; break;
13610   case tok::minus:                Opc = BO_Sub; break;
13611   case tok::lessless:             Opc = BO_Shl; break;
13612   case tok::greatergreater:       Opc = BO_Shr; break;
13613   case tok::lessequal:            Opc = BO_LE; break;
13614   case tok::less:                 Opc = BO_LT; break;
13615   case tok::greaterequal:         Opc = BO_GE; break;
13616   case tok::greater:              Opc = BO_GT; break;
13617   case tok::exclaimequal:         Opc = BO_NE; break;
13618   case tok::equalequal:           Opc = BO_EQ; break;
13619   case tok::spaceship:            Opc = BO_Cmp; break;
13620   case tok::amp:                  Opc = BO_And; break;
13621   case tok::caret:                Opc = BO_Xor; break;
13622   case tok::pipe:                 Opc = BO_Or; break;
13623   case tok::ampamp:               Opc = BO_LAnd; break;
13624   case tok::pipepipe:             Opc = BO_LOr; break;
13625   case tok::equal:                Opc = BO_Assign; break;
13626   case tok::starequal:            Opc = BO_MulAssign; break;
13627   case tok::slashequal:           Opc = BO_DivAssign; break;
13628   case tok::percentequal:         Opc = BO_RemAssign; break;
13629   case tok::plusequal:            Opc = BO_AddAssign; break;
13630   case tok::minusequal:           Opc = BO_SubAssign; break;
13631   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13632   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13633   case tok::ampequal:             Opc = BO_AndAssign; break;
13634   case tok::caretequal:           Opc = BO_XorAssign; break;
13635   case tok::pipeequal:            Opc = BO_OrAssign; break;
13636   case tok::comma:                Opc = BO_Comma; break;
13637   }
13638   return Opc;
13639 }
13640 
13641 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13642   tok::TokenKind Kind) {
13643   UnaryOperatorKind Opc;
13644   switch (Kind) {
13645   default: llvm_unreachable("Unknown unary op!");
13646   case tok::plusplus:     Opc = UO_PreInc; break;
13647   case tok::minusminus:   Opc = UO_PreDec; break;
13648   case tok::amp:          Opc = UO_AddrOf; break;
13649   case tok::star:         Opc = UO_Deref; break;
13650   case tok::plus:         Opc = UO_Plus; break;
13651   case tok::minus:        Opc = UO_Minus; break;
13652   case tok::tilde:        Opc = UO_Not; break;
13653   case tok::exclaim:      Opc = UO_LNot; break;
13654   case tok::kw___real:    Opc = UO_Real; break;
13655   case tok::kw___imag:    Opc = UO_Imag; break;
13656   case tok::kw___extension__: Opc = UO_Extension; break;
13657   }
13658   return Opc;
13659 }
13660 
13661 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13662 /// This warning suppressed in the event of macro expansions.
13663 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13664                                    SourceLocation OpLoc, bool IsBuiltin) {
13665   if (S.inTemplateInstantiation())
13666     return;
13667   if (S.isUnevaluatedContext())
13668     return;
13669   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13670     return;
13671   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13672   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13673   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13674   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13675   if (!LHSDeclRef || !RHSDeclRef ||
13676       LHSDeclRef->getLocation().isMacroID() ||
13677       RHSDeclRef->getLocation().isMacroID())
13678     return;
13679   const ValueDecl *LHSDecl =
13680     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13681   const ValueDecl *RHSDecl =
13682     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13683   if (LHSDecl != RHSDecl)
13684     return;
13685   if (LHSDecl->getType().isVolatileQualified())
13686     return;
13687   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13688     if (RefTy->getPointeeType().isVolatileQualified())
13689       return;
13690 
13691   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13692                           : diag::warn_self_assignment_overloaded)
13693       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13694       << RHSExpr->getSourceRange();
13695 }
13696 
13697 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13698 /// is usually indicative of introspection within the Objective-C pointer.
13699 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13700                                           SourceLocation OpLoc) {
13701   if (!S.getLangOpts().ObjC)
13702     return;
13703 
13704   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13705   const Expr *LHS = L.get();
13706   const Expr *RHS = R.get();
13707 
13708   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13709     ObjCPointerExpr = LHS;
13710     OtherExpr = RHS;
13711   }
13712   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13713     ObjCPointerExpr = RHS;
13714     OtherExpr = LHS;
13715   }
13716 
13717   // This warning is deliberately made very specific to reduce false
13718   // positives with logic that uses '&' for hashing.  This logic mainly
13719   // looks for code trying to introspect into tagged pointers, which
13720   // code should generally never do.
13721   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13722     unsigned Diag = diag::warn_objc_pointer_masking;
13723     // Determine if we are introspecting the result of performSelectorXXX.
13724     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13725     // Special case messages to -performSelector and friends, which
13726     // can return non-pointer values boxed in a pointer value.
13727     // Some clients may wish to silence warnings in this subcase.
13728     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13729       Selector S = ME->getSelector();
13730       StringRef SelArg0 = S.getNameForSlot(0);
13731       if (SelArg0.startswith("performSelector"))
13732         Diag = diag::warn_objc_pointer_masking_performSelector;
13733     }
13734 
13735     S.Diag(OpLoc, Diag)
13736       << ObjCPointerExpr->getSourceRange();
13737   }
13738 }
13739 
13740 static NamedDecl *getDeclFromExpr(Expr *E) {
13741   if (!E)
13742     return nullptr;
13743   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13744     return DRE->getDecl();
13745   if (auto *ME = dyn_cast<MemberExpr>(E))
13746     return ME->getMemberDecl();
13747   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13748     return IRE->getDecl();
13749   return nullptr;
13750 }
13751 
13752 // This helper function promotes a binary operator's operands (which are of a
13753 // half vector type) to a vector of floats and then truncates the result to
13754 // a vector of either half or short.
13755 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13756                                       BinaryOperatorKind Opc, QualType ResultTy,
13757                                       ExprValueKind VK, ExprObjectKind OK,
13758                                       bool IsCompAssign, SourceLocation OpLoc,
13759                                       FPOptionsOverride FPFeatures) {
13760   auto &Context = S.getASTContext();
13761   assert((isVector(ResultTy, Context.HalfTy) ||
13762           isVector(ResultTy, Context.ShortTy)) &&
13763          "Result must be a vector of half or short");
13764   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13765          isVector(RHS.get()->getType(), Context.HalfTy) &&
13766          "both operands expected to be a half vector");
13767 
13768   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13769   QualType BinOpResTy = RHS.get()->getType();
13770 
13771   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13772   // change BinOpResTy to a vector of ints.
13773   if (isVector(ResultTy, Context.ShortTy))
13774     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13775 
13776   if (IsCompAssign)
13777     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13778                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13779                                           BinOpResTy, BinOpResTy);
13780 
13781   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13782   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13783                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13784   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13785 }
13786 
13787 static std::pair<ExprResult, ExprResult>
13788 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13789                            Expr *RHSExpr) {
13790   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13791   if (!S.Context.isDependenceAllowed()) {
13792     // C cannot handle TypoExpr nodes on either side of a binop because it
13793     // doesn't handle dependent types properly, so make sure any TypoExprs have
13794     // been dealt with before checking the operands.
13795     LHS = S.CorrectDelayedTyposInExpr(LHS);
13796     RHS = S.CorrectDelayedTyposInExpr(
13797         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13798         [Opc, LHS](Expr *E) {
13799           if (Opc != BO_Assign)
13800             return ExprResult(E);
13801           // Avoid correcting the RHS to the same Expr as the LHS.
13802           Decl *D = getDeclFromExpr(E);
13803           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13804         });
13805   }
13806   return std::make_pair(LHS, RHS);
13807 }
13808 
13809 /// Returns true if conversion between vectors of halfs and vectors of floats
13810 /// is needed.
13811 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13812                                      Expr *E0, Expr *E1 = nullptr) {
13813   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13814       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13815     return false;
13816 
13817   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13818     QualType Ty = E->IgnoreImplicit()->getType();
13819 
13820     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13821     // to vectors of floats. Although the element type of the vectors is __fp16,
13822     // the vectors shouldn't be treated as storage-only types. See the
13823     // discussion here: https://reviews.llvm.org/rG825235c140e7
13824     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13825       if (VT->getVectorKind() == VectorType::NeonVector)
13826         return false;
13827       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13828     }
13829     return false;
13830   };
13831 
13832   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13833 }
13834 
13835 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13836 /// operator @p Opc at location @c TokLoc. This routine only supports
13837 /// built-in operations; ActOnBinOp handles overloaded operators.
13838 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13839                                     BinaryOperatorKind Opc,
13840                                     Expr *LHSExpr, Expr *RHSExpr) {
13841   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13842     // The syntax only allows initializer lists on the RHS of assignment,
13843     // so we don't need to worry about accepting invalid code for
13844     // non-assignment operators.
13845     // C++11 5.17p9:
13846     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13847     //   of x = {} is x = T().
13848     InitializationKind Kind = InitializationKind::CreateDirectList(
13849         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13850     InitializedEntity Entity =
13851         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13852     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13853     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13854     if (Init.isInvalid())
13855       return Init;
13856     RHSExpr = Init.get();
13857   }
13858 
13859   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13860   QualType ResultTy;     // Result type of the binary operator.
13861   // The following two variables are used for compound assignment operators
13862   QualType CompLHSTy;    // Type of LHS after promotions for computation
13863   QualType CompResultTy; // Type of computation result
13864   ExprValueKind VK = VK_RValue;
13865   ExprObjectKind OK = OK_Ordinary;
13866   bool ConvertHalfVec = false;
13867 
13868   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13869   if (!LHS.isUsable() || !RHS.isUsable())
13870     return ExprError();
13871 
13872   if (getLangOpts().OpenCL) {
13873     QualType LHSTy = LHSExpr->getType();
13874     QualType RHSTy = RHSExpr->getType();
13875     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13876     // the ATOMIC_VAR_INIT macro.
13877     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13878       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13879       if (BO_Assign == Opc)
13880         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13881       else
13882         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13883       return ExprError();
13884     }
13885 
13886     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13887     // only with a builtin functions and therefore should be disallowed here.
13888     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13889         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13890         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13891         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13892       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13893       return ExprError();
13894     }
13895   }
13896 
13897   switch (Opc) {
13898   case BO_Assign:
13899     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13900     if (getLangOpts().CPlusPlus &&
13901         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13902       VK = LHS.get()->getValueKind();
13903       OK = LHS.get()->getObjectKind();
13904     }
13905     if (!ResultTy.isNull()) {
13906       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13907       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13908 
13909       // Avoid copying a block to the heap if the block is assigned to a local
13910       // auto variable that is declared in the same scope as the block. This
13911       // optimization is unsafe if the local variable is declared in an outer
13912       // scope. For example:
13913       //
13914       // BlockTy b;
13915       // {
13916       //   b = ^{...};
13917       // }
13918       // // It is unsafe to invoke the block here if it wasn't copied to the
13919       // // heap.
13920       // b();
13921 
13922       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13923         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13924           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13925             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13926               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13927 
13928       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13929         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13930                               NTCUC_Assignment, NTCUK_Copy);
13931     }
13932     RecordModifiableNonNullParam(*this, LHS.get());
13933     break;
13934   case BO_PtrMemD:
13935   case BO_PtrMemI:
13936     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13937                                             Opc == BO_PtrMemI);
13938     break;
13939   case BO_Mul:
13940   case BO_Div:
13941     ConvertHalfVec = true;
13942     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13943                                            Opc == BO_Div);
13944     break;
13945   case BO_Rem:
13946     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13947     break;
13948   case BO_Add:
13949     ConvertHalfVec = true;
13950     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13951     break;
13952   case BO_Sub:
13953     ConvertHalfVec = true;
13954     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13955     break;
13956   case BO_Shl:
13957   case BO_Shr:
13958     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13959     break;
13960   case BO_LE:
13961   case BO_LT:
13962   case BO_GE:
13963   case BO_GT:
13964     ConvertHalfVec = true;
13965     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13966     break;
13967   case BO_EQ:
13968   case BO_NE:
13969     ConvertHalfVec = true;
13970     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13971     break;
13972   case BO_Cmp:
13973     ConvertHalfVec = true;
13974     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13975     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13976     break;
13977   case BO_And:
13978     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13979     LLVM_FALLTHROUGH;
13980   case BO_Xor:
13981   case BO_Or:
13982     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13983     break;
13984   case BO_LAnd:
13985   case BO_LOr:
13986     ConvertHalfVec = true;
13987     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13988     break;
13989   case BO_MulAssign:
13990   case BO_DivAssign:
13991     ConvertHalfVec = true;
13992     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13993                                                Opc == BO_DivAssign);
13994     CompLHSTy = CompResultTy;
13995     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13996       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13997     break;
13998   case BO_RemAssign:
13999     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14000     CompLHSTy = CompResultTy;
14001     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14002       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14003     break;
14004   case BO_AddAssign:
14005     ConvertHalfVec = true;
14006     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14007     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14008       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14009     break;
14010   case BO_SubAssign:
14011     ConvertHalfVec = true;
14012     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14013     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14014       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14015     break;
14016   case BO_ShlAssign:
14017   case BO_ShrAssign:
14018     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14019     CompLHSTy = CompResultTy;
14020     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14021       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14022     break;
14023   case BO_AndAssign:
14024   case BO_OrAssign: // fallthrough
14025     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14026     LLVM_FALLTHROUGH;
14027   case BO_XorAssign:
14028     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14029     CompLHSTy = CompResultTy;
14030     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14031       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14032     break;
14033   case BO_Comma:
14034     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14035     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14036       VK = RHS.get()->getValueKind();
14037       OK = RHS.get()->getObjectKind();
14038     }
14039     break;
14040   }
14041   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14042     return ExprError();
14043 
14044   // Some of the binary operations require promoting operands of half vector to
14045   // float vectors and truncating the result back to half vector. For now, we do
14046   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14047   // arm64).
14048   assert(
14049       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14050                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14051       "both sides are half vectors or neither sides are");
14052   ConvertHalfVec =
14053       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14054 
14055   // Check for array bounds violations for both sides of the BinaryOperator
14056   CheckArrayAccess(LHS.get());
14057   CheckArrayAccess(RHS.get());
14058 
14059   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14060     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14061                                                  &Context.Idents.get("object_setClass"),
14062                                                  SourceLocation(), LookupOrdinaryName);
14063     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14064       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14065       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14066           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14067                                         "object_setClass(")
14068           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14069                                           ",")
14070           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14071     }
14072     else
14073       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14074   }
14075   else if (const ObjCIvarRefExpr *OIRE =
14076            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14077     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14078 
14079   // Opc is not a compound assignment if CompResultTy is null.
14080   if (CompResultTy.isNull()) {
14081     if (ConvertHalfVec)
14082       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14083                                  OpLoc, CurFPFeatureOverrides());
14084     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14085                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14086   }
14087 
14088   // Handle compound assignments.
14089   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14090       OK_ObjCProperty) {
14091     VK = VK_LValue;
14092     OK = LHS.get()->getObjectKind();
14093   }
14094 
14095   // The LHS is not converted to the result type for fixed-point compound
14096   // assignment as the common type is computed on demand. Reset the CompLHSTy
14097   // to the LHS type we would have gotten after unary conversions.
14098   if (CompResultTy->isFixedPointType())
14099     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14100 
14101   if (ConvertHalfVec)
14102     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14103                                OpLoc, CurFPFeatureOverrides());
14104 
14105   return CompoundAssignOperator::Create(
14106       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14107       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14108 }
14109 
14110 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14111 /// operators are mixed in a way that suggests that the programmer forgot that
14112 /// comparison operators have higher precedence. The most typical example of
14113 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14114 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14115                                       SourceLocation OpLoc, Expr *LHSExpr,
14116                                       Expr *RHSExpr) {
14117   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14118   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14119 
14120   // Check that one of the sides is a comparison operator and the other isn't.
14121   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14122   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14123   if (isLeftComp == isRightComp)
14124     return;
14125 
14126   // Bitwise operations are sometimes used as eager logical ops.
14127   // Don't diagnose this.
14128   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14129   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14130   if (isLeftBitwise || isRightBitwise)
14131     return;
14132 
14133   SourceRange DiagRange = isLeftComp
14134                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14135                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14136   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14137   SourceRange ParensRange =
14138       isLeftComp
14139           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14140           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14141 
14142   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14143     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14144   SuggestParentheses(Self, OpLoc,
14145     Self.PDiag(diag::note_precedence_silence) << OpStr,
14146     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14147   SuggestParentheses(Self, OpLoc,
14148     Self.PDiag(diag::note_precedence_bitwise_first)
14149       << BinaryOperator::getOpcodeStr(Opc),
14150     ParensRange);
14151 }
14152 
14153 /// It accepts a '&&' expr that is inside a '||' one.
14154 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14155 /// in parentheses.
14156 static void
14157 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14158                                        BinaryOperator *Bop) {
14159   assert(Bop->getOpcode() == BO_LAnd);
14160   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14161       << Bop->getSourceRange() << OpLoc;
14162   SuggestParentheses(Self, Bop->getOperatorLoc(),
14163     Self.PDiag(diag::note_precedence_silence)
14164       << Bop->getOpcodeStr(),
14165     Bop->getSourceRange());
14166 }
14167 
14168 /// Returns true if the given expression can be evaluated as a constant
14169 /// 'true'.
14170 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14171   bool Res;
14172   return !E->isValueDependent() &&
14173          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14174 }
14175 
14176 /// Returns true if the given expression can be evaluated as a constant
14177 /// 'false'.
14178 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14179   bool Res;
14180   return !E->isValueDependent() &&
14181          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14182 }
14183 
14184 /// Look for '&&' in the left hand of a '||' expr.
14185 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14186                                              Expr *LHSExpr, Expr *RHSExpr) {
14187   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14188     if (Bop->getOpcode() == BO_LAnd) {
14189       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14190       if (EvaluatesAsFalse(S, RHSExpr))
14191         return;
14192       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14193       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14194         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14195     } else if (Bop->getOpcode() == BO_LOr) {
14196       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14197         // If it's "a || b && 1 || c" we didn't warn earlier for
14198         // "a || b && 1", but warn now.
14199         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14200           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14201       }
14202     }
14203   }
14204 }
14205 
14206 /// Look for '&&' in the right hand of a '||' expr.
14207 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14208                                              Expr *LHSExpr, Expr *RHSExpr) {
14209   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14210     if (Bop->getOpcode() == BO_LAnd) {
14211       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14212       if (EvaluatesAsFalse(S, LHSExpr))
14213         return;
14214       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14215       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14216         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14217     }
14218   }
14219 }
14220 
14221 /// Look for bitwise op in the left or right hand of a bitwise op with
14222 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14223 /// the '&' expression in parentheses.
14224 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14225                                          SourceLocation OpLoc, Expr *SubExpr) {
14226   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14227     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14228       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14229         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14230         << Bop->getSourceRange() << OpLoc;
14231       SuggestParentheses(S, Bop->getOperatorLoc(),
14232         S.PDiag(diag::note_precedence_silence)
14233           << Bop->getOpcodeStr(),
14234         Bop->getSourceRange());
14235     }
14236   }
14237 }
14238 
14239 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14240                                     Expr *SubExpr, StringRef Shift) {
14241   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14242     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14243       StringRef Op = Bop->getOpcodeStr();
14244       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14245           << Bop->getSourceRange() << OpLoc << Shift << Op;
14246       SuggestParentheses(S, Bop->getOperatorLoc(),
14247           S.PDiag(diag::note_precedence_silence) << Op,
14248           Bop->getSourceRange());
14249     }
14250   }
14251 }
14252 
14253 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14254                                  Expr *LHSExpr, Expr *RHSExpr) {
14255   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14256   if (!OCE)
14257     return;
14258 
14259   FunctionDecl *FD = OCE->getDirectCallee();
14260   if (!FD || !FD->isOverloadedOperator())
14261     return;
14262 
14263   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14264   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14265     return;
14266 
14267   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14268       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14269       << (Kind == OO_LessLess);
14270   SuggestParentheses(S, OCE->getOperatorLoc(),
14271                      S.PDiag(diag::note_precedence_silence)
14272                          << (Kind == OO_LessLess ? "<<" : ">>"),
14273                      OCE->getSourceRange());
14274   SuggestParentheses(
14275       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14276       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14277 }
14278 
14279 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14280 /// precedence.
14281 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14282                                     SourceLocation OpLoc, Expr *LHSExpr,
14283                                     Expr *RHSExpr){
14284   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14285   if (BinaryOperator::isBitwiseOp(Opc))
14286     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14287 
14288   // Diagnose "arg1 & arg2 | arg3"
14289   if ((Opc == BO_Or || Opc == BO_Xor) &&
14290       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14291     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14292     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14293   }
14294 
14295   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14296   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14297   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14298     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14299     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14300   }
14301 
14302   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14303       || Opc == BO_Shr) {
14304     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14305     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14306     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14307   }
14308 
14309   // Warn on overloaded shift operators and comparisons, such as:
14310   // cout << 5 == 4;
14311   if (BinaryOperator::isComparisonOp(Opc))
14312     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14313 }
14314 
14315 // Binary Operators.  'Tok' is the token for the operator.
14316 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14317                             tok::TokenKind Kind,
14318                             Expr *LHSExpr, Expr *RHSExpr) {
14319   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14320   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14321   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14322 
14323   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14324   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14325 
14326   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14327 }
14328 
14329 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14330                        UnresolvedSetImpl &Functions) {
14331   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14332   if (OverOp != OO_None && OverOp != OO_Equal)
14333     LookupOverloadedOperatorName(OverOp, S, Functions);
14334 
14335   // In C++20 onwards, we may have a second operator to look up.
14336   if (getLangOpts().CPlusPlus20) {
14337     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14338       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14339   }
14340 }
14341 
14342 /// Build an overloaded binary operator expression in the given scope.
14343 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14344                                        BinaryOperatorKind Opc,
14345                                        Expr *LHS, Expr *RHS) {
14346   switch (Opc) {
14347   case BO_Assign:
14348   case BO_DivAssign:
14349   case BO_RemAssign:
14350   case BO_SubAssign:
14351   case BO_AndAssign:
14352   case BO_OrAssign:
14353   case BO_XorAssign:
14354     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14355     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14356     break;
14357   default:
14358     break;
14359   }
14360 
14361   // Find all of the overloaded operators visible from this point.
14362   UnresolvedSet<16> Functions;
14363   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14364 
14365   // Build the (potentially-overloaded, potentially-dependent)
14366   // binary operation.
14367   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14368 }
14369 
14370 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14371                             BinaryOperatorKind Opc,
14372                             Expr *LHSExpr, Expr *RHSExpr) {
14373   ExprResult LHS, RHS;
14374   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14375   if (!LHS.isUsable() || !RHS.isUsable())
14376     return ExprError();
14377   LHSExpr = LHS.get();
14378   RHSExpr = RHS.get();
14379 
14380   // We want to end up calling one of checkPseudoObjectAssignment
14381   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14382   // both expressions are overloadable or either is type-dependent),
14383   // or CreateBuiltinBinOp (in any other case).  We also want to get
14384   // any placeholder types out of the way.
14385 
14386   // Handle pseudo-objects in the LHS.
14387   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14388     // Assignments with a pseudo-object l-value need special analysis.
14389     if (pty->getKind() == BuiltinType::PseudoObject &&
14390         BinaryOperator::isAssignmentOp(Opc))
14391       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14392 
14393     // Don't resolve overloads if the other type is overloadable.
14394     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14395       // We can't actually test that if we still have a placeholder,
14396       // though.  Fortunately, none of the exceptions we see in that
14397       // code below are valid when the LHS is an overload set.  Note
14398       // that an overload set can be dependently-typed, but it never
14399       // instantiates to having an overloadable type.
14400       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14401       if (resolvedRHS.isInvalid()) return ExprError();
14402       RHSExpr = resolvedRHS.get();
14403 
14404       if (RHSExpr->isTypeDependent() ||
14405           RHSExpr->getType()->isOverloadableType())
14406         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14407     }
14408 
14409     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14410     // template, diagnose the missing 'template' keyword instead of diagnosing
14411     // an invalid use of a bound member function.
14412     //
14413     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14414     // to C++1z [over.over]/1.4, but we already checked for that case above.
14415     if (Opc == BO_LT && inTemplateInstantiation() &&
14416         (pty->getKind() == BuiltinType::BoundMember ||
14417          pty->getKind() == BuiltinType::Overload)) {
14418       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14419       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14420           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14421             return isa<FunctionTemplateDecl>(ND);
14422           })) {
14423         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14424                                 : OE->getNameLoc(),
14425              diag::err_template_kw_missing)
14426           << OE->getName().getAsString() << "";
14427         return ExprError();
14428       }
14429     }
14430 
14431     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14432     if (LHS.isInvalid()) return ExprError();
14433     LHSExpr = LHS.get();
14434   }
14435 
14436   // Handle pseudo-objects in the RHS.
14437   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14438     // An overload in the RHS can potentially be resolved by the type
14439     // being assigned to.
14440     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14441       if (getLangOpts().CPlusPlus &&
14442           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14443            LHSExpr->getType()->isOverloadableType()))
14444         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14445 
14446       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14447     }
14448 
14449     // Don't resolve overloads if the other type is overloadable.
14450     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14451         LHSExpr->getType()->isOverloadableType())
14452       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14453 
14454     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14455     if (!resolvedRHS.isUsable()) return ExprError();
14456     RHSExpr = resolvedRHS.get();
14457   }
14458 
14459   if (getLangOpts().CPlusPlus) {
14460     // If either expression is type-dependent, always build an
14461     // overloaded op.
14462     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14463       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14464 
14465     // Otherwise, build an overloaded op if either expression has an
14466     // overloadable type.
14467     if (LHSExpr->getType()->isOverloadableType() ||
14468         RHSExpr->getType()->isOverloadableType())
14469       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14470   }
14471 
14472   if (getLangOpts().RecoveryAST &&
14473       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14474     assert(!getLangOpts().CPlusPlus);
14475     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14476            "Should only occur in error-recovery path.");
14477     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14478       // C [6.15.16] p3:
14479       // An assignment expression has the value of the left operand after the
14480       // assignment, but is not an lvalue.
14481       return CompoundAssignOperator::Create(
14482           Context, LHSExpr, RHSExpr, Opc,
14483           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14484           OpLoc, CurFPFeatureOverrides());
14485     QualType ResultType;
14486     switch (Opc) {
14487     case BO_Assign:
14488       ResultType = LHSExpr->getType().getUnqualifiedType();
14489       break;
14490     case BO_LT:
14491     case BO_GT:
14492     case BO_LE:
14493     case BO_GE:
14494     case BO_EQ:
14495     case BO_NE:
14496     case BO_LAnd:
14497     case BO_LOr:
14498       // These operators have a fixed result type regardless of operands.
14499       ResultType = Context.IntTy;
14500       break;
14501     case BO_Comma:
14502       ResultType = RHSExpr->getType();
14503       break;
14504     default:
14505       ResultType = Context.DependentTy;
14506       break;
14507     }
14508     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14509                                   VK_RValue, OK_Ordinary, OpLoc,
14510                                   CurFPFeatureOverrides());
14511   }
14512 
14513   // Build a built-in binary operation.
14514   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14515 }
14516 
14517 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14518   if (T.isNull() || T->isDependentType())
14519     return false;
14520 
14521   if (!T->isPromotableIntegerType())
14522     return true;
14523 
14524   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14525 }
14526 
14527 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14528                                       UnaryOperatorKind Opc,
14529                                       Expr *InputExpr) {
14530   ExprResult Input = InputExpr;
14531   ExprValueKind VK = VK_RValue;
14532   ExprObjectKind OK = OK_Ordinary;
14533   QualType resultType;
14534   bool CanOverflow = false;
14535 
14536   bool ConvertHalfVec = false;
14537   if (getLangOpts().OpenCL) {
14538     QualType Ty = InputExpr->getType();
14539     // The only legal unary operation for atomics is '&'.
14540     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14541     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14542     // only with a builtin functions and therefore should be disallowed here.
14543         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14544         || Ty->isBlockPointerType())) {
14545       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14546                        << InputExpr->getType()
14547                        << Input.get()->getSourceRange());
14548     }
14549   }
14550 
14551   switch (Opc) {
14552   case UO_PreInc:
14553   case UO_PreDec:
14554   case UO_PostInc:
14555   case UO_PostDec:
14556     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14557                                                 OpLoc,
14558                                                 Opc == UO_PreInc ||
14559                                                 Opc == UO_PostInc,
14560                                                 Opc == UO_PreInc ||
14561                                                 Opc == UO_PreDec);
14562     CanOverflow = isOverflowingIntegerType(Context, resultType);
14563     break;
14564   case UO_AddrOf:
14565     resultType = CheckAddressOfOperand(Input, OpLoc);
14566     CheckAddressOfNoDeref(InputExpr);
14567     RecordModifiableNonNullParam(*this, InputExpr);
14568     break;
14569   case UO_Deref: {
14570     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14571     if (Input.isInvalid()) return ExprError();
14572     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14573     break;
14574   }
14575   case UO_Plus:
14576   case UO_Minus:
14577     CanOverflow = Opc == UO_Minus &&
14578                   isOverflowingIntegerType(Context, Input.get()->getType());
14579     Input = UsualUnaryConversions(Input.get());
14580     if (Input.isInvalid()) return ExprError();
14581     // Unary plus and minus require promoting an operand of half vector to a
14582     // float vector and truncating the result back to a half vector. For now, we
14583     // do this only when HalfArgsAndReturns is set (that is, when the target is
14584     // arm or arm64).
14585     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14586 
14587     // If the operand is a half vector, promote it to a float vector.
14588     if (ConvertHalfVec)
14589       Input = convertVector(Input.get(), Context.FloatTy, *this);
14590     resultType = Input.get()->getType();
14591     if (resultType->isDependentType())
14592       break;
14593     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14594       break;
14595     else if (resultType->isVectorType() &&
14596              // The z vector extensions don't allow + or - with bool vectors.
14597              (!Context.getLangOpts().ZVector ||
14598               resultType->castAs<VectorType>()->getVectorKind() !=
14599               VectorType::AltiVecBool))
14600       break;
14601     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14602              Opc == UO_Plus &&
14603              resultType->isPointerType())
14604       break;
14605 
14606     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14607       << resultType << Input.get()->getSourceRange());
14608 
14609   case UO_Not: // bitwise complement
14610     Input = UsualUnaryConversions(Input.get());
14611     if (Input.isInvalid())
14612       return ExprError();
14613     resultType = Input.get()->getType();
14614     if (resultType->isDependentType())
14615       break;
14616     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14617     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14618       // C99 does not support '~' for complex conjugation.
14619       Diag(OpLoc, diag::ext_integer_complement_complex)
14620           << resultType << Input.get()->getSourceRange();
14621     else if (resultType->hasIntegerRepresentation())
14622       break;
14623     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14624       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14625       // on vector float types.
14626       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14627       if (!T->isIntegerType())
14628         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14629                           << resultType << Input.get()->getSourceRange());
14630     } else {
14631       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14632                        << resultType << Input.get()->getSourceRange());
14633     }
14634     break;
14635 
14636   case UO_LNot: // logical negation
14637     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14638     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14639     if (Input.isInvalid()) return ExprError();
14640     resultType = Input.get()->getType();
14641 
14642     // Though we still have to promote half FP to float...
14643     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14644       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14645       resultType = Context.FloatTy;
14646     }
14647 
14648     if (resultType->isDependentType())
14649       break;
14650     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14651       // C99 6.5.3.3p1: ok, fallthrough;
14652       if (Context.getLangOpts().CPlusPlus) {
14653         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14654         // operand contextually converted to bool.
14655         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14656                                   ScalarTypeToBooleanCastKind(resultType));
14657       } else if (Context.getLangOpts().OpenCL &&
14658                  Context.getLangOpts().OpenCLVersion < 120) {
14659         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14660         // operate on scalar float types.
14661         if (!resultType->isIntegerType() && !resultType->isPointerType())
14662           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14663                            << resultType << Input.get()->getSourceRange());
14664       }
14665     } else if (resultType->isExtVectorType()) {
14666       if (Context.getLangOpts().OpenCL &&
14667           Context.getLangOpts().OpenCLVersion < 120 &&
14668           !Context.getLangOpts().OpenCLCPlusPlus) {
14669         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14670         // operate on vector float types.
14671         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14672         if (!T->isIntegerType())
14673           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14674                            << resultType << Input.get()->getSourceRange());
14675       }
14676       // Vector logical not returns the signed variant of the operand type.
14677       resultType = GetSignedVectorType(resultType);
14678       break;
14679     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14680       const VectorType *VTy = resultType->castAs<VectorType>();
14681       if (VTy->getVectorKind() != VectorType::GenericVector)
14682         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14683                          << resultType << Input.get()->getSourceRange());
14684 
14685       // Vector logical not returns the signed variant of the operand type.
14686       resultType = GetSignedVectorType(resultType);
14687       break;
14688     } else {
14689       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14690         << resultType << Input.get()->getSourceRange());
14691     }
14692 
14693     // LNot always has type int. C99 6.5.3.3p5.
14694     // In C++, it's bool. C++ 5.3.1p8
14695     resultType = Context.getLogicalOperationType();
14696     break;
14697   case UO_Real:
14698   case UO_Imag:
14699     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14700     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14701     // complex l-values to ordinary l-values and all other values to r-values.
14702     if (Input.isInvalid()) return ExprError();
14703     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14704       if (Input.get()->getValueKind() != VK_RValue &&
14705           Input.get()->getObjectKind() == OK_Ordinary)
14706         VK = Input.get()->getValueKind();
14707     } else if (!getLangOpts().CPlusPlus) {
14708       // In C, a volatile scalar is read by __imag. In C++, it is not.
14709       Input = DefaultLvalueConversion(Input.get());
14710     }
14711     break;
14712   case UO_Extension:
14713     resultType = Input.get()->getType();
14714     VK = Input.get()->getValueKind();
14715     OK = Input.get()->getObjectKind();
14716     break;
14717   case UO_Coawait:
14718     // It's unnecessary to represent the pass-through operator co_await in the
14719     // AST; just return the input expression instead.
14720     assert(!Input.get()->getType()->isDependentType() &&
14721                    "the co_await expression must be non-dependant before "
14722                    "building operator co_await");
14723     return Input;
14724   }
14725   if (resultType.isNull() || Input.isInvalid())
14726     return ExprError();
14727 
14728   // Check for array bounds violations in the operand of the UnaryOperator,
14729   // except for the '*' and '&' operators that have to be handled specially
14730   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14731   // that are explicitly defined as valid by the standard).
14732   if (Opc != UO_AddrOf && Opc != UO_Deref)
14733     CheckArrayAccess(Input.get());
14734 
14735   auto *UO =
14736       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14737                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14738 
14739   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14740       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14741       !isUnevaluatedContext())
14742     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14743 
14744   // Convert the result back to a half vector.
14745   if (ConvertHalfVec)
14746     return convertVector(UO, Context.HalfTy, *this);
14747   return UO;
14748 }
14749 
14750 /// Determine whether the given expression is a qualified member
14751 /// access expression, of a form that could be turned into a pointer to member
14752 /// with the address-of operator.
14753 bool Sema::isQualifiedMemberAccess(Expr *E) {
14754   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14755     if (!DRE->getQualifier())
14756       return false;
14757 
14758     ValueDecl *VD = DRE->getDecl();
14759     if (!VD->isCXXClassMember())
14760       return false;
14761 
14762     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14763       return true;
14764     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14765       return Method->isInstance();
14766 
14767     return false;
14768   }
14769 
14770   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14771     if (!ULE->getQualifier())
14772       return false;
14773 
14774     for (NamedDecl *D : ULE->decls()) {
14775       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14776         if (Method->isInstance())
14777           return true;
14778       } else {
14779         // Overload set does not contain methods.
14780         break;
14781       }
14782     }
14783 
14784     return false;
14785   }
14786 
14787   return false;
14788 }
14789 
14790 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14791                               UnaryOperatorKind Opc, Expr *Input) {
14792   // First things first: handle placeholders so that the
14793   // overloaded-operator check considers the right type.
14794   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14795     // Increment and decrement of pseudo-object references.
14796     if (pty->getKind() == BuiltinType::PseudoObject &&
14797         UnaryOperator::isIncrementDecrementOp(Opc))
14798       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14799 
14800     // extension is always a builtin operator.
14801     if (Opc == UO_Extension)
14802       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14803 
14804     // & gets special logic for several kinds of placeholder.
14805     // The builtin code knows what to do.
14806     if (Opc == UO_AddrOf &&
14807         (pty->getKind() == BuiltinType::Overload ||
14808          pty->getKind() == BuiltinType::UnknownAny ||
14809          pty->getKind() == BuiltinType::BoundMember))
14810       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14811 
14812     // Anything else needs to be handled now.
14813     ExprResult Result = CheckPlaceholderExpr(Input);
14814     if (Result.isInvalid()) return ExprError();
14815     Input = Result.get();
14816   }
14817 
14818   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14819       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14820       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14821     // Find all of the overloaded operators visible from this point.
14822     UnresolvedSet<16> Functions;
14823     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14824     if (S && OverOp != OO_None)
14825       LookupOverloadedOperatorName(OverOp, S, Functions);
14826 
14827     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14828   }
14829 
14830   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14831 }
14832 
14833 // Unary Operators.  'Tok' is the token for the operator.
14834 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14835                               tok::TokenKind Op, Expr *Input) {
14836   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14837 }
14838 
14839 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14840 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14841                                 LabelDecl *TheDecl) {
14842   TheDecl->markUsed(Context);
14843   // Create the AST node.  The address of a label always has type 'void*'.
14844   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14845                                      Context.getPointerType(Context.VoidTy));
14846 }
14847 
14848 void Sema::ActOnStartStmtExpr() {
14849   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14850 }
14851 
14852 void Sema::ActOnStmtExprError() {
14853   // Note that function is also called by TreeTransform when leaving a
14854   // StmtExpr scope without rebuilding anything.
14855 
14856   DiscardCleanupsInEvaluationContext();
14857   PopExpressionEvaluationContext();
14858 }
14859 
14860 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14861                                SourceLocation RPLoc) {
14862   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14863 }
14864 
14865 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14866                                SourceLocation RPLoc, unsigned TemplateDepth) {
14867   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14868   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14869 
14870   if (hasAnyUnrecoverableErrorsInThisFunction())
14871     DiscardCleanupsInEvaluationContext();
14872   assert(!Cleanup.exprNeedsCleanups() &&
14873          "cleanups within StmtExpr not correctly bound!");
14874   PopExpressionEvaluationContext();
14875 
14876   // FIXME: there are a variety of strange constraints to enforce here, for
14877   // example, it is not possible to goto into a stmt expression apparently.
14878   // More semantic analysis is needed.
14879 
14880   // If there are sub-stmts in the compound stmt, take the type of the last one
14881   // as the type of the stmtexpr.
14882   QualType Ty = Context.VoidTy;
14883   bool StmtExprMayBindToTemp = false;
14884   if (!Compound->body_empty()) {
14885     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14886     if (const auto *LastStmt =
14887             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14888       if (const Expr *Value = LastStmt->getExprStmt()) {
14889         StmtExprMayBindToTemp = true;
14890         Ty = Value->getType();
14891       }
14892     }
14893   }
14894 
14895   // FIXME: Check that expression type is complete/non-abstract; statement
14896   // expressions are not lvalues.
14897   Expr *ResStmtExpr =
14898       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14899   if (StmtExprMayBindToTemp)
14900     return MaybeBindToTemporary(ResStmtExpr);
14901   return ResStmtExpr;
14902 }
14903 
14904 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14905   if (ER.isInvalid())
14906     return ExprError();
14907 
14908   // Do function/array conversion on the last expression, but not
14909   // lvalue-to-rvalue.  However, initialize an unqualified type.
14910   ER = DefaultFunctionArrayConversion(ER.get());
14911   if (ER.isInvalid())
14912     return ExprError();
14913   Expr *E = ER.get();
14914 
14915   if (E->isTypeDependent())
14916     return E;
14917 
14918   // In ARC, if the final expression ends in a consume, splice
14919   // the consume out and bind it later.  In the alternate case
14920   // (when dealing with a retainable type), the result
14921   // initialization will create a produce.  In both cases the
14922   // result will be +1, and we'll need to balance that out with
14923   // a bind.
14924   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14925   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14926     return Cast->getSubExpr();
14927 
14928   // FIXME: Provide a better location for the initialization.
14929   return PerformCopyInitialization(
14930       InitializedEntity::InitializeStmtExprResult(
14931           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14932       SourceLocation(), E);
14933 }
14934 
14935 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14936                                       TypeSourceInfo *TInfo,
14937                                       ArrayRef<OffsetOfComponent> Components,
14938                                       SourceLocation RParenLoc) {
14939   QualType ArgTy = TInfo->getType();
14940   bool Dependent = ArgTy->isDependentType();
14941   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14942 
14943   // We must have at least one component that refers to the type, and the first
14944   // one is known to be a field designator.  Verify that the ArgTy represents
14945   // a struct/union/class.
14946   if (!Dependent && !ArgTy->isRecordType())
14947     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14948                        << ArgTy << TypeRange);
14949 
14950   // Type must be complete per C99 7.17p3 because a declaring a variable
14951   // with an incomplete type would be ill-formed.
14952   if (!Dependent
14953       && RequireCompleteType(BuiltinLoc, ArgTy,
14954                              diag::err_offsetof_incomplete_type, TypeRange))
14955     return ExprError();
14956 
14957   bool DidWarnAboutNonPOD = false;
14958   QualType CurrentType = ArgTy;
14959   SmallVector<OffsetOfNode, 4> Comps;
14960   SmallVector<Expr*, 4> Exprs;
14961   for (const OffsetOfComponent &OC : Components) {
14962     if (OC.isBrackets) {
14963       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14964       if (!CurrentType->isDependentType()) {
14965         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14966         if(!AT)
14967           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14968                            << CurrentType);
14969         CurrentType = AT->getElementType();
14970       } else
14971         CurrentType = Context.DependentTy;
14972 
14973       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14974       if (IdxRval.isInvalid())
14975         return ExprError();
14976       Expr *Idx = IdxRval.get();
14977 
14978       // The expression must be an integral expression.
14979       // FIXME: An integral constant expression?
14980       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14981           !Idx->getType()->isIntegerType())
14982         return ExprError(
14983             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14984             << Idx->getSourceRange());
14985 
14986       // Record this array index.
14987       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14988       Exprs.push_back(Idx);
14989       continue;
14990     }
14991 
14992     // Offset of a field.
14993     if (CurrentType->isDependentType()) {
14994       // We have the offset of a field, but we can't look into the dependent
14995       // type. Just record the identifier of the field.
14996       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14997       CurrentType = Context.DependentTy;
14998       continue;
14999     }
15000 
15001     // We need to have a complete type to look into.
15002     if (RequireCompleteType(OC.LocStart, CurrentType,
15003                             diag::err_offsetof_incomplete_type))
15004       return ExprError();
15005 
15006     // Look for the designated field.
15007     const RecordType *RC = CurrentType->getAs<RecordType>();
15008     if (!RC)
15009       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15010                        << CurrentType);
15011     RecordDecl *RD = RC->getDecl();
15012 
15013     // C++ [lib.support.types]p5:
15014     //   The macro offsetof accepts a restricted set of type arguments in this
15015     //   International Standard. type shall be a POD structure or a POD union
15016     //   (clause 9).
15017     // C++11 [support.types]p4:
15018     //   If type is not a standard-layout class (Clause 9), the results are
15019     //   undefined.
15020     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15021       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15022       unsigned DiagID =
15023         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15024                             : diag::ext_offsetof_non_pod_type;
15025 
15026       if (!IsSafe && !DidWarnAboutNonPOD &&
15027           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15028                               PDiag(DiagID)
15029                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15030                               << CurrentType))
15031         DidWarnAboutNonPOD = true;
15032     }
15033 
15034     // Look for the field.
15035     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15036     LookupQualifiedName(R, RD);
15037     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15038     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15039     if (!MemberDecl) {
15040       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15041         MemberDecl = IndirectMemberDecl->getAnonField();
15042     }
15043 
15044     if (!MemberDecl)
15045       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15046                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15047                                                               OC.LocEnd));
15048 
15049     // C99 7.17p3:
15050     //   (If the specified member is a bit-field, the behavior is undefined.)
15051     //
15052     // We diagnose this as an error.
15053     if (MemberDecl->isBitField()) {
15054       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15055         << MemberDecl->getDeclName()
15056         << SourceRange(BuiltinLoc, RParenLoc);
15057       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15058       return ExprError();
15059     }
15060 
15061     RecordDecl *Parent = MemberDecl->getParent();
15062     if (IndirectMemberDecl)
15063       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15064 
15065     // If the member was found in a base class, introduce OffsetOfNodes for
15066     // the base class indirections.
15067     CXXBasePaths Paths;
15068     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15069                       Paths)) {
15070       if (Paths.getDetectedVirtual()) {
15071         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15072           << MemberDecl->getDeclName()
15073           << SourceRange(BuiltinLoc, RParenLoc);
15074         return ExprError();
15075       }
15076 
15077       CXXBasePath &Path = Paths.front();
15078       for (const CXXBasePathElement &B : Path)
15079         Comps.push_back(OffsetOfNode(B.Base));
15080     }
15081 
15082     if (IndirectMemberDecl) {
15083       for (auto *FI : IndirectMemberDecl->chain()) {
15084         assert(isa<FieldDecl>(FI));
15085         Comps.push_back(OffsetOfNode(OC.LocStart,
15086                                      cast<FieldDecl>(FI), OC.LocEnd));
15087       }
15088     } else
15089       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15090 
15091     CurrentType = MemberDecl->getType().getNonReferenceType();
15092   }
15093 
15094   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15095                               Comps, Exprs, RParenLoc);
15096 }
15097 
15098 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15099                                       SourceLocation BuiltinLoc,
15100                                       SourceLocation TypeLoc,
15101                                       ParsedType ParsedArgTy,
15102                                       ArrayRef<OffsetOfComponent> Components,
15103                                       SourceLocation RParenLoc) {
15104 
15105   TypeSourceInfo *ArgTInfo;
15106   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15107   if (ArgTy.isNull())
15108     return ExprError();
15109 
15110   if (!ArgTInfo)
15111     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15112 
15113   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15114 }
15115 
15116 
15117 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15118                                  Expr *CondExpr,
15119                                  Expr *LHSExpr, Expr *RHSExpr,
15120                                  SourceLocation RPLoc) {
15121   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15122 
15123   ExprValueKind VK = VK_RValue;
15124   ExprObjectKind OK = OK_Ordinary;
15125   QualType resType;
15126   bool CondIsTrue = false;
15127   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15128     resType = Context.DependentTy;
15129   } else {
15130     // The conditional expression is required to be a constant expression.
15131     llvm::APSInt condEval(32);
15132     ExprResult CondICE = VerifyIntegerConstantExpression(
15133         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15134     if (CondICE.isInvalid())
15135       return ExprError();
15136     CondExpr = CondICE.get();
15137     CondIsTrue = condEval.getZExtValue();
15138 
15139     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15140     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15141 
15142     resType = ActiveExpr->getType();
15143     VK = ActiveExpr->getValueKind();
15144     OK = ActiveExpr->getObjectKind();
15145   }
15146 
15147   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15148                                   resType, VK, OK, RPLoc, CondIsTrue);
15149 }
15150 
15151 //===----------------------------------------------------------------------===//
15152 // Clang Extensions.
15153 //===----------------------------------------------------------------------===//
15154 
15155 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15156 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15157   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15158 
15159   if (LangOpts.CPlusPlus) {
15160     MangleNumberingContext *MCtx;
15161     Decl *ManglingContextDecl;
15162     std::tie(MCtx, ManglingContextDecl) =
15163         getCurrentMangleNumberContext(Block->getDeclContext());
15164     if (MCtx) {
15165       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15166       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15167     }
15168   }
15169 
15170   PushBlockScope(CurScope, Block);
15171   CurContext->addDecl(Block);
15172   if (CurScope)
15173     PushDeclContext(CurScope, Block);
15174   else
15175     CurContext = Block;
15176 
15177   getCurBlock()->HasImplicitReturnType = true;
15178 
15179   // Enter a new evaluation context to insulate the block from any
15180   // cleanups from the enclosing full-expression.
15181   PushExpressionEvaluationContext(
15182       ExpressionEvaluationContext::PotentiallyEvaluated);
15183 }
15184 
15185 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15186                                Scope *CurScope) {
15187   assert(ParamInfo.getIdentifier() == nullptr &&
15188          "block-id should have no identifier!");
15189   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15190   BlockScopeInfo *CurBlock = getCurBlock();
15191 
15192   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15193   QualType T = Sig->getType();
15194 
15195   // FIXME: We should allow unexpanded parameter packs here, but that would,
15196   // in turn, make the block expression contain unexpanded parameter packs.
15197   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15198     // Drop the parameters.
15199     FunctionProtoType::ExtProtoInfo EPI;
15200     EPI.HasTrailingReturn = false;
15201     EPI.TypeQuals.addConst();
15202     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15203     Sig = Context.getTrivialTypeSourceInfo(T);
15204   }
15205 
15206   // GetTypeForDeclarator always produces a function type for a block
15207   // literal signature.  Furthermore, it is always a FunctionProtoType
15208   // unless the function was written with a typedef.
15209   assert(T->isFunctionType() &&
15210          "GetTypeForDeclarator made a non-function block signature");
15211 
15212   // Look for an explicit signature in that function type.
15213   FunctionProtoTypeLoc ExplicitSignature;
15214 
15215   if ((ExplicitSignature = Sig->getTypeLoc()
15216                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15217 
15218     // Check whether that explicit signature was synthesized by
15219     // GetTypeForDeclarator.  If so, don't save that as part of the
15220     // written signature.
15221     if (ExplicitSignature.getLocalRangeBegin() ==
15222         ExplicitSignature.getLocalRangeEnd()) {
15223       // This would be much cheaper if we stored TypeLocs instead of
15224       // TypeSourceInfos.
15225       TypeLoc Result = ExplicitSignature.getReturnLoc();
15226       unsigned Size = Result.getFullDataSize();
15227       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15228       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15229 
15230       ExplicitSignature = FunctionProtoTypeLoc();
15231     }
15232   }
15233 
15234   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15235   CurBlock->FunctionType = T;
15236 
15237   const auto *Fn = T->castAs<FunctionType>();
15238   QualType RetTy = Fn->getReturnType();
15239   bool isVariadic =
15240       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15241 
15242   CurBlock->TheDecl->setIsVariadic(isVariadic);
15243 
15244   // Context.DependentTy is used as a placeholder for a missing block
15245   // return type.  TODO:  what should we do with declarators like:
15246   //   ^ * { ... }
15247   // If the answer is "apply template argument deduction"....
15248   if (RetTy != Context.DependentTy) {
15249     CurBlock->ReturnType = RetTy;
15250     CurBlock->TheDecl->setBlockMissingReturnType(false);
15251     CurBlock->HasImplicitReturnType = false;
15252   }
15253 
15254   // Push block parameters from the declarator if we had them.
15255   SmallVector<ParmVarDecl*, 8> Params;
15256   if (ExplicitSignature) {
15257     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15258       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15259       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15260           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15261         // Diagnose this as an extension in C17 and earlier.
15262         if (!getLangOpts().C2x)
15263           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15264       }
15265       Params.push_back(Param);
15266     }
15267 
15268   // Fake up parameter variables if we have a typedef, like
15269   //   ^ fntype { ... }
15270   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15271     for (const auto &I : Fn->param_types()) {
15272       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15273           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15274       Params.push_back(Param);
15275     }
15276   }
15277 
15278   // Set the parameters on the block decl.
15279   if (!Params.empty()) {
15280     CurBlock->TheDecl->setParams(Params);
15281     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15282                              /*CheckParameterNames=*/false);
15283   }
15284 
15285   // Finally we can process decl attributes.
15286   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15287 
15288   // Put the parameter variables in scope.
15289   for (auto AI : CurBlock->TheDecl->parameters()) {
15290     AI->setOwningFunction(CurBlock->TheDecl);
15291 
15292     // If this has an identifier, add it to the scope stack.
15293     if (AI->getIdentifier()) {
15294       CheckShadow(CurBlock->TheScope, AI);
15295 
15296       PushOnScopeChains(AI, CurBlock->TheScope);
15297     }
15298   }
15299 }
15300 
15301 /// ActOnBlockError - If there is an error parsing a block, this callback
15302 /// is invoked to pop the information about the block from the action impl.
15303 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15304   // Leave the expression-evaluation context.
15305   DiscardCleanupsInEvaluationContext();
15306   PopExpressionEvaluationContext();
15307 
15308   // Pop off CurBlock, handle nested blocks.
15309   PopDeclContext();
15310   PopFunctionScopeInfo();
15311 }
15312 
15313 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15314 /// literal was successfully completed.  ^(int x){...}
15315 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15316                                     Stmt *Body, Scope *CurScope) {
15317   // If blocks are disabled, emit an error.
15318   if (!LangOpts.Blocks)
15319     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15320 
15321   // Leave the expression-evaluation context.
15322   if (hasAnyUnrecoverableErrorsInThisFunction())
15323     DiscardCleanupsInEvaluationContext();
15324   assert(!Cleanup.exprNeedsCleanups() &&
15325          "cleanups within block not correctly bound!");
15326   PopExpressionEvaluationContext();
15327 
15328   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15329   BlockDecl *BD = BSI->TheDecl;
15330 
15331   if (BSI->HasImplicitReturnType)
15332     deduceClosureReturnType(*BSI);
15333 
15334   QualType RetTy = Context.VoidTy;
15335   if (!BSI->ReturnType.isNull())
15336     RetTy = BSI->ReturnType;
15337 
15338   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15339   QualType BlockTy;
15340 
15341   // If the user wrote a function type in some form, try to use that.
15342   if (!BSI->FunctionType.isNull()) {
15343     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15344 
15345     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15346     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15347 
15348     // Turn protoless block types into nullary block types.
15349     if (isa<FunctionNoProtoType>(FTy)) {
15350       FunctionProtoType::ExtProtoInfo EPI;
15351       EPI.ExtInfo = Ext;
15352       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15353 
15354     // Otherwise, if we don't need to change anything about the function type,
15355     // preserve its sugar structure.
15356     } else if (FTy->getReturnType() == RetTy &&
15357                (!NoReturn || FTy->getNoReturnAttr())) {
15358       BlockTy = BSI->FunctionType;
15359 
15360     // Otherwise, make the minimal modifications to the function type.
15361     } else {
15362       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15363       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15364       EPI.TypeQuals = Qualifiers();
15365       EPI.ExtInfo = Ext;
15366       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15367     }
15368 
15369   // If we don't have a function type, just build one from nothing.
15370   } else {
15371     FunctionProtoType::ExtProtoInfo EPI;
15372     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15373     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15374   }
15375 
15376   DiagnoseUnusedParameters(BD->parameters());
15377   BlockTy = Context.getBlockPointerType(BlockTy);
15378 
15379   // If needed, diagnose invalid gotos and switches in the block.
15380   if (getCurFunction()->NeedsScopeChecking() &&
15381       !PP.isCodeCompletionEnabled())
15382     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15383 
15384   BD->setBody(cast<CompoundStmt>(Body));
15385 
15386   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15387     DiagnoseUnguardedAvailabilityViolations(BD);
15388 
15389   // Try to apply the named return value optimization. We have to check again
15390   // if we can do this, though, because blocks keep return statements around
15391   // to deduce an implicit return type.
15392   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15393       !BD->isDependentContext())
15394     computeNRVO(Body, BSI);
15395 
15396   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15397       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15398     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15399                           NTCUK_Destruct|NTCUK_Copy);
15400 
15401   PopDeclContext();
15402 
15403   // Pop the block scope now but keep it alive to the end of this function.
15404   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15405   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15406 
15407   // Set the captured variables on the block.
15408   SmallVector<BlockDecl::Capture, 4> Captures;
15409   for (Capture &Cap : BSI->Captures) {
15410     if (Cap.isInvalid() || Cap.isThisCapture())
15411       continue;
15412 
15413     VarDecl *Var = Cap.getVariable();
15414     Expr *CopyExpr = nullptr;
15415     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15416       if (const RecordType *Record =
15417               Cap.getCaptureType()->getAs<RecordType>()) {
15418         // The capture logic needs the destructor, so make sure we mark it.
15419         // Usually this is unnecessary because most local variables have
15420         // their destructors marked at declaration time, but parameters are
15421         // an exception because it's technically only the call site that
15422         // actually requires the destructor.
15423         if (isa<ParmVarDecl>(Var))
15424           FinalizeVarWithDestructor(Var, Record);
15425 
15426         // Enter a separate potentially-evaluated context while building block
15427         // initializers to isolate their cleanups from those of the block
15428         // itself.
15429         // FIXME: Is this appropriate even when the block itself occurs in an
15430         // unevaluated operand?
15431         EnterExpressionEvaluationContext EvalContext(
15432             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15433 
15434         SourceLocation Loc = Cap.getLocation();
15435 
15436         ExprResult Result = BuildDeclarationNameExpr(
15437             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15438 
15439         // According to the blocks spec, the capture of a variable from
15440         // the stack requires a const copy constructor.  This is not true
15441         // of the copy/move done to move a __block variable to the heap.
15442         if (!Result.isInvalid() &&
15443             !Result.get()->getType().isConstQualified()) {
15444           Result = ImpCastExprToType(Result.get(),
15445                                      Result.get()->getType().withConst(),
15446                                      CK_NoOp, VK_LValue);
15447         }
15448 
15449         if (!Result.isInvalid()) {
15450           Result = PerformCopyInitialization(
15451               InitializedEntity::InitializeBlock(Var->getLocation(),
15452                                                  Cap.getCaptureType(), false),
15453               Loc, Result.get());
15454         }
15455 
15456         // Build a full-expression copy expression if initialization
15457         // succeeded and used a non-trivial constructor.  Recover from
15458         // errors by pretending that the copy isn't necessary.
15459         if (!Result.isInvalid() &&
15460             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15461                 ->isTrivial()) {
15462           Result = MaybeCreateExprWithCleanups(Result);
15463           CopyExpr = Result.get();
15464         }
15465       }
15466     }
15467 
15468     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15469                               CopyExpr);
15470     Captures.push_back(NewCap);
15471   }
15472   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15473 
15474   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15475 
15476   // If the block isn't obviously global, i.e. it captures anything at
15477   // all, then we need to do a few things in the surrounding context:
15478   if (Result->getBlockDecl()->hasCaptures()) {
15479     // First, this expression has a new cleanup object.
15480     ExprCleanupObjects.push_back(Result->getBlockDecl());
15481     Cleanup.setExprNeedsCleanups(true);
15482 
15483     // It also gets a branch-protected scope if any of the captured
15484     // variables needs destruction.
15485     for (const auto &CI : Result->getBlockDecl()->captures()) {
15486       const VarDecl *var = CI.getVariable();
15487       if (var->getType().isDestructedType() != QualType::DK_none) {
15488         setFunctionHasBranchProtectedScope();
15489         break;
15490       }
15491     }
15492   }
15493 
15494   if (getCurFunction())
15495     getCurFunction()->addBlock(BD);
15496 
15497   return Result;
15498 }
15499 
15500 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15501                             SourceLocation RPLoc) {
15502   TypeSourceInfo *TInfo;
15503   GetTypeFromParser(Ty, &TInfo);
15504   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15505 }
15506 
15507 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15508                                 Expr *E, TypeSourceInfo *TInfo,
15509                                 SourceLocation RPLoc) {
15510   Expr *OrigExpr = E;
15511   bool IsMS = false;
15512 
15513   // CUDA device code does not support varargs.
15514   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15515     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15516       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15517       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15518         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15519     }
15520   }
15521 
15522   // NVPTX does not support va_arg expression.
15523   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15524       Context.getTargetInfo().getTriple().isNVPTX())
15525     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15526 
15527   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15528   // as Microsoft ABI on an actual Microsoft platform, where
15529   // __builtin_ms_va_list and __builtin_va_list are the same.)
15530   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15531       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15532     QualType MSVaListType = Context.getBuiltinMSVaListType();
15533     if (Context.hasSameType(MSVaListType, E->getType())) {
15534       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15535         return ExprError();
15536       IsMS = true;
15537     }
15538   }
15539 
15540   // Get the va_list type
15541   QualType VaListType = Context.getBuiltinVaListType();
15542   if (!IsMS) {
15543     if (VaListType->isArrayType()) {
15544       // Deal with implicit array decay; for example, on x86-64,
15545       // va_list is an array, but it's supposed to decay to
15546       // a pointer for va_arg.
15547       VaListType = Context.getArrayDecayedType(VaListType);
15548       // Make sure the input expression also decays appropriately.
15549       ExprResult Result = UsualUnaryConversions(E);
15550       if (Result.isInvalid())
15551         return ExprError();
15552       E = Result.get();
15553     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15554       // If va_list is a record type and we are compiling in C++ mode,
15555       // check the argument using reference binding.
15556       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15557           Context, Context.getLValueReferenceType(VaListType), false);
15558       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15559       if (Init.isInvalid())
15560         return ExprError();
15561       E = Init.getAs<Expr>();
15562     } else {
15563       // Otherwise, the va_list argument must be an l-value because
15564       // it is modified by va_arg.
15565       if (!E->isTypeDependent() &&
15566           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15567         return ExprError();
15568     }
15569   }
15570 
15571   if (!IsMS && !E->isTypeDependent() &&
15572       !Context.hasSameType(VaListType, E->getType()))
15573     return ExprError(
15574         Diag(E->getBeginLoc(),
15575              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15576         << OrigExpr->getType() << E->getSourceRange());
15577 
15578   if (!TInfo->getType()->isDependentType()) {
15579     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15580                             diag::err_second_parameter_to_va_arg_incomplete,
15581                             TInfo->getTypeLoc()))
15582       return ExprError();
15583 
15584     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15585                                TInfo->getType(),
15586                                diag::err_second_parameter_to_va_arg_abstract,
15587                                TInfo->getTypeLoc()))
15588       return ExprError();
15589 
15590     if (!TInfo->getType().isPODType(Context)) {
15591       Diag(TInfo->getTypeLoc().getBeginLoc(),
15592            TInfo->getType()->isObjCLifetimeType()
15593              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15594              : diag::warn_second_parameter_to_va_arg_not_pod)
15595         << TInfo->getType()
15596         << TInfo->getTypeLoc().getSourceRange();
15597     }
15598 
15599     // Check for va_arg where arguments of the given type will be promoted
15600     // (i.e. this va_arg is guaranteed to have undefined behavior).
15601     QualType PromoteType;
15602     if (TInfo->getType()->isPromotableIntegerType()) {
15603       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15604       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15605         PromoteType = QualType();
15606     }
15607     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15608       PromoteType = Context.DoubleTy;
15609     if (!PromoteType.isNull())
15610       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15611                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15612                           << TInfo->getType()
15613                           << PromoteType
15614                           << TInfo->getTypeLoc().getSourceRange());
15615   }
15616 
15617   QualType T = TInfo->getType().getNonLValueExprType(Context);
15618   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15619 }
15620 
15621 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15622   // The type of __null will be int or long, depending on the size of
15623   // pointers on the target.
15624   QualType Ty;
15625   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15626   if (pw == Context.getTargetInfo().getIntWidth())
15627     Ty = Context.IntTy;
15628   else if (pw == Context.getTargetInfo().getLongWidth())
15629     Ty = Context.LongTy;
15630   else if (pw == Context.getTargetInfo().getLongLongWidth())
15631     Ty = Context.LongLongTy;
15632   else {
15633     llvm_unreachable("I don't know size of pointer!");
15634   }
15635 
15636   return new (Context) GNUNullExpr(Ty, TokenLoc);
15637 }
15638 
15639 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15640                                     SourceLocation BuiltinLoc,
15641                                     SourceLocation RPLoc) {
15642   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15643 }
15644 
15645 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15646                                     SourceLocation BuiltinLoc,
15647                                     SourceLocation RPLoc,
15648                                     DeclContext *ParentContext) {
15649   return new (Context)
15650       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15651 }
15652 
15653 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15654                                         bool Diagnose) {
15655   if (!getLangOpts().ObjC)
15656     return false;
15657 
15658   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15659   if (!PT)
15660     return false;
15661   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15662 
15663   // Ignore any parens, implicit casts (should only be
15664   // array-to-pointer decays), and not-so-opaque values.  The last is
15665   // important for making this trigger for property assignments.
15666   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15667   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15668     if (OV->getSourceExpr())
15669       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15670 
15671   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15672     if (!PT->isObjCIdType() &&
15673         !(ID && ID->getIdentifier()->isStr("NSString")))
15674       return false;
15675     if (!SL->isAscii())
15676       return false;
15677 
15678     if (Diagnose) {
15679       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15680           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15681       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15682     }
15683     return true;
15684   }
15685 
15686   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15687       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15688       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15689       !SrcExpr->isNullPointerConstant(
15690           getASTContext(), Expr::NPC_NeverValueDependent)) {
15691     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15692       return false;
15693     if (Diagnose) {
15694       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15695           << /*number*/1
15696           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15697       Expr *NumLit =
15698           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15699       if (NumLit)
15700         Exp = NumLit;
15701     }
15702     return true;
15703   }
15704 
15705   return false;
15706 }
15707 
15708 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15709                                               const Expr *SrcExpr) {
15710   if (!DstType->isFunctionPointerType() ||
15711       !SrcExpr->getType()->isFunctionType())
15712     return false;
15713 
15714   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15715   if (!DRE)
15716     return false;
15717 
15718   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15719   if (!FD)
15720     return false;
15721 
15722   return !S.checkAddressOfFunctionIsAvailable(FD,
15723                                               /*Complain=*/true,
15724                                               SrcExpr->getBeginLoc());
15725 }
15726 
15727 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15728                                     SourceLocation Loc,
15729                                     QualType DstType, QualType SrcType,
15730                                     Expr *SrcExpr, AssignmentAction Action,
15731                                     bool *Complained) {
15732   if (Complained)
15733     *Complained = false;
15734 
15735   // Decode the result (notice that AST's are still created for extensions).
15736   bool CheckInferredResultType = false;
15737   bool isInvalid = false;
15738   unsigned DiagKind = 0;
15739   ConversionFixItGenerator ConvHints;
15740   bool MayHaveConvFixit = false;
15741   bool MayHaveFunctionDiff = false;
15742   const ObjCInterfaceDecl *IFace = nullptr;
15743   const ObjCProtocolDecl *PDecl = nullptr;
15744 
15745   switch (ConvTy) {
15746   case Compatible:
15747       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15748       return false;
15749 
15750   case PointerToInt:
15751     if (getLangOpts().CPlusPlus) {
15752       DiagKind = diag::err_typecheck_convert_pointer_int;
15753       isInvalid = true;
15754     } else {
15755       DiagKind = diag::ext_typecheck_convert_pointer_int;
15756     }
15757     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15758     MayHaveConvFixit = true;
15759     break;
15760   case IntToPointer:
15761     if (getLangOpts().CPlusPlus) {
15762       DiagKind = diag::err_typecheck_convert_int_pointer;
15763       isInvalid = true;
15764     } else {
15765       DiagKind = diag::ext_typecheck_convert_int_pointer;
15766     }
15767     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15768     MayHaveConvFixit = true;
15769     break;
15770   case IncompatibleFunctionPointer:
15771     if (getLangOpts().CPlusPlus) {
15772       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15773       isInvalid = true;
15774     } else {
15775       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15776     }
15777     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15778     MayHaveConvFixit = true;
15779     break;
15780   case IncompatiblePointer:
15781     if (Action == AA_Passing_CFAudited) {
15782       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15783     } else if (getLangOpts().CPlusPlus) {
15784       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15785       isInvalid = true;
15786     } else {
15787       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15788     }
15789     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15790       SrcType->isObjCObjectPointerType();
15791     if (!CheckInferredResultType) {
15792       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15793     } else if (CheckInferredResultType) {
15794       SrcType = SrcType.getUnqualifiedType();
15795       DstType = DstType.getUnqualifiedType();
15796     }
15797     MayHaveConvFixit = true;
15798     break;
15799   case IncompatiblePointerSign:
15800     if (getLangOpts().CPlusPlus) {
15801       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15802       isInvalid = true;
15803     } else {
15804       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15805     }
15806     break;
15807   case FunctionVoidPointer:
15808     if (getLangOpts().CPlusPlus) {
15809       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15810       isInvalid = true;
15811     } else {
15812       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15813     }
15814     break;
15815   case IncompatiblePointerDiscardsQualifiers: {
15816     // Perform array-to-pointer decay if necessary.
15817     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15818 
15819     isInvalid = true;
15820 
15821     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15822     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15823     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15824       DiagKind = diag::err_typecheck_incompatible_address_space;
15825       break;
15826 
15827     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15828       DiagKind = diag::err_typecheck_incompatible_ownership;
15829       break;
15830     }
15831 
15832     llvm_unreachable("unknown error case for discarding qualifiers!");
15833     // fallthrough
15834   }
15835   case CompatiblePointerDiscardsQualifiers:
15836     // If the qualifiers lost were because we were applying the
15837     // (deprecated) C++ conversion from a string literal to a char*
15838     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15839     // Ideally, this check would be performed in
15840     // checkPointerTypesForAssignment. However, that would require a
15841     // bit of refactoring (so that the second argument is an
15842     // expression, rather than a type), which should be done as part
15843     // of a larger effort to fix checkPointerTypesForAssignment for
15844     // C++ semantics.
15845     if (getLangOpts().CPlusPlus &&
15846         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15847       return false;
15848     if (getLangOpts().CPlusPlus) {
15849       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15850       isInvalid = true;
15851     } else {
15852       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15853     }
15854 
15855     break;
15856   case IncompatibleNestedPointerQualifiers:
15857     if (getLangOpts().CPlusPlus) {
15858       isInvalid = true;
15859       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15860     } else {
15861       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15862     }
15863     break;
15864   case IncompatibleNestedPointerAddressSpaceMismatch:
15865     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15866     isInvalid = true;
15867     break;
15868   case IntToBlockPointer:
15869     DiagKind = diag::err_int_to_block_pointer;
15870     isInvalid = true;
15871     break;
15872   case IncompatibleBlockPointer:
15873     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15874     isInvalid = true;
15875     break;
15876   case IncompatibleObjCQualifiedId: {
15877     if (SrcType->isObjCQualifiedIdType()) {
15878       const ObjCObjectPointerType *srcOPT =
15879                 SrcType->castAs<ObjCObjectPointerType>();
15880       for (auto *srcProto : srcOPT->quals()) {
15881         PDecl = srcProto;
15882         break;
15883       }
15884       if (const ObjCInterfaceType *IFaceT =
15885             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15886         IFace = IFaceT->getDecl();
15887     }
15888     else if (DstType->isObjCQualifiedIdType()) {
15889       const ObjCObjectPointerType *dstOPT =
15890         DstType->castAs<ObjCObjectPointerType>();
15891       for (auto *dstProto : dstOPT->quals()) {
15892         PDecl = dstProto;
15893         break;
15894       }
15895       if (const ObjCInterfaceType *IFaceT =
15896             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15897         IFace = IFaceT->getDecl();
15898     }
15899     if (getLangOpts().CPlusPlus) {
15900       DiagKind = diag::err_incompatible_qualified_id;
15901       isInvalid = true;
15902     } else {
15903       DiagKind = diag::warn_incompatible_qualified_id;
15904     }
15905     break;
15906   }
15907   case IncompatibleVectors:
15908     if (getLangOpts().CPlusPlus) {
15909       DiagKind = diag::err_incompatible_vectors;
15910       isInvalid = true;
15911     } else {
15912       DiagKind = diag::warn_incompatible_vectors;
15913     }
15914     break;
15915   case IncompatibleObjCWeakRef:
15916     DiagKind = diag::err_arc_weak_unavailable_assign;
15917     isInvalid = true;
15918     break;
15919   case Incompatible:
15920     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15921       if (Complained)
15922         *Complained = true;
15923       return true;
15924     }
15925 
15926     DiagKind = diag::err_typecheck_convert_incompatible;
15927     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15928     MayHaveConvFixit = true;
15929     isInvalid = true;
15930     MayHaveFunctionDiff = true;
15931     break;
15932   }
15933 
15934   QualType FirstType, SecondType;
15935   switch (Action) {
15936   case AA_Assigning:
15937   case AA_Initializing:
15938     // The destination type comes first.
15939     FirstType = DstType;
15940     SecondType = SrcType;
15941     break;
15942 
15943   case AA_Returning:
15944   case AA_Passing:
15945   case AA_Passing_CFAudited:
15946   case AA_Converting:
15947   case AA_Sending:
15948   case AA_Casting:
15949     // The source type comes first.
15950     FirstType = SrcType;
15951     SecondType = DstType;
15952     break;
15953   }
15954 
15955   PartialDiagnostic FDiag = PDiag(DiagKind);
15956   if (Action == AA_Passing_CFAudited)
15957     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15958   else
15959     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15960 
15961   // If we can fix the conversion, suggest the FixIts.
15962   if (!ConvHints.isNull()) {
15963     for (FixItHint &H : ConvHints.Hints)
15964       FDiag << H;
15965   }
15966 
15967   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15968 
15969   if (MayHaveFunctionDiff)
15970     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15971 
15972   Diag(Loc, FDiag);
15973   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15974        DiagKind == diag::err_incompatible_qualified_id) &&
15975       PDecl && IFace && !IFace->hasDefinition())
15976     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15977         << IFace << PDecl;
15978 
15979   if (SecondType == Context.OverloadTy)
15980     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15981                               FirstType, /*TakingAddress=*/true);
15982 
15983   if (CheckInferredResultType)
15984     EmitRelatedResultTypeNote(SrcExpr);
15985 
15986   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15987     EmitRelatedResultTypeNoteForReturn(DstType);
15988 
15989   if (Complained)
15990     *Complained = true;
15991   return isInvalid;
15992 }
15993 
15994 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15995                                                  llvm::APSInt *Result,
15996                                                  AllowFoldKind CanFold) {
15997   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15998   public:
15999     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16000                                              QualType T) override {
16001       return S.Diag(Loc, diag::err_ice_not_integral)
16002              << T << S.LangOpts.CPlusPlus;
16003     }
16004     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16005       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16006     }
16007   } Diagnoser;
16008 
16009   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16010 }
16011 
16012 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16013                                                  llvm::APSInt *Result,
16014                                                  unsigned DiagID,
16015                                                  AllowFoldKind CanFold) {
16016   class IDDiagnoser : public VerifyICEDiagnoser {
16017     unsigned DiagID;
16018 
16019   public:
16020     IDDiagnoser(unsigned DiagID)
16021       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16022 
16023     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16024       return S.Diag(Loc, DiagID);
16025     }
16026   } Diagnoser(DiagID);
16027 
16028   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16029 }
16030 
16031 Sema::SemaDiagnosticBuilder
16032 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16033                                              QualType T) {
16034   return diagnoseNotICE(S, Loc);
16035 }
16036 
16037 Sema::SemaDiagnosticBuilder
16038 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16039   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16040 }
16041 
16042 ExprResult
16043 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16044                                       VerifyICEDiagnoser &Diagnoser,
16045                                       AllowFoldKind CanFold) {
16046   SourceLocation DiagLoc = E->getBeginLoc();
16047 
16048   if (getLangOpts().CPlusPlus11) {
16049     // C++11 [expr.const]p5:
16050     //   If an expression of literal class type is used in a context where an
16051     //   integral constant expression is required, then that class type shall
16052     //   have a single non-explicit conversion function to an integral or
16053     //   unscoped enumeration type
16054     ExprResult Converted;
16055     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16056       VerifyICEDiagnoser &BaseDiagnoser;
16057     public:
16058       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16059           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16060                                 BaseDiagnoser.Suppress, true),
16061             BaseDiagnoser(BaseDiagnoser) {}
16062 
16063       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16064                                            QualType T) override {
16065         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16066       }
16067 
16068       SemaDiagnosticBuilder diagnoseIncomplete(
16069           Sema &S, SourceLocation Loc, QualType T) override {
16070         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16071       }
16072 
16073       SemaDiagnosticBuilder diagnoseExplicitConv(
16074           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16075         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16076       }
16077 
16078       SemaDiagnosticBuilder noteExplicitConv(
16079           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16080         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16081                  << ConvTy->isEnumeralType() << ConvTy;
16082       }
16083 
16084       SemaDiagnosticBuilder diagnoseAmbiguous(
16085           Sema &S, SourceLocation Loc, QualType T) override {
16086         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16087       }
16088 
16089       SemaDiagnosticBuilder noteAmbiguous(
16090           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16091         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16092                  << ConvTy->isEnumeralType() << ConvTy;
16093       }
16094 
16095       SemaDiagnosticBuilder diagnoseConversion(
16096           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16097         llvm_unreachable("conversion functions are permitted");
16098       }
16099     } ConvertDiagnoser(Diagnoser);
16100 
16101     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16102                                                     ConvertDiagnoser);
16103     if (Converted.isInvalid())
16104       return Converted;
16105     E = Converted.get();
16106     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16107       return ExprError();
16108   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16109     // An ICE must be of integral or unscoped enumeration type.
16110     if (!Diagnoser.Suppress)
16111       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16112           << E->getSourceRange();
16113     return ExprError();
16114   }
16115 
16116   ExprResult RValueExpr = DefaultLvalueConversion(E);
16117   if (RValueExpr.isInvalid())
16118     return ExprError();
16119 
16120   E = RValueExpr.get();
16121 
16122   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16123   // in the non-ICE case.
16124   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16125     if (Result)
16126       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16127     if (!isa<ConstantExpr>(E))
16128       E = ConstantExpr::Create(Context, E);
16129     return E;
16130   }
16131 
16132   Expr::EvalResult EvalResult;
16133   SmallVector<PartialDiagnosticAt, 8> Notes;
16134   EvalResult.Diag = &Notes;
16135 
16136   // Try to evaluate the expression, and produce diagnostics explaining why it's
16137   // not a constant expression as a side-effect.
16138   bool Folded =
16139       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16140       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16141 
16142   if (!isa<ConstantExpr>(E))
16143     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16144 
16145   // In C++11, we can rely on diagnostics being produced for any expression
16146   // which is not a constant expression. If no diagnostics were produced, then
16147   // this is a constant expression.
16148   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16149     if (Result)
16150       *Result = EvalResult.Val.getInt();
16151     return E;
16152   }
16153 
16154   // If our only note is the usual "invalid subexpression" note, just point
16155   // the caret at its location rather than producing an essentially
16156   // redundant note.
16157   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16158         diag::note_invalid_subexpr_in_const_expr) {
16159     DiagLoc = Notes[0].first;
16160     Notes.clear();
16161   }
16162 
16163   if (!Folded || !CanFold) {
16164     if (!Diagnoser.Suppress) {
16165       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16166       for (const PartialDiagnosticAt &Note : Notes)
16167         Diag(Note.first, Note.second);
16168     }
16169 
16170     return ExprError();
16171   }
16172 
16173   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16174   for (const PartialDiagnosticAt &Note : Notes)
16175     Diag(Note.first, Note.second);
16176 
16177   if (Result)
16178     *Result = EvalResult.Val.getInt();
16179   return E;
16180 }
16181 
16182 namespace {
16183   // Handle the case where we conclude a expression which we speculatively
16184   // considered to be unevaluated is actually evaluated.
16185   class TransformToPE : public TreeTransform<TransformToPE> {
16186     typedef TreeTransform<TransformToPE> BaseTransform;
16187 
16188   public:
16189     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16190 
16191     // Make sure we redo semantic analysis
16192     bool AlwaysRebuild() { return true; }
16193     bool ReplacingOriginal() { return true; }
16194 
16195     // We need to special-case DeclRefExprs referring to FieldDecls which
16196     // are not part of a member pointer formation; normal TreeTransforming
16197     // doesn't catch this case because of the way we represent them in the AST.
16198     // FIXME: This is a bit ugly; is it really the best way to handle this
16199     // case?
16200     //
16201     // Error on DeclRefExprs referring to FieldDecls.
16202     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16203       if (isa<FieldDecl>(E->getDecl()) &&
16204           !SemaRef.isUnevaluatedContext())
16205         return SemaRef.Diag(E->getLocation(),
16206                             diag::err_invalid_non_static_member_use)
16207             << E->getDecl() << E->getSourceRange();
16208 
16209       return BaseTransform::TransformDeclRefExpr(E);
16210     }
16211 
16212     // Exception: filter out member pointer formation
16213     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16214       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16215         return E;
16216 
16217       return BaseTransform::TransformUnaryOperator(E);
16218     }
16219 
16220     // The body of a lambda-expression is in a separate expression evaluation
16221     // context so never needs to be transformed.
16222     // FIXME: Ideally we wouldn't transform the closure type either, and would
16223     // just recreate the capture expressions and lambda expression.
16224     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16225       return SkipLambdaBody(E, Body);
16226     }
16227   };
16228 }
16229 
16230 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16231   assert(isUnevaluatedContext() &&
16232          "Should only transform unevaluated expressions");
16233   ExprEvalContexts.back().Context =
16234       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16235   if (isUnevaluatedContext())
16236     return E;
16237   return TransformToPE(*this).TransformExpr(E);
16238 }
16239 
16240 void
16241 Sema::PushExpressionEvaluationContext(
16242     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16243     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16244   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16245                                 LambdaContextDecl, ExprContext);
16246   Cleanup.reset();
16247   if (!MaybeODRUseExprs.empty())
16248     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16249 }
16250 
16251 void
16252 Sema::PushExpressionEvaluationContext(
16253     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16254     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16255   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16256   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16257 }
16258 
16259 namespace {
16260 
16261 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16262   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16263   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16264     if (E->getOpcode() == UO_Deref)
16265       return CheckPossibleDeref(S, E->getSubExpr());
16266   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16267     return CheckPossibleDeref(S, E->getBase());
16268   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16269     return CheckPossibleDeref(S, E->getBase());
16270   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16271     QualType Inner;
16272     QualType Ty = E->getType();
16273     if (const auto *Ptr = Ty->getAs<PointerType>())
16274       Inner = Ptr->getPointeeType();
16275     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16276       Inner = Arr->getElementType();
16277     else
16278       return nullptr;
16279 
16280     if (Inner->hasAttr(attr::NoDeref))
16281       return E;
16282   }
16283   return nullptr;
16284 }
16285 
16286 } // namespace
16287 
16288 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16289   for (const Expr *E : Rec.PossibleDerefs) {
16290     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16291     if (DeclRef) {
16292       const ValueDecl *Decl = DeclRef->getDecl();
16293       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16294           << Decl->getName() << E->getSourceRange();
16295       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16296     } else {
16297       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16298           << E->getSourceRange();
16299     }
16300   }
16301   Rec.PossibleDerefs.clear();
16302 }
16303 
16304 /// Check whether E, which is either a discarded-value expression or an
16305 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16306 /// and if so, remove it from the list of volatile-qualified assignments that
16307 /// we are going to warn are deprecated.
16308 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16309   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16310     return;
16311 
16312   // Note: ignoring parens here is not justified by the standard rules, but
16313   // ignoring parentheses seems like a more reasonable approach, and this only
16314   // drives a deprecation warning so doesn't affect conformance.
16315   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16316     if (BO->getOpcode() == BO_Assign) {
16317       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16318       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16319                  LHSs.end());
16320     }
16321   }
16322 }
16323 
16324 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16325   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16326       RebuildingImmediateInvocation)
16327     return E;
16328 
16329   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16330   /// It's OK if this fails; we'll also remove this in
16331   /// HandleImmediateInvocations, but catching it here allows us to avoid
16332   /// walking the AST looking for it in simple cases.
16333   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16334     if (auto *DeclRef =
16335             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16336       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16337 
16338   E = MaybeCreateExprWithCleanups(E);
16339 
16340   ConstantExpr *Res = ConstantExpr::Create(
16341       getASTContext(), E.get(),
16342       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16343                                    getASTContext()),
16344       /*IsImmediateInvocation*/ true);
16345   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16346   return Res;
16347 }
16348 
16349 static void EvaluateAndDiagnoseImmediateInvocation(
16350     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16351   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16352   Expr::EvalResult Eval;
16353   Eval.Diag = &Notes;
16354   ConstantExpr *CE = Candidate.getPointer();
16355   bool Result = CE->EvaluateAsConstantExpr(
16356       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16357   if (!Result || !Notes.empty()) {
16358     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16359     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16360       InnerExpr = FunctionalCast->getSubExpr();
16361     FunctionDecl *FD = nullptr;
16362     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16363       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16364     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16365       FD = Call->getConstructor();
16366     else
16367       llvm_unreachable("unhandled decl kind");
16368     assert(FD->isConsteval());
16369     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16370     for (auto &Note : Notes)
16371       SemaRef.Diag(Note.first, Note.second);
16372     return;
16373   }
16374   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16375 }
16376 
16377 static void RemoveNestedImmediateInvocation(
16378     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16379     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16380   struct ComplexRemove : TreeTransform<ComplexRemove> {
16381     using Base = TreeTransform<ComplexRemove>;
16382     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16383     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16384     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16385         CurrentII;
16386     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16387                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16388                   SmallVector<Sema::ImmediateInvocationCandidate,
16389                               4>::reverse_iterator Current)
16390         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16391     void RemoveImmediateInvocation(ConstantExpr* E) {
16392       auto It = std::find_if(CurrentII, IISet.rend(),
16393                              [E](Sema::ImmediateInvocationCandidate Elem) {
16394                                return Elem.getPointer() == E;
16395                              });
16396       assert(It != IISet.rend() &&
16397              "ConstantExpr marked IsImmediateInvocation should "
16398              "be present");
16399       It->setInt(1); // Mark as deleted
16400     }
16401     ExprResult TransformConstantExpr(ConstantExpr *E) {
16402       if (!E->isImmediateInvocation())
16403         return Base::TransformConstantExpr(E);
16404       RemoveImmediateInvocation(E);
16405       return Base::TransformExpr(E->getSubExpr());
16406     }
16407     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16408     /// we need to remove its DeclRefExpr from the DRSet.
16409     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16410       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16411       return Base::TransformCXXOperatorCallExpr(E);
16412     }
16413     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16414     /// here.
16415     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16416       if (!Init)
16417         return Init;
16418       /// ConstantExpr are the first layer of implicit node to be removed so if
16419       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16420       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16421         if (CE->isImmediateInvocation())
16422           RemoveImmediateInvocation(CE);
16423       return Base::TransformInitializer(Init, NotCopyInit);
16424     }
16425     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16426       DRSet.erase(E);
16427       return E;
16428     }
16429     bool AlwaysRebuild() { return false; }
16430     bool ReplacingOriginal() { return true; }
16431     bool AllowSkippingCXXConstructExpr() {
16432       bool Res = AllowSkippingFirstCXXConstructExpr;
16433       AllowSkippingFirstCXXConstructExpr = true;
16434       return Res;
16435     }
16436     bool AllowSkippingFirstCXXConstructExpr = true;
16437   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16438                 Rec.ImmediateInvocationCandidates, It);
16439 
16440   /// CXXConstructExpr with a single argument are getting skipped by
16441   /// TreeTransform in some situtation because they could be implicit. This
16442   /// can only occur for the top-level CXXConstructExpr because it is used
16443   /// nowhere in the expression being transformed therefore will not be rebuilt.
16444   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16445   /// skipping the first CXXConstructExpr.
16446   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16447     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16448 
16449   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16450   assert(Res.isUsable());
16451   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16452   It->getPointer()->setSubExpr(Res.get());
16453 }
16454 
16455 static void
16456 HandleImmediateInvocations(Sema &SemaRef,
16457                            Sema::ExpressionEvaluationContextRecord &Rec) {
16458   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16459        Rec.ReferenceToConsteval.size() == 0) ||
16460       SemaRef.RebuildingImmediateInvocation)
16461     return;
16462 
16463   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16464   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16465   /// need to remove ReferenceToConsteval in the immediate invocation.
16466   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16467 
16468     /// Prevent sema calls during the tree transform from adding pointers that
16469     /// are already in the sets.
16470     llvm::SaveAndRestore<bool> DisableIITracking(
16471         SemaRef.RebuildingImmediateInvocation, true);
16472 
16473     /// Prevent diagnostic during tree transfrom as they are duplicates
16474     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16475 
16476     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16477          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16478       if (!It->getInt())
16479         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16480   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16481              Rec.ReferenceToConsteval.size()) {
16482     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16483       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16484       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16485       bool VisitDeclRefExpr(DeclRefExpr *E) {
16486         DRSet.erase(E);
16487         return DRSet.size();
16488       }
16489     } Visitor(Rec.ReferenceToConsteval);
16490     Visitor.TraverseStmt(
16491         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16492   }
16493   for (auto CE : Rec.ImmediateInvocationCandidates)
16494     if (!CE.getInt())
16495       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16496   for (auto DR : Rec.ReferenceToConsteval) {
16497     auto *FD = cast<FunctionDecl>(DR->getDecl());
16498     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16499         << FD;
16500     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16501   }
16502 }
16503 
16504 void Sema::PopExpressionEvaluationContext() {
16505   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16506   unsigned NumTypos = Rec.NumTypos;
16507 
16508   if (!Rec.Lambdas.empty()) {
16509     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16510     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16511         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16512       unsigned D;
16513       if (Rec.isUnevaluated()) {
16514         // C++11 [expr.prim.lambda]p2:
16515         //   A lambda-expression shall not appear in an unevaluated operand
16516         //   (Clause 5).
16517         D = diag::err_lambda_unevaluated_operand;
16518       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16519         // C++1y [expr.const]p2:
16520         //   A conditional-expression e is a core constant expression unless the
16521         //   evaluation of e, following the rules of the abstract machine, would
16522         //   evaluate [...] a lambda-expression.
16523         D = diag::err_lambda_in_constant_expression;
16524       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16525         // C++17 [expr.prim.lamda]p2:
16526         // A lambda-expression shall not appear [...] in a template-argument.
16527         D = diag::err_lambda_in_invalid_context;
16528       } else
16529         llvm_unreachable("Couldn't infer lambda error message.");
16530 
16531       for (const auto *L : Rec.Lambdas)
16532         Diag(L->getBeginLoc(), D);
16533     }
16534   }
16535 
16536   WarnOnPendingNoDerefs(Rec);
16537   HandleImmediateInvocations(*this, Rec);
16538 
16539   // Warn on any volatile-qualified simple-assignments that are not discarded-
16540   // value expressions nor unevaluated operands (those cases get removed from
16541   // this list by CheckUnusedVolatileAssignment).
16542   for (auto *BO : Rec.VolatileAssignmentLHSs)
16543     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16544         << BO->getType();
16545 
16546   // When are coming out of an unevaluated context, clear out any
16547   // temporaries that we may have created as part of the evaluation of
16548   // the expression in that context: they aren't relevant because they
16549   // will never be constructed.
16550   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16551     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16552                              ExprCleanupObjects.end());
16553     Cleanup = Rec.ParentCleanup;
16554     CleanupVarDeclMarking();
16555     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16556   // Otherwise, merge the contexts together.
16557   } else {
16558     Cleanup.mergeFrom(Rec.ParentCleanup);
16559     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16560                             Rec.SavedMaybeODRUseExprs.end());
16561   }
16562 
16563   // Pop the current expression evaluation context off the stack.
16564   ExprEvalContexts.pop_back();
16565 
16566   // The global expression evaluation context record is never popped.
16567   ExprEvalContexts.back().NumTypos += NumTypos;
16568 }
16569 
16570 void Sema::DiscardCleanupsInEvaluationContext() {
16571   ExprCleanupObjects.erase(
16572          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16573          ExprCleanupObjects.end());
16574   Cleanup.reset();
16575   MaybeODRUseExprs.clear();
16576 }
16577 
16578 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16579   ExprResult Result = CheckPlaceholderExpr(E);
16580   if (Result.isInvalid())
16581     return ExprError();
16582   E = Result.get();
16583   if (!E->getType()->isVariablyModifiedType())
16584     return E;
16585   return TransformToPotentiallyEvaluated(E);
16586 }
16587 
16588 /// Are we in a context that is potentially constant evaluated per C++20
16589 /// [expr.const]p12?
16590 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16591   /// C++2a [expr.const]p12:
16592   //   An expression or conversion is potentially constant evaluated if it is
16593   switch (SemaRef.ExprEvalContexts.back().Context) {
16594     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16595       // -- a manifestly constant-evaluated expression,
16596     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16597     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16598     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16599       // -- a potentially-evaluated expression,
16600     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16601       // -- an immediate subexpression of a braced-init-list,
16602 
16603       // -- [FIXME] an expression of the form & cast-expression that occurs
16604       //    within a templated entity
16605       // -- a subexpression of one of the above that is not a subexpression of
16606       // a nested unevaluated operand.
16607       return true;
16608 
16609     case Sema::ExpressionEvaluationContext::Unevaluated:
16610     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16611       // Expressions in this context are never evaluated.
16612       return false;
16613   }
16614   llvm_unreachable("Invalid context");
16615 }
16616 
16617 /// Return true if this function has a calling convention that requires mangling
16618 /// in the size of the parameter pack.
16619 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16620   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16621   // we don't need parameter type sizes.
16622   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16623   if (!TT.isOSWindows() || !TT.isX86())
16624     return false;
16625 
16626   // If this is C++ and this isn't an extern "C" function, parameters do not
16627   // need to be complete. In this case, C++ mangling will apply, which doesn't
16628   // use the size of the parameters.
16629   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16630     return false;
16631 
16632   // Stdcall, fastcall, and vectorcall need this special treatment.
16633   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16634   switch (CC) {
16635   case CC_X86StdCall:
16636   case CC_X86FastCall:
16637   case CC_X86VectorCall:
16638     return true;
16639   default:
16640     break;
16641   }
16642   return false;
16643 }
16644 
16645 /// Require that all of the parameter types of function be complete. Normally,
16646 /// parameter types are only required to be complete when a function is called
16647 /// or defined, but to mangle functions with certain calling conventions, the
16648 /// mangler needs to know the size of the parameter list. In this situation,
16649 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16650 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16651 /// result in a linker error. Clang doesn't implement this behavior, and instead
16652 /// attempts to error at compile time.
16653 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16654                                                   SourceLocation Loc) {
16655   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16656     FunctionDecl *FD;
16657     ParmVarDecl *Param;
16658 
16659   public:
16660     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16661         : FD(FD), Param(Param) {}
16662 
16663     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16664       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16665       StringRef CCName;
16666       switch (CC) {
16667       case CC_X86StdCall:
16668         CCName = "stdcall";
16669         break;
16670       case CC_X86FastCall:
16671         CCName = "fastcall";
16672         break;
16673       case CC_X86VectorCall:
16674         CCName = "vectorcall";
16675         break;
16676       default:
16677         llvm_unreachable("CC does not need mangling");
16678       }
16679 
16680       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16681           << Param->getDeclName() << FD->getDeclName() << CCName;
16682     }
16683   };
16684 
16685   for (ParmVarDecl *Param : FD->parameters()) {
16686     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16687     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16688   }
16689 }
16690 
16691 namespace {
16692 enum class OdrUseContext {
16693   /// Declarations in this context are not odr-used.
16694   None,
16695   /// Declarations in this context are formally odr-used, but this is a
16696   /// dependent context.
16697   Dependent,
16698   /// Declarations in this context are odr-used but not actually used (yet).
16699   FormallyOdrUsed,
16700   /// Declarations in this context are used.
16701   Used
16702 };
16703 }
16704 
16705 /// Are we within a context in which references to resolved functions or to
16706 /// variables result in odr-use?
16707 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16708   OdrUseContext Result;
16709 
16710   switch (SemaRef.ExprEvalContexts.back().Context) {
16711     case Sema::ExpressionEvaluationContext::Unevaluated:
16712     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16713     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16714       return OdrUseContext::None;
16715 
16716     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16717     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16718       Result = OdrUseContext::Used;
16719       break;
16720 
16721     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16722       Result = OdrUseContext::FormallyOdrUsed;
16723       break;
16724 
16725     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16726       // A default argument formally results in odr-use, but doesn't actually
16727       // result in a use in any real sense until it itself is used.
16728       Result = OdrUseContext::FormallyOdrUsed;
16729       break;
16730   }
16731 
16732   if (SemaRef.CurContext->isDependentContext())
16733     return OdrUseContext::Dependent;
16734 
16735   return Result;
16736 }
16737 
16738 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16739   if (!Func->isConstexpr())
16740     return false;
16741 
16742   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16743     return true;
16744   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16745   return CCD && CCD->getInheritedConstructor();
16746 }
16747 
16748 /// Mark a function referenced, and check whether it is odr-used
16749 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16750 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16751                                   bool MightBeOdrUse) {
16752   assert(Func && "No function?");
16753 
16754   Func->setReferenced();
16755 
16756   // Recursive functions aren't really used until they're used from some other
16757   // context.
16758   bool IsRecursiveCall = CurContext == Func;
16759 
16760   // C++11 [basic.def.odr]p3:
16761   //   A function whose name appears as a potentially-evaluated expression is
16762   //   odr-used if it is the unique lookup result or the selected member of a
16763   //   set of overloaded functions [...].
16764   //
16765   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16766   // can just check that here.
16767   OdrUseContext OdrUse =
16768       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16769   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16770     OdrUse = OdrUseContext::FormallyOdrUsed;
16771 
16772   // Trivial default constructors and destructors are never actually used.
16773   // FIXME: What about other special members?
16774   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16775       OdrUse == OdrUseContext::Used) {
16776     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16777       if (Constructor->isDefaultConstructor())
16778         OdrUse = OdrUseContext::FormallyOdrUsed;
16779     if (isa<CXXDestructorDecl>(Func))
16780       OdrUse = OdrUseContext::FormallyOdrUsed;
16781   }
16782 
16783   // C++20 [expr.const]p12:
16784   //   A function [...] is needed for constant evaluation if it is [...] a
16785   //   constexpr function that is named by an expression that is potentially
16786   //   constant evaluated
16787   bool NeededForConstantEvaluation =
16788       isPotentiallyConstantEvaluatedContext(*this) &&
16789       isImplicitlyDefinableConstexprFunction(Func);
16790 
16791   // Determine whether we require a function definition to exist, per
16792   // C++11 [temp.inst]p3:
16793   //   Unless a function template specialization has been explicitly
16794   //   instantiated or explicitly specialized, the function template
16795   //   specialization is implicitly instantiated when the specialization is
16796   //   referenced in a context that requires a function definition to exist.
16797   // C++20 [temp.inst]p7:
16798   //   The existence of a definition of a [...] function is considered to
16799   //   affect the semantics of the program if the [...] function is needed for
16800   //   constant evaluation by an expression
16801   // C++20 [basic.def.odr]p10:
16802   //   Every program shall contain exactly one definition of every non-inline
16803   //   function or variable that is odr-used in that program outside of a
16804   //   discarded statement
16805   // C++20 [special]p1:
16806   //   The implementation will implicitly define [defaulted special members]
16807   //   if they are odr-used or needed for constant evaluation.
16808   //
16809   // Note that we skip the implicit instantiation of templates that are only
16810   // used in unused default arguments or by recursive calls to themselves.
16811   // This is formally non-conforming, but seems reasonable in practice.
16812   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16813                                              NeededForConstantEvaluation);
16814 
16815   // C++14 [temp.expl.spec]p6:
16816   //   If a template [...] is explicitly specialized then that specialization
16817   //   shall be declared before the first use of that specialization that would
16818   //   cause an implicit instantiation to take place, in every translation unit
16819   //   in which such a use occurs
16820   if (NeedDefinition &&
16821       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16822        Func->getMemberSpecializationInfo()))
16823     checkSpecializationVisibility(Loc, Func);
16824 
16825   if (getLangOpts().CUDA)
16826     CheckCUDACall(Loc, Func);
16827 
16828   if (getLangOpts().SYCLIsDevice)
16829     checkSYCLDeviceFunction(Loc, Func);
16830 
16831   // If we need a definition, try to create one.
16832   if (NeedDefinition && !Func->getBody()) {
16833     runWithSufficientStackSpace(Loc, [&] {
16834       if (CXXConstructorDecl *Constructor =
16835               dyn_cast<CXXConstructorDecl>(Func)) {
16836         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16837         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16838           if (Constructor->isDefaultConstructor()) {
16839             if (Constructor->isTrivial() &&
16840                 !Constructor->hasAttr<DLLExportAttr>())
16841               return;
16842             DefineImplicitDefaultConstructor(Loc, Constructor);
16843           } else if (Constructor->isCopyConstructor()) {
16844             DefineImplicitCopyConstructor(Loc, Constructor);
16845           } else if (Constructor->isMoveConstructor()) {
16846             DefineImplicitMoveConstructor(Loc, Constructor);
16847           }
16848         } else if (Constructor->getInheritedConstructor()) {
16849           DefineInheritingConstructor(Loc, Constructor);
16850         }
16851       } else if (CXXDestructorDecl *Destructor =
16852                      dyn_cast<CXXDestructorDecl>(Func)) {
16853         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16854         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16855           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16856             return;
16857           DefineImplicitDestructor(Loc, Destructor);
16858         }
16859         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16860           MarkVTableUsed(Loc, Destructor->getParent());
16861       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16862         if (MethodDecl->isOverloadedOperator() &&
16863             MethodDecl->getOverloadedOperator() == OO_Equal) {
16864           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16865           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16866             if (MethodDecl->isCopyAssignmentOperator())
16867               DefineImplicitCopyAssignment(Loc, MethodDecl);
16868             else if (MethodDecl->isMoveAssignmentOperator())
16869               DefineImplicitMoveAssignment(Loc, MethodDecl);
16870           }
16871         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16872                    MethodDecl->getParent()->isLambda()) {
16873           CXXConversionDecl *Conversion =
16874               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16875           if (Conversion->isLambdaToBlockPointerConversion())
16876             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16877           else
16878             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16879         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16880           MarkVTableUsed(Loc, MethodDecl->getParent());
16881       }
16882 
16883       if (Func->isDefaulted() && !Func->isDeleted()) {
16884         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16885         if (DCK != DefaultedComparisonKind::None)
16886           DefineDefaultedComparison(Loc, Func, DCK);
16887       }
16888 
16889       // Implicit instantiation of function templates and member functions of
16890       // class templates.
16891       if (Func->isImplicitlyInstantiable()) {
16892         TemplateSpecializationKind TSK =
16893             Func->getTemplateSpecializationKindForInstantiation();
16894         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16895         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16896         if (FirstInstantiation) {
16897           PointOfInstantiation = Loc;
16898           if (auto *MSI = Func->getMemberSpecializationInfo())
16899             MSI->setPointOfInstantiation(Loc);
16900             // FIXME: Notify listener.
16901           else
16902             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16903         } else if (TSK != TSK_ImplicitInstantiation) {
16904           // Use the point of use as the point of instantiation, instead of the
16905           // point of explicit instantiation (which we track as the actual point
16906           // of instantiation). This gives better backtraces in diagnostics.
16907           PointOfInstantiation = Loc;
16908         }
16909 
16910         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16911             Func->isConstexpr()) {
16912           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16913               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16914               CodeSynthesisContexts.size())
16915             PendingLocalImplicitInstantiations.push_back(
16916                 std::make_pair(Func, PointOfInstantiation));
16917           else if (Func->isConstexpr())
16918             // Do not defer instantiations of constexpr functions, to avoid the
16919             // expression evaluator needing to call back into Sema if it sees a
16920             // call to such a function.
16921             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16922           else {
16923             Func->setInstantiationIsPending(true);
16924             PendingInstantiations.push_back(
16925                 std::make_pair(Func, PointOfInstantiation));
16926             // Notify the consumer that a function was implicitly instantiated.
16927             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16928           }
16929         }
16930       } else {
16931         // Walk redefinitions, as some of them may be instantiable.
16932         for (auto i : Func->redecls()) {
16933           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16934             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16935         }
16936       }
16937     });
16938   }
16939 
16940   // C++14 [except.spec]p17:
16941   //   An exception-specification is considered to be needed when:
16942   //   - the function is odr-used or, if it appears in an unevaluated operand,
16943   //     would be odr-used if the expression were potentially-evaluated;
16944   //
16945   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16946   // function is a pure virtual function we're calling, and in that case the
16947   // function was selected by overload resolution and we need to resolve its
16948   // exception specification for a different reason.
16949   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16950   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16951     ResolveExceptionSpec(Loc, FPT);
16952 
16953   // If this is the first "real" use, act on that.
16954   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16955     // Keep track of used but undefined functions.
16956     if (!Func->isDefined()) {
16957       if (mightHaveNonExternalLinkage(Func))
16958         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16959       else if (Func->getMostRecentDecl()->isInlined() &&
16960                !LangOpts.GNUInline &&
16961                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16962         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16963       else if (isExternalWithNoLinkageType(Func))
16964         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16965     }
16966 
16967     // Some x86 Windows calling conventions mangle the size of the parameter
16968     // pack into the name. Computing the size of the parameters requires the
16969     // parameter types to be complete. Check that now.
16970     if (funcHasParameterSizeMangling(*this, Func))
16971       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16972 
16973     // In the MS C++ ABI, the compiler emits destructor variants where they are
16974     // used. If the destructor is used here but defined elsewhere, mark the
16975     // virtual base destructors referenced. If those virtual base destructors
16976     // are inline, this will ensure they are defined when emitting the complete
16977     // destructor variant. This checking may be redundant if the destructor is
16978     // provided later in this TU.
16979     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16980       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16981         CXXRecordDecl *Parent = Dtor->getParent();
16982         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16983           CheckCompleteDestructorVariant(Loc, Dtor);
16984       }
16985     }
16986 
16987     Func->markUsed(Context);
16988   }
16989 }
16990 
16991 /// Directly mark a variable odr-used. Given a choice, prefer to use
16992 /// MarkVariableReferenced since it does additional checks and then
16993 /// calls MarkVarDeclODRUsed.
16994 /// If the variable must be captured:
16995 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16996 ///  - else capture it in the DeclContext that maps to the
16997 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16998 static void
16999 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17000                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17001   // Keep track of used but undefined variables.
17002   // FIXME: We shouldn't suppress this warning for static data members.
17003   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17004       (!Var->isExternallyVisible() || Var->isInline() ||
17005        SemaRef.isExternalWithNoLinkageType(Var)) &&
17006       !(Var->isStaticDataMember() && Var->hasInit())) {
17007     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17008     if (old.isInvalid())
17009       old = Loc;
17010   }
17011   QualType CaptureType, DeclRefType;
17012   if (SemaRef.LangOpts.OpenMP)
17013     SemaRef.tryCaptureOpenMPLambdas(Var);
17014   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17015     /*EllipsisLoc*/ SourceLocation(),
17016     /*BuildAndDiagnose*/ true,
17017     CaptureType, DeclRefType,
17018     FunctionScopeIndexToStopAt);
17019 
17020   Var->markUsed(SemaRef.Context);
17021 }
17022 
17023 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17024                                              SourceLocation Loc,
17025                                              unsigned CapturingScopeIndex) {
17026   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17027 }
17028 
17029 static void
17030 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17031                                    ValueDecl *var, DeclContext *DC) {
17032   DeclContext *VarDC = var->getDeclContext();
17033 
17034   //  If the parameter still belongs to the translation unit, then
17035   //  we're actually just using one parameter in the declaration of
17036   //  the next.
17037   if (isa<ParmVarDecl>(var) &&
17038       isa<TranslationUnitDecl>(VarDC))
17039     return;
17040 
17041   // For C code, don't diagnose about capture if we're not actually in code
17042   // right now; it's impossible to write a non-constant expression outside of
17043   // function context, so we'll get other (more useful) diagnostics later.
17044   //
17045   // For C++, things get a bit more nasty... it would be nice to suppress this
17046   // diagnostic for certain cases like using a local variable in an array bound
17047   // for a member of a local class, but the correct predicate is not obvious.
17048   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17049     return;
17050 
17051   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17052   unsigned ContextKind = 3; // unknown
17053   if (isa<CXXMethodDecl>(VarDC) &&
17054       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17055     ContextKind = 2;
17056   } else if (isa<FunctionDecl>(VarDC)) {
17057     ContextKind = 0;
17058   } else if (isa<BlockDecl>(VarDC)) {
17059     ContextKind = 1;
17060   }
17061 
17062   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17063     << var << ValueKind << ContextKind << VarDC;
17064   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17065       << var;
17066 
17067   // FIXME: Add additional diagnostic info about class etc. which prevents
17068   // capture.
17069 }
17070 
17071 
17072 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17073                                       bool &SubCapturesAreNested,
17074                                       QualType &CaptureType,
17075                                       QualType &DeclRefType) {
17076    // Check whether we've already captured it.
17077   if (CSI->CaptureMap.count(Var)) {
17078     // If we found a capture, any subcaptures are nested.
17079     SubCapturesAreNested = true;
17080 
17081     // Retrieve the capture type for this variable.
17082     CaptureType = CSI->getCapture(Var).getCaptureType();
17083 
17084     // Compute the type of an expression that refers to this variable.
17085     DeclRefType = CaptureType.getNonReferenceType();
17086 
17087     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17088     // are mutable in the sense that user can change their value - they are
17089     // private instances of the captured declarations.
17090     const Capture &Cap = CSI->getCapture(Var);
17091     if (Cap.isCopyCapture() &&
17092         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17093         !(isa<CapturedRegionScopeInfo>(CSI) &&
17094           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17095       DeclRefType.addConst();
17096     return true;
17097   }
17098   return false;
17099 }
17100 
17101 // Only block literals, captured statements, and lambda expressions can
17102 // capture; other scopes don't work.
17103 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17104                                  SourceLocation Loc,
17105                                  const bool Diagnose, Sema &S) {
17106   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17107     return getLambdaAwareParentOfDeclContext(DC);
17108   else if (Var->hasLocalStorage()) {
17109     if (Diagnose)
17110        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17111   }
17112   return nullptr;
17113 }
17114 
17115 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17116 // certain types of variables (unnamed, variably modified types etc.)
17117 // so check for eligibility.
17118 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17119                                  SourceLocation Loc,
17120                                  const bool Diagnose, Sema &S) {
17121 
17122   bool IsBlock = isa<BlockScopeInfo>(CSI);
17123   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17124 
17125   // Lambdas are not allowed to capture unnamed variables
17126   // (e.g. anonymous unions).
17127   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17128   // assuming that's the intent.
17129   if (IsLambda && !Var->getDeclName()) {
17130     if (Diagnose) {
17131       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17132       S.Diag(Var->getLocation(), diag::note_declared_at);
17133     }
17134     return false;
17135   }
17136 
17137   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17138   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17139     if (Diagnose) {
17140       S.Diag(Loc, diag::err_ref_vm_type);
17141       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17142     }
17143     return false;
17144   }
17145   // Prohibit structs with flexible array members too.
17146   // We cannot capture what is in the tail end of the struct.
17147   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17148     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17149       if (Diagnose) {
17150         if (IsBlock)
17151           S.Diag(Loc, diag::err_ref_flexarray_type);
17152         else
17153           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17154         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17155       }
17156       return false;
17157     }
17158   }
17159   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17160   // Lambdas and captured statements are not allowed to capture __block
17161   // variables; they don't support the expected semantics.
17162   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17163     if (Diagnose) {
17164       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17165       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17166     }
17167     return false;
17168   }
17169   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17170   if (S.getLangOpts().OpenCL && IsBlock &&
17171       Var->getType()->isBlockPointerType()) {
17172     if (Diagnose)
17173       S.Diag(Loc, diag::err_opencl_block_ref_block);
17174     return false;
17175   }
17176 
17177   return true;
17178 }
17179 
17180 // Returns true if the capture by block was successful.
17181 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17182                                  SourceLocation Loc,
17183                                  const bool BuildAndDiagnose,
17184                                  QualType &CaptureType,
17185                                  QualType &DeclRefType,
17186                                  const bool Nested,
17187                                  Sema &S, bool Invalid) {
17188   bool ByRef = false;
17189 
17190   // Blocks are not allowed to capture arrays, excepting OpenCL.
17191   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17192   // (decayed to pointers).
17193   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17194     if (BuildAndDiagnose) {
17195       S.Diag(Loc, diag::err_ref_array_type);
17196       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17197       Invalid = true;
17198     } else {
17199       return false;
17200     }
17201   }
17202 
17203   // Forbid the block-capture of autoreleasing variables.
17204   if (!Invalid &&
17205       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17206     if (BuildAndDiagnose) {
17207       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17208         << /*block*/ 0;
17209       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17210       Invalid = true;
17211     } else {
17212       return false;
17213     }
17214   }
17215 
17216   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17217   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17218     QualType PointeeTy = PT->getPointeeType();
17219 
17220     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17221         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17222         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17223       if (BuildAndDiagnose) {
17224         SourceLocation VarLoc = Var->getLocation();
17225         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17226         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17227       }
17228     }
17229   }
17230 
17231   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17232   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17233       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17234     // Block capture by reference does not change the capture or
17235     // declaration reference types.
17236     ByRef = true;
17237   } else {
17238     // Block capture by copy introduces 'const'.
17239     CaptureType = CaptureType.getNonReferenceType().withConst();
17240     DeclRefType = CaptureType;
17241   }
17242 
17243   // Actually capture the variable.
17244   if (BuildAndDiagnose)
17245     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17246                     CaptureType, Invalid);
17247 
17248   return !Invalid;
17249 }
17250 
17251 
17252 /// Capture the given variable in the captured region.
17253 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17254                                     VarDecl *Var,
17255                                     SourceLocation Loc,
17256                                     const bool BuildAndDiagnose,
17257                                     QualType &CaptureType,
17258                                     QualType &DeclRefType,
17259                                     const bool RefersToCapturedVariable,
17260                                     Sema &S, bool Invalid) {
17261   // By default, capture variables by reference.
17262   bool ByRef = true;
17263   // Using an LValue reference type is consistent with Lambdas (see below).
17264   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17265     if (S.isOpenMPCapturedDecl(Var)) {
17266       bool HasConst = DeclRefType.isConstQualified();
17267       DeclRefType = DeclRefType.getUnqualifiedType();
17268       // Don't lose diagnostics about assignments to const.
17269       if (HasConst)
17270         DeclRefType.addConst();
17271     }
17272     // Do not capture firstprivates in tasks.
17273     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17274         OMPC_unknown)
17275       return true;
17276     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17277                                     RSI->OpenMPCaptureLevel);
17278   }
17279 
17280   if (ByRef)
17281     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17282   else
17283     CaptureType = DeclRefType;
17284 
17285   // Actually capture the variable.
17286   if (BuildAndDiagnose)
17287     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17288                     Loc, SourceLocation(), CaptureType, Invalid);
17289 
17290   return !Invalid;
17291 }
17292 
17293 /// Capture the given variable in the lambda.
17294 static bool captureInLambda(LambdaScopeInfo *LSI,
17295                             VarDecl *Var,
17296                             SourceLocation Loc,
17297                             const bool BuildAndDiagnose,
17298                             QualType &CaptureType,
17299                             QualType &DeclRefType,
17300                             const bool RefersToCapturedVariable,
17301                             const Sema::TryCaptureKind Kind,
17302                             SourceLocation EllipsisLoc,
17303                             const bool IsTopScope,
17304                             Sema &S, bool Invalid) {
17305   // Determine whether we are capturing by reference or by value.
17306   bool ByRef = false;
17307   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17308     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17309   } else {
17310     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17311   }
17312 
17313   // Compute the type of the field that will capture this variable.
17314   if (ByRef) {
17315     // C++11 [expr.prim.lambda]p15:
17316     //   An entity is captured by reference if it is implicitly or
17317     //   explicitly captured but not captured by copy. It is
17318     //   unspecified whether additional unnamed non-static data
17319     //   members are declared in the closure type for entities
17320     //   captured by reference.
17321     //
17322     // FIXME: It is not clear whether we want to build an lvalue reference
17323     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17324     // to do the former, while EDG does the latter. Core issue 1249 will
17325     // clarify, but for now we follow GCC because it's a more permissive and
17326     // easily defensible position.
17327     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17328   } else {
17329     // C++11 [expr.prim.lambda]p14:
17330     //   For each entity captured by copy, an unnamed non-static
17331     //   data member is declared in the closure type. The
17332     //   declaration order of these members is unspecified. The type
17333     //   of such a data member is the type of the corresponding
17334     //   captured entity if the entity is not a reference to an
17335     //   object, or the referenced type otherwise. [Note: If the
17336     //   captured entity is a reference to a function, the
17337     //   corresponding data member is also a reference to a
17338     //   function. - end note ]
17339     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17340       if (!RefType->getPointeeType()->isFunctionType())
17341         CaptureType = RefType->getPointeeType();
17342     }
17343 
17344     // Forbid the lambda copy-capture of autoreleasing variables.
17345     if (!Invalid &&
17346         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17347       if (BuildAndDiagnose) {
17348         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17349         S.Diag(Var->getLocation(), diag::note_previous_decl)
17350           << Var->getDeclName();
17351         Invalid = true;
17352       } else {
17353         return false;
17354       }
17355     }
17356 
17357     // Make sure that by-copy captures are of a complete and non-abstract type.
17358     if (!Invalid && BuildAndDiagnose) {
17359       if (!CaptureType->isDependentType() &&
17360           S.RequireCompleteSizedType(
17361               Loc, CaptureType,
17362               diag::err_capture_of_incomplete_or_sizeless_type,
17363               Var->getDeclName()))
17364         Invalid = true;
17365       else if (S.RequireNonAbstractType(Loc, CaptureType,
17366                                         diag::err_capture_of_abstract_type))
17367         Invalid = true;
17368     }
17369   }
17370 
17371   // Compute the type of a reference to this captured variable.
17372   if (ByRef)
17373     DeclRefType = CaptureType.getNonReferenceType();
17374   else {
17375     // C++ [expr.prim.lambda]p5:
17376     //   The closure type for a lambda-expression has a public inline
17377     //   function call operator [...]. This function call operator is
17378     //   declared const (9.3.1) if and only if the lambda-expression's
17379     //   parameter-declaration-clause is not followed by mutable.
17380     DeclRefType = CaptureType.getNonReferenceType();
17381     if (!LSI->Mutable && !CaptureType->isReferenceType())
17382       DeclRefType.addConst();
17383   }
17384 
17385   // Add the capture.
17386   if (BuildAndDiagnose)
17387     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17388                     Loc, EllipsisLoc, CaptureType, Invalid);
17389 
17390   return !Invalid;
17391 }
17392 
17393 bool Sema::tryCaptureVariable(
17394     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17395     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17396     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17397   // An init-capture is notionally from the context surrounding its
17398   // declaration, but its parent DC is the lambda class.
17399   DeclContext *VarDC = Var->getDeclContext();
17400   if (Var->isInitCapture())
17401     VarDC = VarDC->getParent();
17402 
17403   DeclContext *DC = CurContext;
17404   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17405       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17406   // We need to sync up the Declaration Context with the
17407   // FunctionScopeIndexToStopAt
17408   if (FunctionScopeIndexToStopAt) {
17409     unsigned FSIndex = FunctionScopes.size() - 1;
17410     while (FSIndex != MaxFunctionScopesIndex) {
17411       DC = getLambdaAwareParentOfDeclContext(DC);
17412       --FSIndex;
17413     }
17414   }
17415 
17416 
17417   // If the variable is declared in the current context, there is no need to
17418   // capture it.
17419   if (VarDC == DC) return true;
17420 
17421   // Capture global variables if it is required to use private copy of this
17422   // variable.
17423   bool IsGlobal = !Var->hasLocalStorage();
17424   if (IsGlobal &&
17425       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17426                                                 MaxFunctionScopesIndex)))
17427     return true;
17428   Var = Var->getCanonicalDecl();
17429 
17430   // Walk up the stack to determine whether we can capture the variable,
17431   // performing the "simple" checks that don't depend on type. We stop when
17432   // we've either hit the declared scope of the variable or find an existing
17433   // capture of that variable.  We start from the innermost capturing-entity
17434   // (the DC) and ensure that all intervening capturing-entities
17435   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17436   // declcontext can either capture the variable or have already captured
17437   // the variable.
17438   CaptureType = Var->getType();
17439   DeclRefType = CaptureType.getNonReferenceType();
17440   bool Nested = false;
17441   bool Explicit = (Kind != TryCapture_Implicit);
17442   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17443   do {
17444     // Only block literals, captured statements, and lambda expressions can
17445     // capture; other scopes don't work.
17446     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17447                                                               ExprLoc,
17448                                                               BuildAndDiagnose,
17449                                                               *this);
17450     // We need to check for the parent *first* because, if we *have*
17451     // private-captured a global variable, we need to recursively capture it in
17452     // intermediate blocks, lambdas, etc.
17453     if (!ParentDC) {
17454       if (IsGlobal) {
17455         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17456         break;
17457       }
17458       return true;
17459     }
17460 
17461     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17462     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17463 
17464 
17465     // Check whether we've already captured it.
17466     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17467                                              DeclRefType)) {
17468       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17469       break;
17470     }
17471     // If we are instantiating a generic lambda call operator body,
17472     // we do not want to capture new variables.  What was captured
17473     // during either a lambdas transformation or initial parsing
17474     // should be used.
17475     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17476       if (BuildAndDiagnose) {
17477         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17478         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17479           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17480           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17481           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17482         } else
17483           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17484       }
17485       return true;
17486     }
17487 
17488     // Try to capture variable-length arrays types.
17489     if (Var->getType()->isVariablyModifiedType()) {
17490       // We're going to walk down into the type and look for VLA
17491       // expressions.
17492       QualType QTy = Var->getType();
17493       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17494         QTy = PVD->getOriginalType();
17495       captureVariablyModifiedType(Context, QTy, CSI);
17496     }
17497 
17498     if (getLangOpts().OpenMP) {
17499       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17500         // OpenMP private variables should not be captured in outer scope, so
17501         // just break here. Similarly, global variables that are captured in a
17502         // target region should not be captured outside the scope of the region.
17503         if (RSI->CapRegionKind == CR_OpenMP) {
17504           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17505               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17506           // If the variable is private (i.e. not captured) and has variably
17507           // modified type, we still need to capture the type for correct
17508           // codegen in all regions, associated with the construct. Currently,
17509           // it is captured in the innermost captured region only.
17510           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17511               Var->getType()->isVariablyModifiedType()) {
17512             QualType QTy = Var->getType();
17513             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17514               QTy = PVD->getOriginalType();
17515             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17516                  I < E; ++I) {
17517               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17518                   FunctionScopes[FunctionScopesIndex - I]);
17519               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17520                      "Wrong number of captured regions associated with the "
17521                      "OpenMP construct.");
17522               captureVariablyModifiedType(Context, QTy, OuterRSI);
17523             }
17524           }
17525           bool IsTargetCap =
17526               IsOpenMPPrivateDecl != OMPC_private &&
17527               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17528                                          RSI->OpenMPCaptureLevel);
17529           // Do not capture global if it is not privatized in outer regions.
17530           bool IsGlobalCap =
17531               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17532                                                      RSI->OpenMPCaptureLevel);
17533 
17534           // When we detect target captures we are looking from inside the
17535           // target region, therefore we need to propagate the capture from the
17536           // enclosing region. Therefore, the capture is not initially nested.
17537           if (IsTargetCap)
17538             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17539 
17540           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17541               (IsGlobal && !IsGlobalCap)) {
17542             Nested = !IsTargetCap;
17543             bool HasConst = DeclRefType.isConstQualified();
17544             DeclRefType = DeclRefType.getUnqualifiedType();
17545             // Don't lose diagnostics about assignments to const.
17546             if (HasConst)
17547               DeclRefType.addConst();
17548             CaptureType = Context.getLValueReferenceType(DeclRefType);
17549             break;
17550           }
17551         }
17552       }
17553     }
17554     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17555       // No capture-default, and this is not an explicit capture
17556       // so cannot capture this variable.
17557       if (BuildAndDiagnose) {
17558         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17559         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17560         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17561           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17562                diag::note_lambda_decl);
17563         // FIXME: If we error out because an outer lambda can not implicitly
17564         // capture a variable that an inner lambda explicitly captures, we
17565         // should have the inner lambda do the explicit capture - because
17566         // it makes for cleaner diagnostics later.  This would purely be done
17567         // so that the diagnostic does not misleadingly claim that a variable
17568         // can not be captured by a lambda implicitly even though it is captured
17569         // explicitly.  Suggestion:
17570         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17571         //    at the function head
17572         //  - cache the StartingDeclContext - this must be a lambda
17573         //  - captureInLambda in the innermost lambda the variable.
17574       }
17575       return true;
17576     }
17577 
17578     FunctionScopesIndex--;
17579     DC = ParentDC;
17580     Explicit = false;
17581   } while (!VarDC->Equals(DC));
17582 
17583   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17584   // computing the type of the capture at each step, checking type-specific
17585   // requirements, and adding captures if requested.
17586   // If the variable had already been captured previously, we start capturing
17587   // at the lambda nested within that one.
17588   bool Invalid = false;
17589   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17590        ++I) {
17591     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17592 
17593     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17594     // certain types of variables (unnamed, variably modified types etc.)
17595     // so check for eligibility.
17596     if (!Invalid)
17597       Invalid =
17598           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17599 
17600     // After encountering an error, if we're actually supposed to capture, keep
17601     // capturing in nested contexts to suppress any follow-on diagnostics.
17602     if (Invalid && !BuildAndDiagnose)
17603       return true;
17604 
17605     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17606       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17607                                DeclRefType, Nested, *this, Invalid);
17608       Nested = true;
17609     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17610       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17611                                          CaptureType, DeclRefType, Nested,
17612                                          *this, Invalid);
17613       Nested = true;
17614     } else {
17615       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17616       Invalid =
17617           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17618                            DeclRefType, Nested, Kind, EllipsisLoc,
17619                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17620       Nested = true;
17621     }
17622 
17623     if (Invalid && !BuildAndDiagnose)
17624       return true;
17625   }
17626   return Invalid;
17627 }
17628 
17629 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17630                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17631   QualType CaptureType;
17632   QualType DeclRefType;
17633   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17634                             /*BuildAndDiagnose=*/true, CaptureType,
17635                             DeclRefType, nullptr);
17636 }
17637 
17638 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17639   QualType CaptureType;
17640   QualType DeclRefType;
17641   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17642                              /*BuildAndDiagnose=*/false, CaptureType,
17643                              DeclRefType, nullptr);
17644 }
17645 
17646 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17647   QualType CaptureType;
17648   QualType DeclRefType;
17649 
17650   // Determine whether we can capture this variable.
17651   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17652                          /*BuildAndDiagnose=*/false, CaptureType,
17653                          DeclRefType, nullptr))
17654     return QualType();
17655 
17656   return DeclRefType;
17657 }
17658 
17659 namespace {
17660 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17661 // The produced TemplateArgumentListInfo* points to data stored within this
17662 // object, so should only be used in contexts where the pointer will not be
17663 // used after the CopiedTemplateArgs object is destroyed.
17664 class CopiedTemplateArgs {
17665   bool HasArgs;
17666   TemplateArgumentListInfo TemplateArgStorage;
17667 public:
17668   template<typename RefExpr>
17669   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17670     if (HasArgs)
17671       E->copyTemplateArgumentsInto(TemplateArgStorage);
17672   }
17673   operator TemplateArgumentListInfo*()
17674 #ifdef __has_cpp_attribute
17675 #if __has_cpp_attribute(clang::lifetimebound)
17676   [[clang::lifetimebound]]
17677 #endif
17678 #endif
17679   {
17680     return HasArgs ? &TemplateArgStorage : nullptr;
17681   }
17682 };
17683 }
17684 
17685 /// Walk the set of potential results of an expression and mark them all as
17686 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17687 ///
17688 /// \return A new expression if we found any potential results, ExprEmpty() if
17689 ///         not, and ExprError() if we diagnosed an error.
17690 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17691                                                       NonOdrUseReason NOUR) {
17692   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17693   // an object that satisfies the requirements for appearing in a
17694   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17695   // is immediately applied."  This function handles the lvalue-to-rvalue
17696   // conversion part.
17697   //
17698   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17699   // transform it into the relevant kind of non-odr-use node and rebuild the
17700   // tree of nodes leading to it.
17701   //
17702   // This is a mini-TreeTransform that only transforms a restricted subset of
17703   // nodes (and only certain operands of them).
17704 
17705   // Rebuild a subexpression.
17706   auto Rebuild = [&](Expr *Sub) {
17707     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17708   };
17709 
17710   // Check whether a potential result satisfies the requirements of NOUR.
17711   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17712     // Any entity other than a VarDecl is always odr-used whenever it's named
17713     // in a potentially-evaluated expression.
17714     auto *VD = dyn_cast<VarDecl>(D);
17715     if (!VD)
17716       return true;
17717 
17718     // C++2a [basic.def.odr]p4:
17719     //   A variable x whose name appears as a potentially-evalauted expression
17720     //   e is odr-used by e unless
17721     //   -- x is a reference that is usable in constant expressions, or
17722     //   -- x is a variable of non-reference type that is usable in constant
17723     //      expressions and has no mutable subobjects, and e is an element of
17724     //      the set of potential results of an expression of
17725     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17726     //      conversion is applied, or
17727     //   -- x is a variable of non-reference type, and e is an element of the
17728     //      set of potential results of a discarded-value expression to which
17729     //      the lvalue-to-rvalue conversion is not applied
17730     //
17731     // We check the first bullet and the "potentially-evaluated" condition in
17732     // BuildDeclRefExpr. We check the type requirements in the second bullet
17733     // in CheckLValueToRValueConversionOperand below.
17734     switch (NOUR) {
17735     case NOUR_None:
17736     case NOUR_Unevaluated:
17737       llvm_unreachable("unexpected non-odr-use-reason");
17738 
17739     case NOUR_Constant:
17740       // Constant references were handled when they were built.
17741       if (VD->getType()->isReferenceType())
17742         return true;
17743       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17744         if (RD->hasMutableFields())
17745           return true;
17746       if (!VD->isUsableInConstantExpressions(S.Context))
17747         return true;
17748       break;
17749 
17750     case NOUR_Discarded:
17751       if (VD->getType()->isReferenceType())
17752         return true;
17753       break;
17754     }
17755     return false;
17756   };
17757 
17758   // Mark that this expression does not constitute an odr-use.
17759   auto MarkNotOdrUsed = [&] {
17760     S.MaybeODRUseExprs.remove(E);
17761     if (LambdaScopeInfo *LSI = S.getCurLambda())
17762       LSI->markVariableExprAsNonODRUsed(E);
17763   };
17764 
17765   // C++2a [basic.def.odr]p2:
17766   //   The set of potential results of an expression e is defined as follows:
17767   switch (E->getStmtClass()) {
17768   //   -- If e is an id-expression, ...
17769   case Expr::DeclRefExprClass: {
17770     auto *DRE = cast<DeclRefExpr>(E);
17771     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17772       break;
17773 
17774     // Rebuild as a non-odr-use DeclRefExpr.
17775     MarkNotOdrUsed();
17776     return DeclRefExpr::Create(
17777         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17778         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17779         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17780         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17781   }
17782 
17783   case Expr::FunctionParmPackExprClass: {
17784     auto *FPPE = cast<FunctionParmPackExpr>(E);
17785     // If any of the declarations in the pack is odr-used, then the expression
17786     // as a whole constitutes an odr-use.
17787     for (VarDecl *D : *FPPE)
17788       if (IsPotentialResultOdrUsed(D))
17789         return ExprEmpty();
17790 
17791     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17792     // nothing cares about whether we marked this as an odr-use, but it might
17793     // be useful for non-compiler tools.
17794     MarkNotOdrUsed();
17795     break;
17796   }
17797 
17798   //   -- If e is a subscripting operation with an array operand...
17799   case Expr::ArraySubscriptExprClass: {
17800     auto *ASE = cast<ArraySubscriptExpr>(E);
17801     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17802     if (!OldBase->getType()->isArrayType())
17803       break;
17804     ExprResult Base = Rebuild(OldBase);
17805     if (!Base.isUsable())
17806       return Base;
17807     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17808     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17809     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17810     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17811                                      ASE->getRBracketLoc());
17812   }
17813 
17814   case Expr::MemberExprClass: {
17815     auto *ME = cast<MemberExpr>(E);
17816     // -- If e is a class member access expression [...] naming a non-static
17817     //    data member...
17818     if (isa<FieldDecl>(ME->getMemberDecl())) {
17819       ExprResult Base = Rebuild(ME->getBase());
17820       if (!Base.isUsable())
17821         return Base;
17822       return MemberExpr::Create(
17823           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17824           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17825           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17826           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17827           ME->getObjectKind(), ME->isNonOdrUse());
17828     }
17829 
17830     if (ME->getMemberDecl()->isCXXInstanceMember())
17831       break;
17832 
17833     // -- If e is a class member access expression naming a static data member,
17834     //    ...
17835     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17836       break;
17837 
17838     // Rebuild as a non-odr-use MemberExpr.
17839     MarkNotOdrUsed();
17840     return MemberExpr::Create(
17841         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17842         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17843         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17844         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17845     return ExprEmpty();
17846   }
17847 
17848   case Expr::BinaryOperatorClass: {
17849     auto *BO = cast<BinaryOperator>(E);
17850     Expr *LHS = BO->getLHS();
17851     Expr *RHS = BO->getRHS();
17852     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17853     if (BO->getOpcode() == BO_PtrMemD) {
17854       ExprResult Sub = Rebuild(LHS);
17855       if (!Sub.isUsable())
17856         return Sub;
17857       LHS = Sub.get();
17858     //   -- If e is a comma expression, ...
17859     } else if (BO->getOpcode() == BO_Comma) {
17860       ExprResult Sub = Rebuild(RHS);
17861       if (!Sub.isUsable())
17862         return Sub;
17863       RHS = Sub.get();
17864     } else {
17865       break;
17866     }
17867     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17868                         LHS, RHS);
17869   }
17870 
17871   //   -- If e has the form (e1)...
17872   case Expr::ParenExprClass: {
17873     auto *PE = cast<ParenExpr>(E);
17874     ExprResult Sub = Rebuild(PE->getSubExpr());
17875     if (!Sub.isUsable())
17876       return Sub;
17877     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17878   }
17879 
17880   //   -- If e is a glvalue conditional expression, ...
17881   // We don't apply this to a binary conditional operator. FIXME: Should we?
17882   case Expr::ConditionalOperatorClass: {
17883     auto *CO = cast<ConditionalOperator>(E);
17884     ExprResult LHS = Rebuild(CO->getLHS());
17885     if (LHS.isInvalid())
17886       return ExprError();
17887     ExprResult RHS = Rebuild(CO->getRHS());
17888     if (RHS.isInvalid())
17889       return ExprError();
17890     if (!LHS.isUsable() && !RHS.isUsable())
17891       return ExprEmpty();
17892     if (!LHS.isUsable())
17893       LHS = CO->getLHS();
17894     if (!RHS.isUsable())
17895       RHS = CO->getRHS();
17896     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17897                                 CO->getCond(), LHS.get(), RHS.get());
17898   }
17899 
17900   // [Clang extension]
17901   //   -- If e has the form __extension__ e1...
17902   case Expr::UnaryOperatorClass: {
17903     auto *UO = cast<UnaryOperator>(E);
17904     if (UO->getOpcode() != UO_Extension)
17905       break;
17906     ExprResult Sub = Rebuild(UO->getSubExpr());
17907     if (!Sub.isUsable())
17908       return Sub;
17909     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17910                           Sub.get());
17911   }
17912 
17913   // [Clang extension]
17914   //   -- If e has the form _Generic(...), the set of potential results is the
17915   //      union of the sets of potential results of the associated expressions.
17916   case Expr::GenericSelectionExprClass: {
17917     auto *GSE = cast<GenericSelectionExpr>(E);
17918 
17919     SmallVector<Expr *, 4> AssocExprs;
17920     bool AnyChanged = false;
17921     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17922       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17923       if (AssocExpr.isInvalid())
17924         return ExprError();
17925       if (AssocExpr.isUsable()) {
17926         AssocExprs.push_back(AssocExpr.get());
17927         AnyChanged = true;
17928       } else {
17929         AssocExprs.push_back(OrigAssocExpr);
17930       }
17931     }
17932 
17933     return AnyChanged ? S.CreateGenericSelectionExpr(
17934                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17935                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17936                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17937                       : ExprEmpty();
17938   }
17939 
17940   // [Clang extension]
17941   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17942   //      results is the union of the sets of potential results of the
17943   //      second and third subexpressions.
17944   case Expr::ChooseExprClass: {
17945     auto *CE = cast<ChooseExpr>(E);
17946 
17947     ExprResult LHS = Rebuild(CE->getLHS());
17948     if (LHS.isInvalid())
17949       return ExprError();
17950 
17951     ExprResult RHS = Rebuild(CE->getLHS());
17952     if (RHS.isInvalid())
17953       return ExprError();
17954 
17955     if (!LHS.get() && !RHS.get())
17956       return ExprEmpty();
17957     if (!LHS.isUsable())
17958       LHS = CE->getLHS();
17959     if (!RHS.isUsable())
17960       RHS = CE->getRHS();
17961 
17962     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17963                              RHS.get(), CE->getRParenLoc());
17964   }
17965 
17966   // Step through non-syntactic nodes.
17967   case Expr::ConstantExprClass: {
17968     auto *CE = cast<ConstantExpr>(E);
17969     ExprResult Sub = Rebuild(CE->getSubExpr());
17970     if (!Sub.isUsable())
17971       return Sub;
17972     return ConstantExpr::Create(S.Context, Sub.get());
17973   }
17974 
17975   // We could mostly rely on the recursive rebuilding to rebuild implicit
17976   // casts, but not at the top level, so rebuild them here.
17977   case Expr::ImplicitCastExprClass: {
17978     auto *ICE = cast<ImplicitCastExpr>(E);
17979     // Only step through the narrow set of cast kinds we expect to encounter.
17980     // Anything else suggests we've left the region in which potential results
17981     // can be found.
17982     switch (ICE->getCastKind()) {
17983     case CK_NoOp:
17984     case CK_DerivedToBase:
17985     case CK_UncheckedDerivedToBase: {
17986       ExprResult Sub = Rebuild(ICE->getSubExpr());
17987       if (!Sub.isUsable())
17988         return Sub;
17989       CXXCastPath Path(ICE->path());
17990       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17991                                  ICE->getValueKind(), &Path);
17992     }
17993 
17994     default:
17995       break;
17996     }
17997     break;
17998   }
17999 
18000   default:
18001     break;
18002   }
18003 
18004   // Can't traverse through this node. Nothing to do.
18005   return ExprEmpty();
18006 }
18007 
18008 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18009   // Check whether the operand is or contains an object of non-trivial C union
18010   // type.
18011   if (E->getType().isVolatileQualified() &&
18012       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18013        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18014     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18015                           Sema::NTCUC_LValueToRValueVolatile,
18016                           NTCUK_Destruct|NTCUK_Copy);
18017 
18018   // C++2a [basic.def.odr]p4:
18019   //   [...] an expression of non-volatile-qualified non-class type to which
18020   //   the lvalue-to-rvalue conversion is applied [...]
18021   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18022     return E;
18023 
18024   ExprResult Result =
18025       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18026   if (Result.isInvalid())
18027     return ExprError();
18028   return Result.get() ? Result : E;
18029 }
18030 
18031 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18032   Res = CorrectDelayedTyposInExpr(Res);
18033 
18034   if (!Res.isUsable())
18035     return Res;
18036 
18037   // If a constant-expression is a reference to a variable where we delay
18038   // deciding whether it is an odr-use, just assume we will apply the
18039   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18040   // (a non-type template argument), we have special handling anyway.
18041   return CheckLValueToRValueConversionOperand(Res.get());
18042 }
18043 
18044 void Sema::CleanupVarDeclMarking() {
18045   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18046   // call.
18047   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18048   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18049 
18050   for (Expr *E : LocalMaybeODRUseExprs) {
18051     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18052       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18053                          DRE->getLocation(), *this);
18054     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18055       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18056                          *this);
18057     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18058       for (VarDecl *VD : *FP)
18059         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18060     } else {
18061       llvm_unreachable("Unexpected expression");
18062     }
18063   }
18064 
18065   assert(MaybeODRUseExprs.empty() &&
18066          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18067 }
18068 
18069 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18070                                     VarDecl *Var, Expr *E) {
18071   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18072           isa<FunctionParmPackExpr>(E)) &&
18073          "Invalid Expr argument to DoMarkVarDeclReferenced");
18074   Var->setReferenced();
18075 
18076   if (Var->isInvalidDecl())
18077     return;
18078 
18079   // Record a CUDA/HIP static device/constant variable if it is referenced
18080   // by host code. This is done conservatively, when the variable is referenced
18081   // in any of the following contexts:
18082   //   - a non-function context
18083   //   - a host function
18084   //   - a host device function
18085   // This also requires the reference of the static device/constant variable by
18086   // host code to be visible in the device compilation for the compiler to be
18087   // able to externalize the static device/constant variable.
18088   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18089     auto *CurContext = SemaRef.CurContext;
18090     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18091         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18092         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18093          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18094       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18095   }
18096 
18097   auto *MSI = Var->getMemberSpecializationInfo();
18098   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18099                                        : Var->getTemplateSpecializationKind();
18100 
18101   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18102   bool UsableInConstantExpr =
18103       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18104 
18105   // C++20 [expr.const]p12:
18106   //   A variable [...] is needed for constant evaluation if it is [...] a
18107   //   variable whose name appears as a potentially constant evaluated
18108   //   expression that is either a contexpr variable or is of non-volatile
18109   //   const-qualified integral type or of reference type
18110   bool NeededForConstantEvaluation =
18111       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18112 
18113   bool NeedDefinition =
18114       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18115 
18116   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18117          "Can't instantiate a partial template specialization.");
18118 
18119   // If this might be a member specialization of a static data member, check
18120   // the specialization is visible. We already did the checks for variable
18121   // template specializations when we created them.
18122   if (NeedDefinition && TSK != TSK_Undeclared &&
18123       !isa<VarTemplateSpecializationDecl>(Var))
18124     SemaRef.checkSpecializationVisibility(Loc, Var);
18125 
18126   // Perform implicit instantiation of static data members, static data member
18127   // templates of class templates, and variable template specializations. Delay
18128   // instantiations of variable templates, except for those that could be used
18129   // in a constant expression.
18130   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18131     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18132     // instantiation declaration if a variable is usable in a constant
18133     // expression (among other cases).
18134     bool TryInstantiating =
18135         TSK == TSK_ImplicitInstantiation ||
18136         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18137 
18138     if (TryInstantiating) {
18139       SourceLocation PointOfInstantiation =
18140           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18141       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18142       if (FirstInstantiation) {
18143         PointOfInstantiation = Loc;
18144         if (MSI)
18145           MSI->setPointOfInstantiation(PointOfInstantiation);
18146           // FIXME: Notify listener.
18147         else
18148           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18149       }
18150 
18151       if (UsableInConstantExpr) {
18152         // Do not defer instantiations of variables that could be used in a
18153         // constant expression.
18154         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18155           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18156         });
18157 
18158         // Re-set the member to trigger a recomputation of the dependence bits
18159         // for the expression.
18160         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18161           DRE->setDecl(DRE->getDecl());
18162         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18163           ME->setMemberDecl(ME->getMemberDecl());
18164       } else if (FirstInstantiation ||
18165                  isa<VarTemplateSpecializationDecl>(Var)) {
18166         // FIXME: For a specialization of a variable template, we don't
18167         // distinguish between "declaration and type implicitly instantiated"
18168         // and "implicit instantiation of definition requested", so we have
18169         // no direct way to avoid enqueueing the pending instantiation
18170         // multiple times.
18171         SemaRef.PendingInstantiations
18172             .push_back(std::make_pair(Var, PointOfInstantiation));
18173       }
18174     }
18175   }
18176 
18177   // C++2a [basic.def.odr]p4:
18178   //   A variable x whose name appears as a potentially-evaluated expression e
18179   //   is odr-used by e unless
18180   //   -- x is a reference that is usable in constant expressions
18181   //   -- x is a variable of non-reference type that is usable in constant
18182   //      expressions and has no mutable subobjects [FIXME], and e is an
18183   //      element of the set of potential results of an expression of
18184   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18185   //      conversion is applied
18186   //   -- x is a variable of non-reference type, and e is an element of the set
18187   //      of potential results of a discarded-value expression to which the
18188   //      lvalue-to-rvalue conversion is not applied [FIXME]
18189   //
18190   // We check the first part of the second bullet here, and
18191   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18192   // FIXME: To get the third bullet right, we need to delay this even for
18193   // variables that are not usable in constant expressions.
18194 
18195   // If we already know this isn't an odr-use, there's nothing more to do.
18196   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18197     if (DRE->isNonOdrUse())
18198       return;
18199   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18200     if (ME->isNonOdrUse())
18201       return;
18202 
18203   switch (OdrUse) {
18204   case OdrUseContext::None:
18205     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18206            "missing non-odr-use marking for unevaluated decl ref");
18207     break;
18208 
18209   case OdrUseContext::FormallyOdrUsed:
18210     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18211     // behavior.
18212     break;
18213 
18214   case OdrUseContext::Used:
18215     // If we might later find that this expression isn't actually an odr-use,
18216     // delay the marking.
18217     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18218       SemaRef.MaybeODRUseExprs.insert(E);
18219     else
18220       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18221     break;
18222 
18223   case OdrUseContext::Dependent:
18224     // If this is a dependent context, we don't need to mark variables as
18225     // odr-used, but we may still need to track them for lambda capture.
18226     // FIXME: Do we also need to do this inside dependent typeid expressions
18227     // (which are modeled as unevaluated at this point)?
18228     const bool RefersToEnclosingScope =
18229         (SemaRef.CurContext != Var->getDeclContext() &&
18230          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18231     if (RefersToEnclosingScope) {
18232       LambdaScopeInfo *const LSI =
18233           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18234       if (LSI && (!LSI->CallOperator ||
18235                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18236         // If a variable could potentially be odr-used, defer marking it so
18237         // until we finish analyzing the full expression for any
18238         // lvalue-to-rvalue
18239         // or discarded value conversions that would obviate odr-use.
18240         // Add it to the list of potential captures that will be analyzed
18241         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18242         // unless the variable is a reference that was initialized by a constant
18243         // expression (this will never need to be captured or odr-used).
18244         //
18245         // FIXME: We can simplify this a lot after implementing P0588R1.
18246         assert(E && "Capture variable should be used in an expression.");
18247         if (!Var->getType()->isReferenceType() ||
18248             !Var->isUsableInConstantExpressions(SemaRef.Context))
18249           LSI->addPotentialCapture(E->IgnoreParens());
18250       }
18251     }
18252     break;
18253   }
18254 }
18255 
18256 /// Mark a variable referenced, and check whether it is odr-used
18257 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18258 /// used directly for normal expressions referring to VarDecl.
18259 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18260   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18261 }
18262 
18263 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18264                                Decl *D, Expr *E, bool MightBeOdrUse) {
18265   if (SemaRef.isInOpenMPDeclareTargetContext())
18266     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18267 
18268   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18269     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18270     return;
18271   }
18272 
18273   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18274 
18275   // If this is a call to a method via a cast, also mark the method in the
18276   // derived class used in case codegen can devirtualize the call.
18277   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18278   if (!ME)
18279     return;
18280   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18281   if (!MD)
18282     return;
18283   // Only attempt to devirtualize if this is truly a virtual call.
18284   bool IsVirtualCall = MD->isVirtual() &&
18285                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18286   if (!IsVirtualCall)
18287     return;
18288 
18289   // If it's possible to devirtualize the call, mark the called function
18290   // referenced.
18291   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18292       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18293   if (DM)
18294     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18295 }
18296 
18297 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18298 ///
18299 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18300 /// handled with care if the DeclRefExpr is not newly-created.
18301 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18302   // TODO: update this with DR# once a defect report is filed.
18303   // C++11 defect. The address of a pure member should not be an ODR use, even
18304   // if it's a qualified reference.
18305   bool OdrUse = true;
18306   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18307     if (Method->isVirtual() &&
18308         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18309       OdrUse = false;
18310 
18311   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18312     if (!isConstantEvaluated() && FD->isConsteval() &&
18313         !RebuildingImmediateInvocation)
18314       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18315   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18316 }
18317 
18318 /// Perform reference-marking and odr-use handling for a MemberExpr.
18319 void Sema::MarkMemberReferenced(MemberExpr *E) {
18320   // C++11 [basic.def.odr]p2:
18321   //   A non-overloaded function whose name appears as a potentially-evaluated
18322   //   expression or a member of a set of candidate functions, if selected by
18323   //   overload resolution when referred to from a potentially-evaluated
18324   //   expression, is odr-used, unless it is a pure virtual function and its
18325   //   name is not explicitly qualified.
18326   bool MightBeOdrUse = true;
18327   if (E->performsVirtualDispatch(getLangOpts())) {
18328     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18329       if (Method->isPure())
18330         MightBeOdrUse = false;
18331   }
18332   SourceLocation Loc =
18333       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18334   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18335 }
18336 
18337 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18338 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18339   for (VarDecl *VD : *E)
18340     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18341 }
18342 
18343 /// Perform marking for a reference to an arbitrary declaration.  It
18344 /// marks the declaration referenced, and performs odr-use checking for
18345 /// functions and variables. This method should not be used when building a
18346 /// normal expression which refers to a variable.
18347 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18348                                  bool MightBeOdrUse) {
18349   if (MightBeOdrUse) {
18350     if (auto *VD = dyn_cast<VarDecl>(D)) {
18351       MarkVariableReferenced(Loc, VD);
18352       return;
18353     }
18354   }
18355   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18356     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18357     return;
18358   }
18359   D->setReferenced();
18360 }
18361 
18362 namespace {
18363   // Mark all of the declarations used by a type as referenced.
18364   // FIXME: Not fully implemented yet! We need to have a better understanding
18365   // of when we're entering a context we should not recurse into.
18366   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18367   // TreeTransforms rebuilding the type in a new context. Rather than
18368   // duplicating the TreeTransform logic, we should consider reusing it here.
18369   // Currently that causes problems when rebuilding LambdaExprs.
18370   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18371     Sema &S;
18372     SourceLocation Loc;
18373 
18374   public:
18375     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18376 
18377     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18378 
18379     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18380   };
18381 }
18382 
18383 bool MarkReferencedDecls::TraverseTemplateArgument(
18384     const TemplateArgument &Arg) {
18385   {
18386     // A non-type template argument is a constant-evaluated context.
18387     EnterExpressionEvaluationContext Evaluated(
18388         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18389     if (Arg.getKind() == TemplateArgument::Declaration) {
18390       if (Decl *D = Arg.getAsDecl())
18391         S.MarkAnyDeclReferenced(Loc, D, true);
18392     } else if (Arg.getKind() == TemplateArgument::Expression) {
18393       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18394     }
18395   }
18396 
18397   return Inherited::TraverseTemplateArgument(Arg);
18398 }
18399 
18400 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18401   MarkReferencedDecls Marker(*this, Loc);
18402   Marker.TraverseType(T);
18403 }
18404 
18405 namespace {
18406 /// Helper class that marks all of the declarations referenced by
18407 /// potentially-evaluated subexpressions as "referenced".
18408 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18409 public:
18410   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18411   bool SkipLocalVariables;
18412 
18413   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18414       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18415 
18416   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18417     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18418   }
18419 
18420   void VisitDeclRefExpr(DeclRefExpr *E) {
18421     // If we were asked not to visit local variables, don't.
18422     if (SkipLocalVariables) {
18423       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18424         if (VD->hasLocalStorage())
18425           return;
18426     }
18427 
18428     // FIXME: This can trigger the instantiation of the initializer of a
18429     // variable, which can cause the expression to become value-dependent
18430     // or error-dependent. Do we need to propagate the new dependence bits?
18431     S.MarkDeclRefReferenced(E);
18432   }
18433 
18434   void VisitMemberExpr(MemberExpr *E) {
18435     S.MarkMemberReferenced(E);
18436     Visit(E->getBase());
18437   }
18438 };
18439 } // namespace
18440 
18441 /// Mark any declarations that appear within this expression or any
18442 /// potentially-evaluated subexpressions as "referenced".
18443 ///
18444 /// \param SkipLocalVariables If true, don't mark local variables as
18445 /// 'referenced'.
18446 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18447                                             bool SkipLocalVariables) {
18448   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18449 }
18450 
18451 /// Emit a diagnostic that describes an effect on the run-time behavior
18452 /// of the program being compiled.
18453 ///
18454 /// This routine emits the given diagnostic when the code currently being
18455 /// type-checked is "potentially evaluated", meaning that there is a
18456 /// possibility that the code will actually be executable. Code in sizeof()
18457 /// expressions, code used only during overload resolution, etc., are not
18458 /// potentially evaluated. This routine will suppress such diagnostics or,
18459 /// in the absolutely nutty case of potentially potentially evaluated
18460 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18461 /// later.
18462 ///
18463 /// This routine should be used for all diagnostics that describe the run-time
18464 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18465 /// Failure to do so will likely result in spurious diagnostics or failures
18466 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18467 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18468                                const PartialDiagnostic &PD) {
18469   switch (ExprEvalContexts.back().Context) {
18470   case ExpressionEvaluationContext::Unevaluated:
18471   case ExpressionEvaluationContext::UnevaluatedList:
18472   case ExpressionEvaluationContext::UnevaluatedAbstract:
18473   case ExpressionEvaluationContext::DiscardedStatement:
18474     // The argument will never be evaluated, so don't complain.
18475     break;
18476 
18477   case ExpressionEvaluationContext::ConstantEvaluated:
18478     // Relevant diagnostics should be produced by constant evaluation.
18479     break;
18480 
18481   case ExpressionEvaluationContext::PotentiallyEvaluated:
18482   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18483     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18484       FunctionScopes.back()->PossiblyUnreachableDiags.
18485         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18486       return true;
18487     }
18488 
18489     // The initializer of a constexpr variable or of the first declaration of a
18490     // static data member is not syntactically a constant evaluated constant,
18491     // but nonetheless is always required to be a constant expression, so we
18492     // can skip diagnosing.
18493     // FIXME: Using the mangling context here is a hack.
18494     if (auto *VD = dyn_cast_or_null<VarDecl>(
18495             ExprEvalContexts.back().ManglingContextDecl)) {
18496       if (VD->isConstexpr() ||
18497           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18498         break;
18499       // FIXME: For any other kind of variable, we should build a CFG for its
18500       // initializer and check whether the context in question is reachable.
18501     }
18502 
18503     Diag(Loc, PD);
18504     return true;
18505   }
18506 
18507   return false;
18508 }
18509 
18510 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18511                                const PartialDiagnostic &PD) {
18512   return DiagRuntimeBehavior(
18513       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18514 }
18515 
18516 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18517                                CallExpr *CE, FunctionDecl *FD) {
18518   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18519     return false;
18520 
18521   // If we're inside a decltype's expression, don't check for a valid return
18522   // type or construct temporaries until we know whether this is the last call.
18523   if (ExprEvalContexts.back().ExprContext ==
18524       ExpressionEvaluationContextRecord::EK_Decltype) {
18525     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18526     return false;
18527   }
18528 
18529   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18530     FunctionDecl *FD;
18531     CallExpr *CE;
18532 
18533   public:
18534     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18535       : FD(FD), CE(CE) { }
18536 
18537     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18538       if (!FD) {
18539         S.Diag(Loc, diag::err_call_incomplete_return)
18540           << T << CE->getSourceRange();
18541         return;
18542       }
18543 
18544       S.Diag(Loc, diag::err_call_function_incomplete_return)
18545           << CE->getSourceRange() << FD << T;
18546       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18547           << FD->getDeclName();
18548     }
18549   } Diagnoser(FD, CE);
18550 
18551   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18552     return true;
18553 
18554   return false;
18555 }
18556 
18557 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18558 // will prevent this condition from triggering, which is what we want.
18559 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18560   SourceLocation Loc;
18561 
18562   unsigned diagnostic = diag::warn_condition_is_assignment;
18563   bool IsOrAssign = false;
18564 
18565   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18566     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18567       return;
18568 
18569     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18570 
18571     // Greylist some idioms by putting them into a warning subcategory.
18572     if (ObjCMessageExpr *ME
18573           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18574       Selector Sel = ME->getSelector();
18575 
18576       // self = [<foo> init...]
18577       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18578         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18579 
18580       // <foo> = [<bar> nextObject]
18581       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18582         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18583     }
18584 
18585     Loc = Op->getOperatorLoc();
18586   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18587     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18588       return;
18589 
18590     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18591     Loc = Op->getOperatorLoc();
18592   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18593     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18594   else {
18595     // Not an assignment.
18596     return;
18597   }
18598 
18599   Diag(Loc, diagnostic) << E->getSourceRange();
18600 
18601   SourceLocation Open = E->getBeginLoc();
18602   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18603   Diag(Loc, diag::note_condition_assign_silence)
18604         << FixItHint::CreateInsertion(Open, "(")
18605         << FixItHint::CreateInsertion(Close, ")");
18606 
18607   if (IsOrAssign)
18608     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18609       << FixItHint::CreateReplacement(Loc, "!=");
18610   else
18611     Diag(Loc, diag::note_condition_assign_to_comparison)
18612       << FixItHint::CreateReplacement(Loc, "==");
18613 }
18614 
18615 /// Redundant parentheses over an equality comparison can indicate
18616 /// that the user intended an assignment used as condition.
18617 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18618   // Don't warn if the parens came from a macro.
18619   SourceLocation parenLoc = ParenE->getBeginLoc();
18620   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18621     return;
18622   // Don't warn for dependent expressions.
18623   if (ParenE->isTypeDependent())
18624     return;
18625 
18626   Expr *E = ParenE->IgnoreParens();
18627 
18628   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18629     if (opE->getOpcode() == BO_EQ &&
18630         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18631                                                            == Expr::MLV_Valid) {
18632       SourceLocation Loc = opE->getOperatorLoc();
18633 
18634       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18635       SourceRange ParenERange = ParenE->getSourceRange();
18636       Diag(Loc, diag::note_equality_comparison_silence)
18637         << FixItHint::CreateRemoval(ParenERange.getBegin())
18638         << FixItHint::CreateRemoval(ParenERange.getEnd());
18639       Diag(Loc, diag::note_equality_comparison_to_assign)
18640         << FixItHint::CreateReplacement(Loc, "=");
18641     }
18642 }
18643 
18644 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18645                                        bool IsConstexpr) {
18646   DiagnoseAssignmentAsCondition(E);
18647   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18648     DiagnoseEqualityWithExtraParens(parenE);
18649 
18650   ExprResult result = CheckPlaceholderExpr(E);
18651   if (result.isInvalid()) return ExprError();
18652   E = result.get();
18653 
18654   if (!E->isTypeDependent()) {
18655     if (getLangOpts().CPlusPlus)
18656       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18657 
18658     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18659     if (ERes.isInvalid())
18660       return ExprError();
18661     E = ERes.get();
18662 
18663     QualType T = E->getType();
18664     if (!T->isScalarType()) { // C99 6.8.4.1p1
18665       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18666         << T << E->getSourceRange();
18667       return ExprError();
18668     }
18669     CheckBoolLikeConversion(E, Loc);
18670   }
18671 
18672   return E;
18673 }
18674 
18675 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18676                                            Expr *SubExpr, ConditionKind CK) {
18677   // Empty conditions are valid in for-statements.
18678   if (!SubExpr)
18679     return ConditionResult();
18680 
18681   ExprResult Cond;
18682   switch (CK) {
18683   case ConditionKind::Boolean:
18684     Cond = CheckBooleanCondition(Loc, SubExpr);
18685     break;
18686 
18687   case ConditionKind::ConstexprIf:
18688     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18689     break;
18690 
18691   case ConditionKind::Switch:
18692     Cond = CheckSwitchCondition(Loc, SubExpr);
18693     break;
18694   }
18695   if (Cond.isInvalid()) {
18696     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18697                               {SubExpr});
18698     if (!Cond.get())
18699       return ConditionError();
18700   }
18701   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18702   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18703   if (!FullExpr.get())
18704     return ConditionError();
18705 
18706   return ConditionResult(*this, nullptr, FullExpr,
18707                          CK == ConditionKind::ConstexprIf);
18708 }
18709 
18710 namespace {
18711   /// A visitor for rebuilding a call to an __unknown_any expression
18712   /// to have an appropriate type.
18713   struct RebuildUnknownAnyFunction
18714     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18715 
18716     Sema &S;
18717 
18718     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18719 
18720     ExprResult VisitStmt(Stmt *S) {
18721       llvm_unreachable("unexpected statement!");
18722     }
18723 
18724     ExprResult VisitExpr(Expr *E) {
18725       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18726         << E->getSourceRange();
18727       return ExprError();
18728     }
18729 
18730     /// Rebuild an expression which simply semantically wraps another
18731     /// expression which it shares the type and value kind of.
18732     template <class T> ExprResult rebuildSugarExpr(T *E) {
18733       ExprResult SubResult = Visit(E->getSubExpr());
18734       if (SubResult.isInvalid()) return ExprError();
18735 
18736       Expr *SubExpr = SubResult.get();
18737       E->setSubExpr(SubExpr);
18738       E->setType(SubExpr->getType());
18739       E->setValueKind(SubExpr->getValueKind());
18740       assert(E->getObjectKind() == OK_Ordinary);
18741       return E;
18742     }
18743 
18744     ExprResult VisitParenExpr(ParenExpr *E) {
18745       return rebuildSugarExpr(E);
18746     }
18747 
18748     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18749       return rebuildSugarExpr(E);
18750     }
18751 
18752     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18753       ExprResult SubResult = Visit(E->getSubExpr());
18754       if (SubResult.isInvalid()) return ExprError();
18755 
18756       Expr *SubExpr = SubResult.get();
18757       E->setSubExpr(SubExpr);
18758       E->setType(S.Context.getPointerType(SubExpr->getType()));
18759       assert(E->getValueKind() == VK_RValue);
18760       assert(E->getObjectKind() == OK_Ordinary);
18761       return E;
18762     }
18763 
18764     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18765       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18766 
18767       E->setType(VD->getType());
18768 
18769       assert(E->getValueKind() == VK_RValue);
18770       if (S.getLangOpts().CPlusPlus &&
18771           !(isa<CXXMethodDecl>(VD) &&
18772             cast<CXXMethodDecl>(VD)->isInstance()))
18773         E->setValueKind(VK_LValue);
18774 
18775       return E;
18776     }
18777 
18778     ExprResult VisitMemberExpr(MemberExpr *E) {
18779       return resolveDecl(E, E->getMemberDecl());
18780     }
18781 
18782     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18783       return resolveDecl(E, E->getDecl());
18784     }
18785   };
18786 }
18787 
18788 /// Given a function expression of unknown-any type, try to rebuild it
18789 /// to have a function type.
18790 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18791   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18792   if (Result.isInvalid()) return ExprError();
18793   return S.DefaultFunctionArrayConversion(Result.get());
18794 }
18795 
18796 namespace {
18797   /// A visitor for rebuilding an expression of type __unknown_anytype
18798   /// into one which resolves the type directly on the referring
18799   /// expression.  Strict preservation of the original source
18800   /// structure is not a goal.
18801   struct RebuildUnknownAnyExpr
18802     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18803 
18804     Sema &S;
18805 
18806     /// The current destination type.
18807     QualType DestType;
18808 
18809     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18810       : S(S), DestType(CastType) {}
18811 
18812     ExprResult VisitStmt(Stmt *S) {
18813       llvm_unreachable("unexpected statement!");
18814     }
18815 
18816     ExprResult VisitExpr(Expr *E) {
18817       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18818         << E->getSourceRange();
18819       return ExprError();
18820     }
18821 
18822     ExprResult VisitCallExpr(CallExpr *E);
18823     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18824 
18825     /// Rebuild an expression which simply semantically wraps another
18826     /// expression which it shares the type and value kind of.
18827     template <class T> ExprResult rebuildSugarExpr(T *E) {
18828       ExprResult SubResult = Visit(E->getSubExpr());
18829       if (SubResult.isInvalid()) return ExprError();
18830       Expr *SubExpr = SubResult.get();
18831       E->setSubExpr(SubExpr);
18832       E->setType(SubExpr->getType());
18833       E->setValueKind(SubExpr->getValueKind());
18834       assert(E->getObjectKind() == OK_Ordinary);
18835       return E;
18836     }
18837 
18838     ExprResult VisitParenExpr(ParenExpr *E) {
18839       return rebuildSugarExpr(E);
18840     }
18841 
18842     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18843       return rebuildSugarExpr(E);
18844     }
18845 
18846     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18847       const PointerType *Ptr = DestType->getAs<PointerType>();
18848       if (!Ptr) {
18849         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18850           << E->getSourceRange();
18851         return ExprError();
18852       }
18853 
18854       if (isa<CallExpr>(E->getSubExpr())) {
18855         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18856           << E->getSourceRange();
18857         return ExprError();
18858       }
18859 
18860       assert(E->getValueKind() == VK_RValue);
18861       assert(E->getObjectKind() == OK_Ordinary);
18862       E->setType(DestType);
18863 
18864       // Build the sub-expression as if it were an object of the pointee type.
18865       DestType = Ptr->getPointeeType();
18866       ExprResult SubResult = Visit(E->getSubExpr());
18867       if (SubResult.isInvalid()) return ExprError();
18868       E->setSubExpr(SubResult.get());
18869       return E;
18870     }
18871 
18872     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18873 
18874     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18875 
18876     ExprResult VisitMemberExpr(MemberExpr *E) {
18877       return resolveDecl(E, E->getMemberDecl());
18878     }
18879 
18880     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18881       return resolveDecl(E, E->getDecl());
18882     }
18883   };
18884 }
18885 
18886 /// Rebuilds a call expression which yielded __unknown_anytype.
18887 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18888   Expr *CalleeExpr = E->getCallee();
18889 
18890   enum FnKind {
18891     FK_MemberFunction,
18892     FK_FunctionPointer,
18893     FK_BlockPointer
18894   };
18895 
18896   FnKind Kind;
18897   QualType CalleeType = CalleeExpr->getType();
18898   if (CalleeType == S.Context.BoundMemberTy) {
18899     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18900     Kind = FK_MemberFunction;
18901     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18902   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18903     CalleeType = Ptr->getPointeeType();
18904     Kind = FK_FunctionPointer;
18905   } else {
18906     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18907     Kind = FK_BlockPointer;
18908   }
18909   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18910 
18911   // Verify that this is a legal result type of a function.
18912   if (DestType->isArrayType() || DestType->isFunctionType()) {
18913     unsigned diagID = diag::err_func_returning_array_function;
18914     if (Kind == FK_BlockPointer)
18915       diagID = diag::err_block_returning_array_function;
18916 
18917     S.Diag(E->getExprLoc(), diagID)
18918       << DestType->isFunctionType() << DestType;
18919     return ExprError();
18920   }
18921 
18922   // Otherwise, go ahead and set DestType as the call's result.
18923   E->setType(DestType.getNonLValueExprType(S.Context));
18924   E->setValueKind(Expr::getValueKindForType(DestType));
18925   assert(E->getObjectKind() == OK_Ordinary);
18926 
18927   // Rebuild the function type, replacing the result type with DestType.
18928   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18929   if (Proto) {
18930     // __unknown_anytype(...) is a special case used by the debugger when
18931     // it has no idea what a function's signature is.
18932     //
18933     // We want to build this call essentially under the K&R
18934     // unprototyped rules, but making a FunctionNoProtoType in C++
18935     // would foul up all sorts of assumptions.  However, we cannot
18936     // simply pass all arguments as variadic arguments, nor can we
18937     // portably just call the function under a non-variadic type; see
18938     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18939     // However, it turns out that in practice it is generally safe to
18940     // call a function declared as "A foo(B,C,D);" under the prototype
18941     // "A foo(B,C,D,...);".  The only known exception is with the
18942     // Windows ABI, where any variadic function is implicitly cdecl
18943     // regardless of its normal CC.  Therefore we change the parameter
18944     // types to match the types of the arguments.
18945     //
18946     // This is a hack, but it is far superior to moving the
18947     // corresponding target-specific code from IR-gen to Sema/AST.
18948 
18949     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18950     SmallVector<QualType, 8> ArgTypes;
18951     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18952       ArgTypes.reserve(E->getNumArgs());
18953       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18954         Expr *Arg = E->getArg(i);
18955         QualType ArgType = Arg->getType();
18956         if (E->isLValue()) {
18957           ArgType = S.Context.getLValueReferenceType(ArgType);
18958         } else if (E->isXValue()) {
18959           ArgType = S.Context.getRValueReferenceType(ArgType);
18960         }
18961         ArgTypes.push_back(ArgType);
18962       }
18963       ParamTypes = ArgTypes;
18964     }
18965     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18966                                          Proto->getExtProtoInfo());
18967   } else {
18968     DestType = S.Context.getFunctionNoProtoType(DestType,
18969                                                 FnType->getExtInfo());
18970   }
18971 
18972   // Rebuild the appropriate pointer-to-function type.
18973   switch (Kind) {
18974   case FK_MemberFunction:
18975     // Nothing to do.
18976     break;
18977 
18978   case FK_FunctionPointer:
18979     DestType = S.Context.getPointerType(DestType);
18980     break;
18981 
18982   case FK_BlockPointer:
18983     DestType = S.Context.getBlockPointerType(DestType);
18984     break;
18985   }
18986 
18987   // Finally, we can recurse.
18988   ExprResult CalleeResult = Visit(CalleeExpr);
18989   if (!CalleeResult.isUsable()) return ExprError();
18990   E->setCallee(CalleeResult.get());
18991 
18992   // Bind a temporary if necessary.
18993   return S.MaybeBindToTemporary(E);
18994 }
18995 
18996 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18997   // Verify that this is a legal result type of a call.
18998   if (DestType->isArrayType() || DestType->isFunctionType()) {
18999     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19000       << DestType->isFunctionType() << DestType;
19001     return ExprError();
19002   }
19003 
19004   // Rewrite the method result type if available.
19005   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19006     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19007     Method->setReturnType(DestType);
19008   }
19009 
19010   // Change the type of the message.
19011   E->setType(DestType.getNonReferenceType());
19012   E->setValueKind(Expr::getValueKindForType(DestType));
19013 
19014   return S.MaybeBindToTemporary(E);
19015 }
19016 
19017 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19018   // The only case we should ever see here is a function-to-pointer decay.
19019   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19020     assert(E->getValueKind() == VK_RValue);
19021     assert(E->getObjectKind() == OK_Ordinary);
19022 
19023     E->setType(DestType);
19024 
19025     // Rebuild the sub-expression as the pointee (function) type.
19026     DestType = DestType->castAs<PointerType>()->getPointeeType();
19027 
19028     ExprResult Result = Visit(E->getSubExpr());
19029     if (!Result.isUsable()) return ExprError();
19030 
19031     E->setSubExpr(Result.get());
19032     return E;
19033   } else if (E->getCastKind() == CK_LValueToRValue) {
19034     assert(E->getValueKind() == VK_RValue);
19035     assert(E->getObjectKind() == OK_Ordinary);
19036 
19037     assert(isa<BlockPointerType>(E->getType()));
19038 
19039     E->setType(DestType);
19040 
19041     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19042     DestType = S.Context.getLValueReferenceType(DestType);
19043 
19044     ExprResult Result = Visit(E->getSubExpr());
19045     if (!Result.isUsable()) return ExprError();
19046 
19047     E->setSubExpr(Result.get());
19048     return E;
19049   } else {
19050     llvm_unreachable("Unhandled cast type!");
19051   }
19052 }
19053 
19054 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19055   ExprValueKind ValueKind = VK_LValue;
19056   QualType Type = DestType;
19057 
19058   // We know how to make this work for certain kinds of decls:
19059 
19060   //  - functions
19061   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19062     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19063       DestType = Ptr->getPointeeType();
19064       ExprResult Result = resolveDecl(E, VD);
19065       if (Result.isInvalid()) return ExprError();
19066       return S.ImpCastExprToType(Result.get(), Type,
19067                                  CK_FunctionToPointerDecay, VK_RValue);
19068     }
19069 
19070     if (!Type->isFunctionType()) {
19071       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19072         << VD << E->getSourceRange();
19073       return ExprError();
19074     }
19075     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19076       // We must match the FunctionDecl's type to the hack introduced in
19077       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19078       // type. See the lengthy commentary in that routine.
19079       QualType FDT = FD->getType();
19080       const FunctionType *FnType = FDT->castAs<FunctionType>();
19081       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19082       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19083       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19084         SourceLocation Loc = FD->getLocation();
19085         FunctionDecl *NewFD = FunctionDecl::Create(
19086             S.Context, FD->getDeclContext(), Loc, Loc,
19087             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19088             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19089             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19090 
19091         if (FD->getQualifier())
19092           NewFD->setQualifierInfo(FD->getQualifierLoc());
19093 
19094         SmallVector<ParmVarDecl*, 16> Params;
19095         for (const auto &AI : FT->param_types()) {
19096           ParmVarDecl *Param =
19097             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19098           Param->setScopeInfo(0, Params.size());
19099           Params.push_back(Param);
19100         }
19101         NewFD->setParams(Params);
19102         DRE->setDecl(NewFD);
19103         VD = DRE->getDecl();
19104       }
19105     }
19106 
19107     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19108       if (MD->isInstance()) {
19109         ValueKind = VK_RValue;
19110         Type = S.Context.BoundMemberTy;
19111       }
19112 
19113     // Function references aren't l-values in C.
19114     if (!S.getLangOpts().CPlusPlus)
19115       ValueKind = VK_RValue;
19116 
19117   //  - variables
19118   } else if (isa<VarDecl>(VD)) {
19119     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19120       Type = RefTy->getPointeeType();
19121     } else if (Type->isFunctionType()) {
19122       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19123         << VD << E->getSourceRange();
19124       return ExprError();
19125     }
19126 
19127   //  - nothing else
19128   } else {
19129     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19130       << VD << E->getSourceRange();
19131     return ExprError();
19132   }
19133 
19134   // Modifying the declaration like this is friendly to IR-gen but
19135   // also really dangerous.
19136   VD->setType(DestType);
19137   E->setType(Type);
19138   E->setValueKind(ValueKind);
19139   return E;
19140 }
19141 
19142 /// Check a cast of an unknown-any type.  We intentionally only
19143 /// trigger this for C-style casts.
19144 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19145                                      Expr *CastExpr, CastKind &CastKind,
19146                                      ExprValueKind &VK, CXXCastPath &Path) {
19147   // The type we're casting to must be either void or complete.
19148   if (!CastType->isVoidType() &&
19149       RequireCompleteType(TypeRange.getBegin(), CastType,
19150                           diag::err_typecheck_cast_to_incomplete))
19151     return ExprError();
19152 
19153   // Rewrite the casted expression from scratch.
19154   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19155   if (!result.isUsable()) return ExprError();
19156 
19157   CastExpr = result.get();
19158   VK = CastExpr->getValueKind();
19159   CastKind = CK_NoOp;
19160 
19161   return CastExpr;
19162 }
19163 
19164 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19165   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19166 }
19167 
19168 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19169                                     Expr *arg, QualType &paramType) {
19170   // If the syntactic form of the argument is not an explicit cast of
19171   // any sort, just do default argument promotion.
19172   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19173   if (!castArg) {
19174     ExprResult result = DefaultArgumentPromotion(arg);
19175     if (result.isInvalid()) return ExprError();
19176     paramType = result.get()->getType();
19177     return result;
19178   }
19179 
19180   // Otherwise, use the type that was written in the explicit cast.
19181   assert(!arg->hasPlaceholderType());
19182   paramType = castArg->getTypeAsWritten();
19183 
19184   // Copy-initialize a parameter of that type.
19185   InitializedEntity entity =
19186     InitializedEntity::InitializeParameter(Context, paramType,
19187                                            /*consumed*/ false);
19188   return PerformCopyInitialization(entity, callLoc, arg);
19189 }
19190 
19191 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19192   Expr *orig = E;
19193   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19194   while (true) {
19195     E = E->IgnoreParenImpCasts();
19196     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19197       E = call->getCallee();
19198       diagID = diag::err_uncasted_call_of_unknown_any;
19199     } else {
19200       break;
19201     }
19202   }
19203 
19204   SourceLocation loc;
19205   NamedDecl *d;
19206   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19207     loc = ref->getLocation();
19208     d = ref->getDecl();
19209   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19210     loc = mem->getMemberLoc();
19211     d = mem->getMemberDecl();
19212   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19213     diagID = diag::err_uncasted_call_of_unknown_any;
19214     loc = msg->getSelectorStartLoc();
19215     d = msg->getMethodDecl();
19216     if (!d) {
19217       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19218         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19219         << orig->getSourceRange();
19220       return ExprError();
19221     }
19222   } else {
19223     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19224       << E->getSourceRange();
19225     return ExprError();
19226   }
19227 
19228   S.Diag(loc, diagID) << d << orig->getSourceRange();
19229 
19230   // Never recoverable.
19231   return ExprError();
19232 }
19233 
19234 /// Check for operands with placeholder types and complain if found.
19235 /// Returns ExprError() if there was an error and no recovery was possible.
19236 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19237   if (!Context.isDependenceAllowed()) {
19238     // C cannot handle TypoExpr nodes on either side of a binop because it
19239     // doesn't handle dependent types properly, so make sure any TypoExprs have
19240     // been dealt with before checking the operands.
19241     ExprResult Result = CorrectDelayedTyposInExpr(E);
19242     if (!Result.isUsable()) return ExprError();
19243     E = Result.get();
19244   }
19245 
19246   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19247   if (!placeholderType) return E;
19248 
19249   switch (placeholderType->getKind()) {
19250 
19251   // Overloaded expressions.
19252   case BuiltinType::Overload: {
19253     // Try to resolve a single function template specialization.
19254     // This is obligatory.
19255     ExprResult Result = E;
19256     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19257       return Result;
19258 
19259     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19260     // leaves Result unchanged on failure.
19261     Result = E;
19262     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19263       return Result;
19264 
19265     // If that failed, try to recover with a call.
19266     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19267                          /*complain*/ true);
19268     return Result;
19269   }
19270 
19271   // Bound member functions.
19272   case BuiltinType::BoundMember: {
19273     ExprResult result = E;
19274     const Expr *BME = E->IgnoreParens();
19275     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19276     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19277     if (isa<CXXPseudoDestructorExpr>(BME)) {
19278       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19279     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19280       if (ME->getMemberNameInfo().getName().getNameKind() ==
19281           DeclarationName::CXXDestructorName)
19282         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19283     }
19284     tryToRecoverWithCall(result, PD,
19285                          /*complain*/ true);
19286     return result;
19287   }
19288 
19289   // ARC unbridged casts.
19290   case BuiltinType::ARCUnbridgedCast: {
19291     Expr *realCast = stripARCUnbridgedCast(E);
19292     diagnoseARCUnbridgedCast(realCast);
19293     return realCast;
19294   }
19295 
19296   // Expressions of unknown type.
19297   case BuiltinType::UnknownAny:
19298     return diagnoseUnknownAnyExpr(*this, E);
19299 
19300   // Pseudo-objects.
19301   case BuiltinType::PseudoObject:
19302     return checkPseudoObjectRValue(E);
19303 
19304   case BuiltinType::BuiltinFn: {
19305     // Accept __noop without parens by implicitly converting it to a call expr.
19306     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19307     if (DRE) {
19308       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19309       if (FD->getBuiltinID() == Builtin::BI__noop) {
19310         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19311                               CK_BuiltinFnToFnPtr)
19312                 .get();
19313         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19314                                 VK_RValue, SourceLocation(),
19315                                 FPOptionsOverride());
19316       }
19317     }
19318 
19319     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19320     return ExprError();
19321   }
19322 
19323   case BuiltinType::IncompleteMatrixIdx:
19324     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19325              ->getRowIdx()
19326              ->getBeginLoc(),
19327          diag::err_matrix_incomplete_index);
19328     return ExprError();
19329 
19330   // Expressions of unknown type.
19331   case BuiltinType::OMPArraySection:
19332     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19333     return ExprError();
19334 
19335   // Expressions of unknown type.
19336   case BuiltinType::OMPArrayShaping:
19337     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19338 
19339   case BuiltinType::OMPIterator:
19340     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19341 
19342   // Everything else should be impossible.
19343 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19344   case BuiltinType::Id:
19345 #include "clang/Basic/OpenCLImageTypes.def"
19346 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19347   case BuiltinType::Id:
19348 #include "clang/Basic/OpenCLExtensionTypes.def"
19349 #define SVE_TYPE(Name, Id, SingletonId) \
19350   case BuiltinType::Id:
19351 #include "clang/Basic/AArch64SVEACLETypes.def"
19352 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19353   case BuiltinType::Id:
19354 #include "clang/Basic/PPCTypes.def"
19355 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19356 #define PLACEHOLDER_TYPE(Id, SingletonId)
19357 #include "clang/AST/BuiltinTypes.def"
19358     break;
19359   }
19360 
19361   llvm_unreachable("invalid placeholder type!");
19362 }
19363 
19364 bool Sema::CheckCaseExpression(Expr *E) {
19365   if (E->isTypeDependent())
19366     return true;
19367   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19368     return E->getType()->isIntegralOrEnumerationType();
19369   return false;
19370 }
19371 
19372 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19373 ExprResult
19374 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19375   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19376          "Unknown Objective-C Boolean value!");
19377   QualType BoolT = Context.ObjCBuiltinBoolTy;
19378   if (!Context.getBOOLDecl()) {
19379     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19380                         Sema::LookupOrdinaryName);
19381     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19382       NamedDecl *ND = Result.getFoundDecl();
19383       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19384         Context.setBOOLDecl(TD);
19385     }
19386   }
19387   if (Context.getBOOLDecl())
19388     BoolT = Context.getBOOLType();
19389   return new (Context)
19390       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19391 }
19392 
19393 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19394     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19395     SourceLocation RParen) {
19396 
19397   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19398 
19399   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19400     return Spec.getPlatform() == Platform;
19401   });
19402 
19403   VersionTuple Version;
19404   if (Spec != AvailSpecs.end())
19405     Version = Spec->getVersion();
19406 
19407   // The use of `@available` in the enclosing function should be analyzed to
19408   // warn when it's used inappropriately (i.e. not if(@available)).
19409   if (getCurFunctionOrMethodDecl())
19410     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19411   else if (getCurBlock() || getCurLambda())
19412     getCurFunction()->HasPotentialAvailabilityViolations = true;
19413 
19414   return new (Context)
19415       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19416 }
19417 
19418 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19419                                     ArrayRef<Expr *> SubExprs, QualType T) {
19420   if (!Context.getLangOpts().RecoveryAST)
19421     return ExprError();
19422 
19423   if (isSFINAEContext())
19424     return ExprError();
19425 
19426   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19427     // We don't know the concrete type, fallback to dependent type.
19428     T = Context.DependentTy;
19429   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19430 }
19431