xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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 (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.setImplicitSelfParam(&II);
2855   CXXScopeSpec SelfScopeSpec;
2856   SourceLocation TemplateKWLoc;
2857   ExprResult SelfExpr =
2858       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2859                         /*HasTrailingLParen=*/false,
2860                         /*IsAddressOfOperand=*/false);
2861   if (SelfExpr.isInvalid())
2862     return ExprError();
2863 
2864   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2865   if (SelfExpr.isInvalid())
2866     return ExprError();
2867 
2868   MarkAnyDeclReferenced(Loc, IV, true);
2869 
2870   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2871   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2872       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2873     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2874 
2875   ObjCIvarRefExpr *Result = new (Context)
2876       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2877                       IV->getLocation(), SelfExpr.get(), true, true);
2878 
2879   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2880     if (!isUnevaluatedContext() &&
2881         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2882       getCurFunction()->recordUseOfWeak(Result);
2883   }
2884   if (getLangOpts().ObjCAutoRefCount)
2885     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2886       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2887 
2888   return Result;
2889 }
2890 
2891 /// The parser has read a name in, and Sema has detected that we're currently
2892 /// inside an ObjC method. Perform some additional checks and determine if we
2893 /// should form a reference to an ivar. If so, build an expression referencing
2894 /// that ivar.
2895 ExprResult
2896 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2897                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2898   // FIXME: Integrate this lookup step into LookupParsedName.
2899   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2900   if (Ivar.isInvalid())
2901     return ExprError();
2902   if (Ivar.isUsable())
2903     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2904                             cast<ObjCIvarDecl>(Ivar.get()));
2905 
2906   if (Lookup.empty() && II && AllowBuiltinCreation)
2907     LookupBuiltin(Lookup);
2908 
2909   // Sentinel value saying that we didn't do anything special.
2910   return ExprResult(false);
2911 }
2912 
2913 /// Cast a base object to a member's actual type.
2914 ///
2915 /// There are two relevant checks:
2916 ///
2917 /// C++ [class.access.base]p7:
2918 ///
2919 ///   If a class member access operator [...] is used to access a non-static
2920 ///   data member or non-static member function, the reference is ill-formed if
2921 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2922 ///   naming class of the right operand.
2923 ///
2924 /// C++ [expr.ref]p7:
2925 ///
2926 ///   If E2 is a non-static data member or a non-static member function, the
2927 ///   program is ill-formed if the class of which E2 is directly a member is an
2928 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2929 ///
2930 /// Note that the latter check does not consider access; the access of the
2931 /// "real" base class is checked as appropriate when checking the access of the
2932 /// member name.
2933 ExprResult
2934 Sema::PerformObjectMemberConversion(Expr *From,
2935                                     NestedNameSpecifier *Qualifier,
2936                                     NamedDecl *FoundDecl,
2937                                     NamedDecl *Member) {
2938   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2939   if (!RD)
2940     return From;
2941 
2942   QualType DestRecordType;
2943   QualType DestType;
2944   QualType FromRecordType;
2945   QualType FromType = From->getType();
2946   bool PointerConversions = false;
2947   if (isa<FieldDecl>(Member)) {
2948     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2949     auto FromPtrType = FromType->getAs<PointerType>();
2950     DestRecordType = Context.getAddrSpaceQualType(
2951         DestRecordType, FromPtrType
2952                             ? FromType->getPointeeType().getAddressSpace()
2953                             : FromType.getAddressSpace());
2954 
2955     if (FromPtrType) {
2956       DestType = Context.getPointerType(DestRecordType);
2957       FromRecordType = FromPtrType->getPointeeType();
2958       PointerConversions = true;
2959     } else {
2960       DestType = DestRecordType;
2961       FromRecordType = FromType;
2962     }
2963   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2964     if (Method->isStatic())
2965       return From;
2966 
2967     DestType = Method->getThisType();
2968     DestRecordType = DestType->getPointeeType();
2969 
2970     if (FromType->getAs<PointerType>()) {
2971       FromRecordType = FromType->getPointeeType();
2972       PointerConversions = true;
2973     } else {
2974       FromRecordType = FromType;
2975       DestType = DestRecordType;
2976     }
2977 
2978     LangAS FromAS = FromRecordType.getAddressSpace();
2979     LangAS DestAS = DestRecordType.getAddressSpace();
2980     if (FromAS != DestAS) {
2981       QualType FromRecordTypeWithoutAS =
2982           Context.removeAddrSpaceQualType(FromRecordType);
2983       QualType FromTypeWithDestAS =
2984           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2985       if (PointerConversions)
2986         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2987       From = ImpCastExprToType(From, FromTypeWithDestAS,
2988                                CK_AddressSpaceConversion, From->getValueKind())
2989                  .get();
2990     }
2991   } else {
2992     // No conversion necessary.
2993     return From;
2994   }
2995 
2996   if (DestType->isDependentType() || FromType->isDependentType())
2997     return From;
2998 
2999   // If the unqualified types are the same, no conversion is necessary.
3000   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3001     return From;
3002 
3003   SourceRange FromRange = From->getSourceRange();
3004   SourceLocation FromLoc = FromRange.getBegin();
3005 
3006   ExprValueKind VK = From->getValueKind();
3007 
3008   // C++ [class.member.lookup]p8:
3009   //   [...] Ambiguities can often be resolved by qualifying a name with its
3010   //   class name.
3011   //
3012   // If the member was a qualified name and the qualified referred to a
3013   // specific base subobject type, we'll cast to that intermediate type
3014   // first and then to the object in which the member is declared. That allows
3015   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3016   //
3017   //   class Base { public: int x; };
3018   //   class Derived1 : public Base { };
3019   //   class Derived2 : public Base { };
3020   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3021   //
3022   //   void VeryDerived::f() {
3023   //     x = 17; // error: ambiguous base subobjects
3024   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3025   //   }
3026   if (Qualifier && Qualifier->getAsType()) {
3027     QualType QType = QualType(Qualifier->getAsType(), 0);
3028     assert(QType->isRecordType() && "lookup done with non-record type");
3029 
3030     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3031 
3032     // In C++98, the qualifier type doesn't actually have to be a base
3033     // type of the object type, in which case we just ignore it.
3034     // Otherwise build the appropriate casts.
3035     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3036       CXXCastPath BasePath;
3037       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3038                                        FromLoc, FromRange, &BasePath))
3039         return ExprError();
3040 
3041       if (PointerConversions)
3042         QType = Context.getPointerType(QType);
3043       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3044                                VK, &BasePath).get();
3045 
3046       FromType = QType;
3047       FromRecordType = QRecordType;
3048 
3049       // If the qualifier type was the same as the destination type,
3050       // we're done.
3051       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3052         return From;
3053     }
3054   }
3055 
3056   CXXCastPath BasePath;
3057   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3058                                    FromLoc, FromRange, &BasePath,
3059                                    /*IgnoreAccess=*/true))
3060     return ExprError();
3061 
3062   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3063                            VK, &BasePath);
3064 }
3065 
3066 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3067                                       const LookupResult &R,
3068                                       bool HasTrailingLParen) {
3069   // Only when used directly as the postfix-expression of a call.
3070   if (!HasTrailingLParen)
3071     return false;
3072 
3073   // Never if a scope specifier was provided.
3074   if (SS.isSet())
3075     return false;
3076 
3077   // Only in C++ or ObjC++.
3078   if (!getLangOpts().CPlusPlus)
3079     return false;
3080 
3081   // Turn off ADL when we find certain kinds of declarations during
3082   // normal lookup:
3083   for (NamedDecl *D : R) {
3084     // C++0x [basic.lookup.argdep]p3:
3085     //     -- a declaration of a class member
3086     // Since using decls preserve this property, we check this on the
3087     // original decl.
3088     if (D->isCXXClassMember())
3089       return false;
3090 
3091     // C++0x [basic.lookup.argdep]p3:
3092     //     -- a block-scope function declaration that is not a
3093     //        using-declaration
3094     // NOTE: we also trigger this for function templates (in fact, we
3095     // don't check the decl type at all, since all other decl types
3096     // turn off ADL anyway).
3097     if (isa<UsingShadowDecl>(D))
3098       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3099     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3100       return false;
3101 
3102     // C++0x [basic.lookup.argdep]p3:
3103     //     -- a declaration that is neither a function or a function
3104     //        template
3105     // And also for builtin functions.
3106     if (isa<FunctionDecl>(D)) {
3107       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3108 
3109       // But also builtin functions.
3110       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3111         return false;
3112     } else if (!isa<FunctionTemplateDecl>(D))
3113       return false;
3114   }
3115 
3116   return true;
3117 }
3118 
3119 
3120 /// Diagnoses obvious problems with the use of the given declaration
3121 /// as an expression.  This is only actually called for lookups that
3122 /// were not overloaded, and it doesn't promise that the declaration
3123 /// will in fact be used.
3124 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3125   if (D->isInvalidDecl())
3126     return true;
3127 
3128   if (isa<TypedefNameDecl>(D)) {
3129     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3130     return true;
3131   }
3132 
3133   if (isa<ObjCInterfaceDecl>(D)) {
3134     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3135     return true;
3136   }
3137 
3138   if (isa<NamespaceDecl>(D)) {
3139     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3140     return true;
3141   }
3142 
3143   return false;
3144 }
3145 
3146 // Certain multiversion types should be treated as overloaded even when there is
3147 // only one result.
3148 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3149   assert(R.isSingleResult() && "Expected only a single result");
3150   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3151   return FD &&
3152          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3153 }
3154 
3155 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3156                                           LookupResult &R, bool NeedsADL,
3157                                           bool AcceptInvalidDecl) {
3158   // If this is a single, fully-resolved result and we don't need ADL,
3159   // just build an ordinary singleton decl ref.
3160   if (!NeedsADL && R.isSingleResult() &&
3161       !R.getAsSingle<FunctionTemplateDecl>() &&
3162       !ShouldLookupResultBeMultiVersionOverload(R))
3163     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3164                                     R.getRepresentativeDecl(), nullptr,
3165                                     AcceptInvalidDecl);
3166 
3167   // We only need to check the declaration if there's exactly one
3168   // result, because in the overloaded case the results can only be
3169   // functions and function templates.
3170   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3171       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3172     return ExprError();
3173 
3174   // Otherwise, just build an unresolved lookup expression.  Suppress
3175   // any lookup-related diagnostics; we'll hash these out later, when
3176   // we've picked a target.
3177   R.suppressDiagnostics();
3178 
3179   UnresolvedLookupExpr *ULE
3180     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3181                                    SS.getWithLocInContext(Context),
3182                                    R.getLookupNameInfo(),
3183                                    NeedsADL, R.isOverloadedResult(),
3184                                    R.begin(), R.end());
3185 
3186   return ULE;
3187 }
3188 
3189 static void
3190 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3191                                    ValueDecl *var, DeclContext *DC);
3192 
3193 /// Complete semantic analysis for a reference to the given declaration.
3194 ExprResult Sema::BuildDeclarationNameExpr(
3195     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3196     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3197     bool AcceptInvalidDecl) {
3198   assert(D && "Cannot refer to a NULL declaration");
3199   assert(!isa<FunctionTemplateDecl>(D) &&
3200          "Cannot refer unambiguously to a function template");
3201 
3202   SourceLocation Loc = NameInfo.getLoc();
3203   if (CheckDeclInExpr(*this, Loc, D))
3204     return ExprError();
3205 
3206   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3207     // Specifically diagnose references to class templates that are missing
3208     // a template argument list.
3209     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3210     return ExprError();
3211   }
3212 
3213   // Make sure that we're referring to a value.
3214   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3215   if (!VD) {
3216     Diag(Loc, diag::err_ref_non_value)
3217       << D << SS.getRange();
3218     Diag(D->getLocation(), diag::note_declared_at);
3219     return ExprError();
3220   }
3221 
3222   // Check whether this declaration can be used. Note that we suppress
3223   // this check when we're going to perform argument-dependent lookup
3224   // on this function name, because this might not be the function
3225   // that overload resolution actually selects.
3226   if (DiagnoseUseOfDecl(VD, Loc))
3227     return ExprError();
3228 
3229   // Only create DeclRefExpr's for valid Decl's.
3230   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3231     return ExprError();
3232 
3233   // Handle members of anonymous structs and unions.  If we got here,
3234   // and the reference is to a class member indirect field, then this
3235   // must be the subject of a pointer-to-member expression.
3236   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3237     if (!indirectField->isCXXClassMember())
3238       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3239                                                       indirectField);
3240 
3241   {
3242     QualType type = VD->getType();
3243     if (type.isNull())
3244       return ExprError();
3245     ExprValueKind valueKind = VK_RValue;
3246 
3247     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3248     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3249     // is expanded by some outer '...' in the context of the use.
3250     type = type.getNonPackExpansionType();
3251 
3252     switch (D->getKind()) {
3253     // Ignore all the non-ValueDecl kinds.
3254 #define ABSTRACT_DECL(kind)
3255 #define VALUE(type, base)
3256 #define DECL(type, base) \
3257     case Decl::type:
3258 #include "clang/AST/DeclNodes.inc"
3259       llvm_unreachable("invalid value decl kind");
3260 
3261     // These shouldn't make it here.
3262     case Decl::ObjCAtDefsField:
3263       llvm_unreachable("forming non-member reference to ivar?");
3264 
3265     // Enum constants are always r-values and never references.
3266     // Unresolved using declarations are dependent.
3267     case Decl::EnumConstant:
3268     case Decl::UnresolvedUsingValue:
3269     case Decl::OMPDeclareReduction:
3270     case Decl::OMPDeclareMapper:
3271       valueKind = VK_RValue;
3272       break;
3273 
3274     // Fields and indirect fields that got here must be for
3275     // pointer-to-member expressions; we just call them l-values for
3276     // internal consistency, because this subexpression doesn't really
3277     // exist in the high-level semantics.
3278     case Decl::Field:
3279     case Decl::IndirectField:
3280     case Decl::ObjCIvar:
3281       assert(getLangOpts().CPlusPlus &&
3282              "building reference to field in C?");
3283 
3284       // These can't have reference type in well-formed programs, but
3285       // for internal consistency we do this anyway.
3286       type = type.getNonReferenceType();
3287       valueKind = VK_LValue;
3288       break;
3289 
3290     // Non-type template parameters are either l-values or r-values
3291     // depending on the type.
3292     case Decl::NonTypeTemplateParm: {
3293       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3294         type = reftype->getPointeeType();
3295         valueKind = VK_LValue; // even if the parameter is an r-value reference
3296         break;
3297       }
3298 
3299       // [expr.prim.id.unqual]p2:
3300       //   If the entity is a template parameter object for a template
3301       //   parameter of type T, the type of the expression is const T.
3302       //   [...] The expression is an lvalue if the entity is a [...] template
3303       //   parameter object.
3304       if (type->isRecordType()) {
3305         type = type.getUnqualifiedType().withConst();
3306         valueKind = VK_LValue;
3307         break;
3308       }
3309 
3310       // For non-references, we need to strip qualifiers just in case
3311       // the template parameter was declared as 'const int' or whatever.
3312       valueKind = VK_RValue;
3313       type = type.getUnqualifiedType();
3314       break;
3315     }
3316 
3317     case Decl::Var:
3318     case Decl::VarTemplateSpecialization:
3319     case Decl::VarTemplatePartialSpecialization:
3320     case Decl::Decomposition:
3321     case Decl::OMPCapturedExpr:
3322       // In C, "extern void blah;" is valid and is an r-value.
3323       if (!getLangOpts().CPlusPlus &&
3324           !type.hasQualifiers() &&
3325           type->isVoidType()) {
3326         valueKind = VK_RValue;
3327         break;
3328       }
3329       LLVM_FALLTHROUGH;
3330 
3331     case Decl::ImplicitParam:
3332     case Decl::ParmVar: {
3333       // These are always l-values.
3334       valueKind = VK_LValue;
3335       type = type.getNonReferenceType();
3336 
3337       // FIXME: Does the addition of const really only apply in
3338       // potentially-evaluated contexts? Since the variable isn't actually
3339       // captured in an unevaluated context, it seems that the answer is no.
3340       if (!isUnevaluatedContext()) {
3341         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3342         if (!CapturedType.isNull())
3343           type = CapturedType;
3344       }
3345 
3346       break;
3347     }
3348 
3349     case Decl::Binding: {
3350       // These are always lvalues.
3351       valueKind = VK_LValue;
3352       type = type.getNonReferenceType();
3353       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3354       // decides how that's supposed to work.
3355       auto *BD = cast<BindingDecl>(VD);
3356       if (BD->getDeclContext() != CurContext) {
3357         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3358         if (DD && DD->hasLocalStorage())
3359           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3360       }
3361       break;
3362     }
3363 
3364     case Decl::Function: {
3365       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3366         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3367           type = Context.BuiltinFnTy;
3368           valueKind = VK_RValue;
3369           break;
3370         }
3371       }
3372 
3373       const FunctionType *fty = type->castAs<FunctionType>();
3374 
3375       // If we're referring to a function with an __unknown_anytype
3376       // result type, make the entire expression __unknown_anytype.
3377       if (fty->getReturnType() == Context.UnknownAnyTy) {
3378         type = Context.UnknownAnyTy;
3379         valueKind = VK_RValue;
3380         break;
3381       }
3382 
3383       // Functions are l-values in C++.
3384       if (getLangOpts().CPlusPlus) {
3385         valueKind = VK_LValue;
3386         break;
3387       }
3388 
3389       // C99 DR 316 says that, if a function type comes from a
3390       // function definition (without a prototype), that type is only
3391       // used for checking compatibility. Therefore, when referencing
3392       // the function, we pretend that we don't have the full function
3393       // type.
3394       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3395           isa<FunctionProtoType>(fty))
3396         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3397                                               fty->getExtInfo());
3398 
3399       // Functions are r-values in C.
3400       valueKind = VK_RValue;
3401       break;
3402     }
3403 
3404     case Decl::CXXDeductionGuide:
3405       llvm_unreachable("building reference to deduction guide");
3406 
3407     case Decl::MSProperty:
3408     case Decl::MSGuid:
3409     case Decl::TemplateParamObject:
3410       // FIXME: Should MSGuidDecl and template parameter objects be subject to
3411       // capture in OpenMP, or duplicated between host and device?
3412       valueKind = VK_LValue;
3413       break;
3414 
3415     case Decl::CXXMethod:
3416       // If we're referring to a method with an __unknown_anytype
3417       // result type, make the entire expression __unknown_anytype.
3418       // This should only be possible with a type written directly.
3419       if (const FunctionProtoType *proto
3420             = dyn_cast<FunctionProtoType>(VD->getType()))
3421         if (proto->getReturnType() == Context.UnknownAnyTy) {
3422           type = Context.UnknownAnyTy;
3423           valueKind = VK_RValue;
3424           break;
3425         }
3426 
3427       // C++ methods are l-values if static, r-values if non-static.
3428       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3429         valueKind = VK_LValue;
3430         break;
3431       }
3432       LLVM_FALLTHROUGH;
3433 
3434     case Decl::CXXConversion:
3435     case Decl::CXXDestructor:
3436     case Decl::CXXConstructor:
3437       valueKind = VK_RValue;
3438       break;
3439     }
3440 
3441     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3442                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3443                             TemplateArgs);
3444   }
3445 }
3446 
3447 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3448                                     SmallString<32> &Target) {
3449   Target.resize(CharByteWidth * (Source.size() + 1));
3450   char *ResultPtr = &Target[0];
3451   const llvm::UTF8 *ErrorPtr;
3452   bool success =
3453       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3454   (void)success;
3455   assert(success);
3456   Target.resize(ResultPtr - &Target[0]);
3457 }
3458 
3459 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3460                                      PredefinedExpr::IdentKind IK) {
3461   // Pick the current block, lambda, captured statement or function.
3462   Decl *currentDecl = nullptr;
3463   if (const BlockScopeInfo *BSI = getCurBlock())
3464     currentDecl = BSI->TheDecl;
3465   else if (const LambdaScopeInfo *LSI = getCurLambda())
3466     currentDecl = LSI->CallOperator;
3467   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3468     currentDecl = CSI->TheCapturedDecl;
3469   else
3470     currentDecl = getCurFunctionOrMethodDecl();
3471 
3472   if (!currentDecl) {
3473     Diag(Loc, diag::ext_predef_outside_function);
3474     currentDecl = Context.getTranslationUnitDecl();
3475   }
3476 
3477   QualType ResTy;
3478   StringLiteral *SL = nullptr;
3479   if (cast<DeclContext>(currentDecl)->isDependentContext())
3480     ResTy = Context.DependentTy;
3481   else {
3482     // Pre-defined identifiers are of type char[x], where x is the length of
3483     // the string.
3484     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3485     unsigned Length = Str.length();
3486 
3487     llvm::APInt LengthI(32, Length + 1);
3488     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3489       ResTy =
3490           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3491       SmallString<32> RawChars;
3492       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3493                               Str, RawChars);
3494       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3495                                            ArrayType::Normal,
3496                                            /*IndexTypeQuals*/ 0);
3497       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3498                                  /*Pascal*/ false, ResTy, Loc);
3499     } else {
3500       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3501       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3502                                            ArrayType::Normal,
3503                                            /*IndexTypeQuals*/ 0);
3504       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3505                                  /*Pascal*/ false, ResTy, Loc);
3506     }
3507   }
3508 
3509   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3510 }
3511 
3512 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3513   PredefinedExpr::IdentKind IK;
3514 
3515   switch (Kind) {
3516   default: llvm_unreachable("Unknown simple primary expr!");
3517   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3518   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3519   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3520   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3521   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3522   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3523   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3524   }
3525 
3526   return BuildPredefinedExpr(Loc, IK);
3527 }
3528 
3529 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3530   SmallString<16> CharBuffer;
3531   bool Invalid = false;
3532   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3533   if (Invalid)
3534     return ExprError();
3535 
3536   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3537                             PP, Tok.getKind());
3538   if (Literal.hadError())
3539     return ExprError();
3540 
3541   QualType Ty;
3542   if (Literal.isWide())
3543     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3544   else if (Literal.isUTF8() && getLangOpts().Char8)
3545     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3546   else if (Literal.isUTF16())
3547     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3548   else if (Literal.isUTF32())
3549     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3550   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3551     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3552   else
3553     Ty = Context.CharTy;  // 'x' -> char in C++
3554 
3555   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3556   if (Literal.isWide())
3557     Kind = CharacterLiteral::Wide;
3558   else if (Literal.isUTF16())
3559     Kind = CharacterLiteral::UTF16;
3560   else if (Literal.isUTF32())
3561     Kind = CharacterLiteral::UTF32;
3562   else if (Literal.isUTF8())
3563     Kind = CharacterLiteral::UTF8;
3564 
3565   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3566                                              Tok.getLocation());
3567 
3568   if (Literal.getUDSuffix().empty())
3569     return Lit;
3570 
3571   // We're building a user-defined literal.
3572   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3573   SourceLocation UDSuffixLoc =
3574     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3575 
3576   // Make sure we're allowed user-defined literals here.
3577   if (!UDLScope)
3578     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3579 
3580   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3581   //   operator "" X (ch)
3582   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3583                                         Lit, Tok.getLocation());
3584 }
3585 
3586 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3587   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3588   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3589                                 Context.IntTy, Loc);
3590 }
3591 
3592 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3593                                   QualType Ty, SourceLocation Loc) {
3594   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3595 
3596   using llvm::APFloat;
3597   APFloat Val(Format);
3598 
3599   APFloat::opStatus result = Literal.GetFloatValue(Val);
3600 
3601   // Overflow is always an error, but underflow is only an error if
3602   // we underflowed to zero (APFloat reports denormals as underflow).
3603   if ((result & APFloat::opOverflow) ||
3604       ((result & APFloat::opUnderflow) && Val.isZero())) {
3605     unsigned diagnostic;
3606     SmallString<20> buffer;
3607     if (result & APFloat::opOverflow) {
3608       diagnostic = diag::warn_float_overflow;
3609       APFloat::getLargest(Format).toString(buffer);
3610     } else {
3611       diagnostic = diag::warn_float_underflow;
3612       APFloat::getSmallest(Format).toString(buffer);
3613     }
3614 
3615     S.Diag(Loc, diagnostic)
3616       << Ty
3617       << StringRef(buffer.data(), buffer.size());
3618   }
3619 
3620   bool isExact = (result == APFloat::opOK);
3621   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3622 }
3623 
3624 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3625   assert(E && "Invalid expression");
3626 
3627   if (E->isValueDependent())
3628     return false;
3629 
3630   QualType QT = E->getType();
3631   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3632     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3633     return true;
3634   }
3635 
3636   llvm::APSInt ValueAPS;
3637   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3638 
3639   if (R.isInvalid())
3640     return true;
3641 
3642   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3643   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3644     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3645         << ValueAPS.toString(10) << ValueIsPositive;
3646     return true;
3647   }
3648 
3649   return false;
3650 }
3651 
3652 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3653   // Fast path for a single digit (which is quite common).  A single digit
3654   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3655   if (Tok.getLength() == 1) {
3656     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3657     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3658   }
3659 
3660   SmallString<128> SpellingBuffer;
3661   // NumericLiteralParser wants to overread by one character.  Add padding to
3662   // the buffer in case the token is copied to the buffer.  If getSpelling()
3663   // returns a StringRef to the memory buffer, it should have a null char at
3664   // the EOF, so it is also safe.
3665   SpellingBuffer.resize(Tok.getLength() + 1);
3666 
3667   // Get the spelling of the token, which eliminates trigraphs, etc.
3668   bool Invalid = false;
3669   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3670   if (Invalid)
3671     return ExprError();
3672 
3673   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3674                                PP.getSourceManager(), PP.getLangOpts(),
3675                                PP.getTargetInfo(), PP.getDiagnostics());
3676   if (Literal.hadError)
3677     return ExprError();
3678 
3679   if (Literal.hasUDSuffix()) {
3680     // We're building a user-defined literal.
3681     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3682     SourceLocation UDSuffixLoc =
3683       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3684 
3685     // Make sure we're allowed user-defined literals here.
3686     if (!UDLScope)
3687       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3688 
3689     QualType CookedTy;
3690     if (Literal.isFloatingLiteral()) {
3691       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3692       // long double, the literal is treated as a call of the form
3693       //   operator "" X (f L)
3694       CookedTy = Context.LongDoubleTy;
3695     } else {
3696       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3697       // unsigned long long, the literal is treated as a call of the form
3698       //   operator "" X (n ULL)
3699       CookedTy = Context.UnsignedLongLongTy;
3700     }
3701 
3702     DeclarationName OpName =
3703       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3704     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3705     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3706 
3707     SourceLocation TokLoc = Tok.getLocation();
3708 
3709     // Perform literal operator lookup to determine if we're building a raw
3710     // literal or a cooked one.
3711     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3712     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3713                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3714                                   /*AllowStringTemplatePack*/ false,
3715                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3716     case LOLR_ErrorNoDiagnostic:
3717       // Lookup failure for imaginary constants isn't fatal, there's still the
3718       // GNU extension producing _Complex types.
3719       break;
3720     case LOLR_Error:
3721       return ExprError();
3722     case LOLR_Cooked: {
3723       Expr *Lit;
3724       if (Literal.isFloatingLiteral()) {
3725         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3726       } else {
3727         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3728         if (Literal.GetIntegerValue(ResultVal))
3729           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3730               << /* Unsigned */ 1;
3731         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3732                                      Tok.getLocation());
3733       }
3734       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3735     }
3736 
3737     case LOLR_Raw: {
3738       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3739       // literal is treated as a call of the form
3740       //   operator "" X ("n")
3741       unsigned Length = Literal.getUDSuffixOffset();
3742       QualType StrTy = Context.getConstantArrayType(
3743           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3744           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3745       Expr *Lit = StringLiteral::Create(
3746           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3747           /*Pascal*/false, StrTy, &TokLoc, 1);
3748       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3749     }
3750 
3751     case LOLR_Template: {
3752       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3753       // template), L is treated as a call fo the form
3754       //   operator "" X <'c1', 'c2', ... 'ck'>()
3755       // where n is the source character sequence c1 c2 ... ck.
3756       TemplateArgumentListInfo ExplicitArgs;
3757       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3758       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3759       llvm::APSInt Value(CharBits, CharIsUnsigned);
3760       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3761         Value = TokSpelling[I];
3762         TemplateArgument Arg(Context, Value, Context.CharTy);
3763         TemplateArgumentLocInfo ArgInfo;
3764         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3765       }
3766       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3767                                       &ExplicitArgs);
3768     }
3769     case LOLR_StringTemplatePack:
3770       llvm_unreachable("unexpected literal operator lookup result");
3771     }
3772   }
3773 
3774   Expr *Res;
3775 
3776   if (Literal.isFixedPointLiteral()) {
3777     QualType Ty;
3778 
3779     if (Literal.isAccum) {
3780       if (Literal.isHalf) {
3781         Ty = Context.ShortAccumTy;
3782       } else if (Literal.isLong) {
3783         Ty = Context.LongAccumTy;
3784       } else {
3785         Ty = Context.AccumTy;
3786       }
3787     } else if (Literal.isFract) {
3788       if (Literal.isHalf) {
3789         Ty = Context.ShortFractTy;
3790       } else if (Literal.isLong) {
3791         Ty = Context.LongFractTy;
3792       } else {
3793         Ty = Context.FractTy;
3794       }
3795     }
3796 
3797     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3798 
3799     bool isSigned = !Literal.isUnsigned;
3800     unsigned scale = Context.getFixedPointScale(Ty);
3801     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3802 
3803     llvm::APInt Val(bit_width, 0, isSigned);
3804     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3805     bool ValIsZero = Val.isNullValue() && !Overflowed;
3806 
3807     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3808     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3809       // Clause 6.4.4 - The value of a constant shall be in the range of
3810       // representable values for its type, with exception for constants of a
3811       // fract type with a value of exactly 1; such a constant shall denote
3812       // the maximal value for the type.
3813       --Val;
3814     else if (Val.ugt(MaxVal) || Overflowed)
3815       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3816 
3817     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3818                                               Tok.getLocation(), scale);
3819   } else if (Literal.isFloatingLiteral()) {
3820     QualType Ty;
3821     if (Literal.isHalf){
3822       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3823         Ty = Context.HalfTy;
3824       else {
3825         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3826         return ExprError();
3827       }
3828     } else if (Literal.isFloat)
3829       Ty = Context.FloatTy;
3830     else if (Literal.isLong)
3831       Ty = Context.LongDoubleTy;
3832     else if (Literal.isFloat16)
3833       Ty = Context.Float16Ty;
3834     else if (Literal.isFloat128)
3835       Ty = Context.Float128Ty;
3836     else
3837       Ty = Context.DoubleTy;
3838 
3839     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3840 
3841     if (Ty == Context.DoubleTy) {
3842       if (getLangOpts().SinglePrecisionConstants) {
3843         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3844           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3845         }
3846       } else if (getLangOpts().OpenCL &&
3847                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3848         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3849         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3850         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3851       }
3852     }
3853   } else if (!Literal.isIntegerLiteral()) {
3854     return ExprError();
3855   } else {
3856     QualType Ty;
3857 
3858     // 'long long' is a C99 or C++11 feature.
3859     if (!getLangOpts().C99 && Literal.isLongLong) {
3860       if (getLangOpts().CPlusPlus)
3861         Diag(Tok.getLocation(),
3862              getLangOpts().CPlusPlus11 ?
3863              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3864       else
3865         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3866     }
3867 
3868     // Get the value in the widest-possible width.
3869     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3870     llvm::APInt ResultVal(MaxWidth, 0);
3871 
3872     if (Literal.GetIntegerValue(ResultVal)) {
3873       // If this value didn't fit into uintmax_t, error and force to ull.
3874       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3875           << /* Unsigned */ 1;
3876       Ty = Context.UnsignedLongLongTy;
3877       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3878              "long long is not intmax_t?");
3879     } else {
3880       // If this value fits into a ULL, try to figure out what else it fits into
3881       // according to the rules of C99 6.4.4.1p5.
3882 
3883       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3884       // be an unsigned int.
3885       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3886 
3887       // Check from smallest to largest, picking the smallest type we can.
3888       unsigned Width = 0;
3889 
3890       // Microsoft specific integer suffixes are explicitly sized.
3891       if (Literal.MicrosoftInteger) {
3892         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3893           Width = 8;
3894           Ty = Context.CharTy;
3895         } else {
3896           Width = Literal.MicrosoftInteger;
3897           Ty = Context.getIntTypeForBitwidth(Width,
3898                                              /*Signed=*/!Literal.isUnsigned);
3899         }
3900       }
3901 
3902       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3903         // Are int/unsigned possibilities?
3904         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3905 
3906         // Does it fit in a unsigned int?
3907         if (ResultVal.isIntN(IntSize)) {
3908           // Does it fit in a signed int?
3909           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3910             Ty = Context.IntTy;
3911           else if (AllowUnsigned)
3912             Ty = Context.UnsignedIntTy;
3913           Width = IntSize;
3914         }
3915       }
3916 
3917       // Are long/unsigned long possibilities?
3918       if (Ty.isNull() && !Literal.isLongLong) {
3919         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3920 
3921         // Does it fit in a unsigned long?
3922         if (ResultVal.isIntN(LongSize)) {
3923           // Does it fit in a signed long?
3924           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3925             Ty = Context.LongTy;
3926           else if (AllowUnsigned)
3927             Ty = Context.UnsignedLongTy;
3928           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3929           // is compatible.
3930           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3931             const unsigned LongLongSize =
3932                 Context.getTargetInfo().getLongLongWidth();
3933             Diag(Tok.getLocation(),
3934                  getLangOpts().CPlusPlus
3935                      ? Literal.isLong
3936                            ? diag::warn_old_implicitly_unsigned_long_cxx
3937                            : /*C++98 UB*/ diag::
3938                                  ext_old_implicitly_unsigned_long_cxx
3939                      : diag::warn_old_implicitly_unsigned_long)
3940                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3941                                             : /*will be ill-formed*/ 1);
3942             Ty = Context.UnsignedLongTy;
3943           }
3944           Width = LongSize;
3945         }
3946       }
3947 
3948       // Check long long if needed.
3949       if (Ty.isNull()) {
3950         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3951 
3952         // Does it fit in a unsigned long long?
3953         if (ResultVal.isIntN(LongLongSize)) {
3954           // Does it fit in a signed long long?
3955           // To be compatible with MSVC, hex integer literals ending with the
3956           // LL or i64 suffix are always signed in Microsoft mode.
3957           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3958               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3959             Ty = Context.LongLongTy;
3960           else if (AllowUnsigned)
3961             Ty = Context.UnsignedLongLongTy;
3962           Width = LongLongSize;
3963         }
3964       }
3965 
3966       // If we still couldn't decide a type, we probably have something that
3967       // does not fit in a signed long long, but has no U suffix.
3968       if (Ty.isNull()) {
3969         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3970         Ty = Context.UnsignedLongLongTy;
3971         Width = Context.getTargetInfo().getLongLongWidth();
3972       }
3973 
3974       if (ResultVal.getBitWidth() != Width)
3975         ResultVal = ResultVal.trunc(Width);
3976     }
3977     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3978   }
3979 
3980   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3981   if (Literal.isImaginary) {
3982     Res = new (Context) ImaginaryLiteral(Res,
3983                                         Context.getComplexType(Res->getType()));
3984 
3985     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3986   }
3987   return Res;
3988 }
3989 
3990 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3991   assert(E && "ActOnParenExpr() missing expr");
3992   return new (Context) ParenExpr(L, R, E);
3993 }
3994 
3995 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3996                                          SourceLocation Loc,
3997                                          SourceRange ArgRange) {
3998   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3999   // scalar or vector data type argument..."
4000   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4001   // type (C99 6.2.5p18) or void.
4002   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4003     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4004       << T << ArgRange;
4005     return true;
4006   }
4007 
4008   assert((T->isVoidType() || !T->isIncompleteType()) &&
4009          "Scalar types should always be complete");
4010   return false;
4011 }
4012 
4013 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4014                                            SourceLocation Loc,
4015                                            SourceRange ArgRange,
4016                                            UnaryExprOrTypeTrait TraitKind) {
4017   // Invalid types must be hard errors for SFINAE in C++.
4018   if (S.LangOpts.CPlusPlus)
4019     return true;
4020 
4021   // C99 6.5.3.4p1:
4022   if (T->isFunctionType() &&
4023       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4024        TraitKind == UETT_PreferredAlignOf)) {
4025     // sizeof(function)/alignof(function) is allowed as an extension.
4026     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4027         << getTraitSpelling(TraitKind) << ArgRange;
4028     return false;
4029   }
4030 
4031   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4032   // this is an error (OpenCL v1.1 s6.3.k)
4033   if (T->isVoidType()) {
4034     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4035                                         : diag::ext_sizeof_alignof_void_type;
4036     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4037     return false;
4038   }
4039 
4040   return true;
4041 }
4042 
4043 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4044                                              SourceLocation Loc,
4045                                              SourceRange ArgRange,
4046                                              UnaryExprOrTypeTrait TraitKind) {
4047   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4048   // runtime doesn't allow it.
4049   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4050     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4051       << T << (TraitKind == UETT_SizeOf)
4052       << ArgRange;
4053     return true;
4054   }
4055 
4056   return false;
4057 }
4058 
4059 /// Check whether E is a pointer from a decayed array type (the decayed
4060 /// pointer type is equal to T) and emit a warning if it is.
4061 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4062                                      Expr *E) {
4063   // Don't warn if the operation changed the type.
4064   if (T != E->getType())
4065     return;
4066 
4067   // Now look for array decays.
4068   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4069   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4070     return;
4071 
4072   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4073                                              << ICE->getType()
4074                                              << ICE->getSubExpr()->getType();
4075 }
4076 
4077 /// Check the constraints on expression operands to unary type expression
4078 /// and type traits.
4079 ///
4080 /// Completes any types necessary and validates the constraints on the operand
4081 /// expression. The logic mostly mirrors the type-based overload, but may modify
4082 /// the expression as it completes the type for that expression through template
4083 /// instantiation, etc.
4084 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4085                                             UnaryExprOrTypeTrait ExprKind) {
4086   QualType ExprTy = E->getType();
4087   assert(!ExprTy->isReferenceType());
4088 
4089   bool IsUnevaluatedOperand =
4090       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4091        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4092   if (IsUnevaluatedOperand) {
4093     ExprResult Result = CheckUnevaluatedOperand(E);
4094     if (Result.isInvalid())
4095       return true;
4096     E = Result.get();
4097   }
4098 
4099   // The operand for sizeof and alignof is in an unevaluated expression context,
4100   // so side effects could result in unintended consequences.
4101   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4102   // used to build SFINAE gadgets.
4103   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4104   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4105       !E->isInstantiationDependent() &&
4106       E->HasSideEffects(Context, false))
4107     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4108 
4109   if (ExprKind == UETT_VecStep)
4110     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4111                                         E->getSourceRange());
4112 
4113   // Explicitly list some types as extensions.
4114   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4115                                       E->getSourceRange(), ExprKind))
4116     return false;
4117 
4118   // 'alignof' applied to an expression only requires the base element type of
4119   // the expression to be complete. 'sizeof' requires the expression's type to
4120   // be complete (and will attempt to complete it if it's an array of unknown
4121   // bound).
4122   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4123     if (RequireCompleteSizedType(
4124             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4125             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4126             getTraitSpelling(ExprKind), E->getSourceRange()))
4127       return true;
4128   } else {
4129     if (RequireCompleteSizedExprType(
4130             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4131             getTraitSpelling(ExprKind), E->getSourceRange()))
4132       return true;
4133   }
4134 
4135   // Completing the expression's type may have changed it.
4136   ExprTy = E->getType();
4137   assert(!ExprTy->isReferenceType());
4138 
4139   if (ExprTy->isFunctionType()) {
4140     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4141         << getTraitSpelling(ExprKind) << E->getSourceRange();
4142     return true;
4143   }
4144 
4145   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4146                                        E->getSourceRange(), ExprKind))
4147     return true;
4148 
4149   if (ExprKind == UETT_SizeOf) {
4150     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4151       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4152         QualType OType = PVD->getOriginalType();
4153         QualType Type = PVD->getType();
4154         if (Type->isPointerType() && OType->isArrayType()) {
4155           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4156             << Type << OType;
4157           Diag(PVD->getLocation(), diag::note_declared_at);
4158         }
4159       }
4160     }
4161 
4162     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4163     // decays into a pointer and returns an unintended result. This is most
4164     // likely a typo for "sizeof(array) op x".
4165     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4166       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4167                                BO->getLHS());
4168       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4169                                BO->getRHS());
4170     }
4171   }
4172 
4173   return false;
4174 }
4175 
4176 /// Check the constraints on operands to unary expression and type
4177 /// traits.
4178 ///
4179 /// This will complete any types necessary, and validate the various constraints
4180 /// on those operands.
4181 ///
4182 /// The UsualUnaryConversions() function is *not* called by this routine.
4183 /// C99 6.3.2.1p[2-4] all state:
4184 ///   Except when it is the operand of the sizeof operator ...
4185 ///
4186 /// C++ [expr.sizeof]p4
4187 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4188 ///   standard conversions are not applied to the operand of sizeof.
4189 ///
4190 /// This policy is followed for all of the unary trait expressions.
4191 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4192                                             SourceLocation OpLoc,
4193                                             SourceRange ExprRange,
4194                                             UnaryExprOrTypeTrait ExprKind) {
4195   if (ExprType->isDependentType())
4196     return false;
4197 
4198   // C++ [expr.sizeof]p2:
4199   //     When applied to a reference or a reference type, the result
4200   //     is the size of the referenced type.
4201   // C++11 [expr.alignof]p3:
4202   //     When alignof is applied to a reference type, the result
4203   //     shall be the alignment of the referenced type.
4204   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4205     ExprType = Ref->getPointeeType();
4206 
4207   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4208   //   When alignof or _Alignof is applied to an array type, the result
4209   //   is the alignment of the element type.
4210   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4211       ExprKind == UETT_OpenMPRequiredSimdAlign)
4212     ExprType = Context.getBaseElementType(ExprType);
4213 
4214   if (ExprKind == UETT_VecStep)
4215     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4216 
4217   // Explicitly list some types as extensions.
4218   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4219                                       ExprKind))
4220     return false;
4221 
4222   if (RequireCompleteSizedType(
4223           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4224           getTraitSpelling(ExprKind), ExprRange))
4225     return true;
4226 
4227   if (ExprType->isFunctionType()) {
4228     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4229         << getTraitSpelling(ExprKind) << ExprRange;
4230     return true;
4231   }
4232 
4233   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4234                                        ExprKind))
4235     return true;
4236 
4237   return false;
4238 }
4239 
4240 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4241   // Cannot know anything else if the expression is dependent.
4242   if (E->isTypeDependent())
4243     return false;
4244 
4245   if (E->getObjectKind() == OK_BitField) {
4246     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4247        << 1 << E->getSourceRange();
4248     return true;
4249   }
4250 
4251   ValueDecl *D = nullptr;
4252   Expr *Inner = E->IgnoreParens();
4253   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4254     D = DRE->getDecl();
4255   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4256     D = ME->getMemberDecl();
4257   }
4258 
4259   // If it's a field, require the containing struct to have a
4260   // complete definition so that we can compute the layout.
4261   //
4262   // This can happen in C++11 onwards, either by naming the member
4263   // in a way that is not transformed into a member access expression
4264   // (in an unevaluated operand, for instance), or by naming the member
4265   // in a trailing-return-type.
4266   //
4267   // For the record, since __alignof__ on expressions is a GCC
4268   // extension, GCC seems to permit this but always gives the
4269   // nonsensical answer 0.
4270   //
4271   // We don't really need the layout here --- we could instead just
4272   // directly check for all the appropriate alignment-lowing
4273   // attributes --- but that would require duplicating a lot of
4274   // logic that just isn't worth duplicating for such a marginal
4275   // use-case.
4276   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4277     // Fast path this check, since we at least know the record has a
4278     // definition if we can find a member of it.
4279     if (!FD->getParent()->isCompleteDefinition()) {
4280       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4281         << E->getSourceRange();
4282       return true;
4283     }
4284 
4285     // Otherwise, if it's a field, and the field doesn't have
4286     // reference type, then it must have a complete type (or be a
4287     // flexible array member, which we explicitly want to
4288     // white-list anyway), which makes the following checks trivial.
4289     if (!FD->getType()->isReferenceType())
4290       return false;
4291   }
4292 
4293   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4294 }
4295 
4296 bool Sema::CheckVecStepExpr(Expr *E) {
4297   E = E->IgnoreParens();
4298 
4299   // Cannot know anything else if the expression is dependent.
4300   if (E->isTypeDependent())
4301     return false;
4302 
4303   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4304 }
4305 
4306 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4307                                         CapturingScopeInfo *CSI) {
4308   assert(T->isVariablyModifiedType());
4309   assert(CSI != nullptr);
4310 
4311   // We're going to walk down into the type and look for VLA expressions.
4312   do {
4313     const Type *Ty = T.getTypePtr();
4314     switch (Ty->getTypeClass()) {
4315 #define TYPE(Class, Base)
4316 #define ABSTRACT_TYPE(Class, Base)
4317 #define NON_CANONICAL_TYPE(Class, Base)
4318 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4319 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4320 #include "clang/AST/TypeNodes.inc"
4321       T = QualType();
4322       break;
4323     // These types are never variably-modified.
4324     case Type::Builtin:
4325     case Type::Complex:
4326     case Type::Vector:
4327     case Type::ExtVector:
4328     case Type::ConstantMatrix:
4329     case Type::Record:
4330     case Type::Enum:
4331     case Type::Elaborated:
4332     case Type::TemplateSpecialization:
4333     case Type::ObjCObject:
4334     case Type::ObjCInterface:
4335     case Type::ObjCObjectPointer:
4336     case Type::ObjCTypeParam:
4337     case Type::Pipe:
4338     case Type::ExtInt:
4339       llvm_unreachable("type class is never variably-modified!");
4340     case Type::Adjusted:
4341       T = cast<AdjustedType>(Ty)->getOriginalType();
4342       break;
4343     case Type::Decayed:
4344       T = cast<DecayedType>(Ty)->getPointeeType();
4345       break;
4346     case Type::Pointer:
4347       T = cast<PointerType>(Ty)->getPointeeType();
4348       break;
4349     case Type::BlockPointer:
4350       T = cast<BlockPointerType>(Ty)->getPointeeType();
4351       break;
4352     case Type::LValueReference:
4353     case Type::RValueReference:
4354       T = cast<ReferenceType>(Ty)->getPointeeType();
4355       break;
4356     case Type::MemberPointer:
4357       T = cast<MemberPointerType>(Ty)->getPointeeType();
4358       break;
4359     case Type::ConstantArray:
4360     case Type::IncompleteArray:
4361       // Losing element qualification here is fine.
4362       T = cast<ArrayType>(Ty)->getElementType();
4363       break;
4364     case Type::VariableArray: {
4365       // Losing element qualification here is fine.
4366       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4367 
4368       // Unknown size indication requires no size computation.
4369       // Otherwise, evaluate and record it.
4370       auto Size = VAT->getSizeExpr();
4371       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4372           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4373         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4374 
4375       T = VAT->getElementType();
4376       break;
4377     }
4378     case Type::FunctionProto:
4379     case Type::FunctionNoProto:
4380       T = cast<FunctionType>(Ty)->getReturnType();
4381       break;
4382     case Type::Paren:
4383     case Type::TypeOf:
4384     case Type::UnaryTransform:
4385     case Type::Attributed:
4386     case Type::SubstTemplateTypeParm:
4387     case Type::MacroQualified:
4388       // Keep walking after single level desugaring.
4389       T = T.getSingleStepDesugaredType(Context);
4390       break;
4391     case Type::Typedef:
4392       T = cast<TypedefType>(Ty)->desugar();
4393       break;
4394     case Type::Decltype:
4395       T = cast<DecltypeType>(Ty)->desugar();
4396       break;
4397     case Type::Auto:
4398     case Type::DeducedTemplateSpecialization:
4399       T = cast<DeducedType>(Ty)->getDeducedType();
4400       break;
4401     case Type::TypeOfExpr:
4402       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4403       break;
4404     case Type::Atomic:
4405       T = cast<AtomicType>(Ty)->getValueType();
4406       break;
4407     }
4408   } while (!T.isNull() && T->isVariablyModifiedType());
4409 }
4410 
4411 /// Build a sizeof or alignof expression given a type operand.
4412 ExprResult
4413 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4414                                      SourceLocation OpLoc,
4415                                      UnaryExprOrTypeTrait ExprKind,
4416                                      SourceRange R) {
4417   if (!TInfo)
4418     return ExprError();
4419 
4420   QualType T = TInfo->getType();
4421 
4422   if (!T->isDependentType() &&
4423       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4424     return ExprError();
4425 
4426   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4427     if (auto *TT = T->getAs<TypedefType>()) {
4428       for (auto I = FunctionScopes.rbegin(),
4429                 E = std::prev(FunctionScopes.rend());
4430            I != E; ++I) {
4431         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4432         if (CSI == nullptr)
4433           break;
4434         DeclContext *DC = nullptr;
4435         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4436           DC = LSI->CallOperator;
4437         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4438           DC = CRSI->TheCapturedDecl;
4439         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4440           DC = BSI->TheDecl;
4441         if (DC) {
4442           if (DC->containsDecl(TT->getDecl()))
4443             break;
4444           captureVariablyModifiedType(Context, T, CSI);
4445         }
4446       }
4447     }
4448   }
4449 
4450   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4451   return new (Context) UnaryExprOrTypeTraitExpr(
4452       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4453 }
4454 
4455 /// Build a sizeof or alignof expression given an expression
4456 /// operand.
4457 ExprResult
4458 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4459                                      UnaryExprOrTypeTrait ExprKind) {
4460   ExprResult PE = CheckPlaceholderExpr(E);
4461   if (PE.isInvalid())
4462     return ExprError();
4463 
4464   E = PE.get();
4465 
4466   // Verify that the operand is valid.
4467   bool isInvalid = false;
4468   if (E->isTypeDependent()) {
4469     // Delay type-checking for type-dependent expressions.
4470   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4471     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4472   } else if (ExprKind == UETT_VecStep) {
4473     isInvalid = CheckVecStepExpr(E);
4474   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4475       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4476       isInvalid = true;
4477   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4478     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4479     isInvalid = true;
4480   } else {
4481     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4482   }
4483 
4484   if (isInvalid)
4485     return ExprError();
4486 
4487   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4488     PE = TransformToPotentiallyEvaluated(E);
4489     if (PE.isInvalid()) return ExprError();
4490     E = PE.get();
4491   }
4492 
4493   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4494   return new (Context) UnaryExprOrTypeTraitExpr(
4495       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4496 }
4497 
4498 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4499 /// expr and the same for @c alignof and @c __alignof
4500 /// Note that the ArgRange is invalid if isType is false.
4501 ExprResult
4502 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4503                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4504                                     void *TyOrEx, SourceRange ArgRange) {
4505   // If error parsing type, ignore.
4506   if (!TyOrEx) return ExprError();
4507 
4508   if (IsType) {
4509     TypeSourceInfo *TInfo;
4510     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4511     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4512   }
4513 
4514   Expr *ArgEx = (Expr *)TyOrEx;
4515   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4516   return Result;
4517 }
4518 
4519 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4520                                      bool IsReal) {
4521   if (V.get()->isTypeDependent())
4522     return S.Context.DependentTy;
4523 
4524   // _Real and _Imag are only l-values for normal l-values.
4525   if (V.get()->getObjectKind() != OK_Ordinary) {
4526     V = S.DefaultLvalueConversion(V.get());
4527     if (V.isInvalid())
4528       return QualType();
4529   }
4530 
4531   // These operators return the element type of a complex type.
4532   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4533     return CT->getElementType();
4534 
4535   // Otherwise they pass through real integer and floating point types here.
4536   if (V.get()->getType()->isArithmeticType())
4537     return V.get()->getType();
4538 
4539   // Test for placeholders.
4540   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4541   if (PR.isInvalid()) return QualType();
4542   if (PR.get() != V.get()) {
4543     V = PR;
4544     return CheckRealImagOperand(S, V, Loc, IsReal);
4545   }
4546 
4547   // Reject anything else.
4548   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4549     << (IsReal ? "__real" : "__imag");
4550   return QualType();
4551 }
4552 
4553 
4554 
4555 ExprResult
4556 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4557                           tok::TokenKind Kind, Expr *Input) {
4558   UnaryOperatorKind Opc;
4559   switch (Kind) {
4560   default: llvm_unreachable("Unknown unary op!");
4561   case tok::plusplus:   Opc = UO_PostInc; break;
4562   case tok::minusminus: Opc = UO_PostDec; break;
4563   }
4564 
4565   // Since this might is a postfix expression, get rid of ParenListExprs.
4566   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4567   if (Result.isInvalid()) return ExprError();
4568   Input = Result.get();
4569 
4570   return BuildUnaryOp(S, OpLoc, Opc, Input);
4571 }
4572 
4573 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4574 ///
4575 /// \return true on error
4576 static bool checkArithmeticOnObjCPointer(Sema &S,
4577                                          SourceLocation opLoc,
4578                                          Expr *op) {
4579   assert(op->getType()->isObjCObjectPointerType());
4580   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4581       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4582     return false;
4583 
4584   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4585     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4586     << op->getSourceRange();
4587   return true;
4588 }
4589 
4590 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4591   auto *BaseNoParens = Base->IgnoreParens();
4592   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4593     return MSProp->getPropertyDecl()->getType()->isArrayType();
4594   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4595 }
4596 
4597 ExprResult
4598 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4599                               Expr *idx, SourceLocation rbLoc) {
4600   if (base && !base->getType().isNull() &&
4601       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4602     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4603                                     SourceLocation(), /*Length*/ nullptr,
4604                                     /*Stride=*/nullptr, rbLoc);
4605 
4606   // Since this might be a postfix expression, get rid of ParenListExprs.
4607   if (isa<ParenListExpr>(base)) {
4608     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4609     if (result.isInvalid()) return ExprError();
4610     base = result.get();
4611   }
4612 
4613   // Check if base and idx form a MatrixSubscriptExpr.
4614   //
4615   // Helper to check for comma expressions, which are not allowed as indices for
4616   // matrix subscript expressions.
4617   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4618     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4619       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4620           << SourceRange(base->getBeginLoc(), rbLoc);
4621       return true;
4622     }
4623     return false;
4624   };
4625   // The matrix subscript operator ([][])is considered a single operator.
4626   // Separating the index expressions by parenthesis is not allowed.
4627   if (base->getType()->isSpecificPlaceholderType(
4628           BuiltinType::IncompleteMatrixIdx) &&
4629       !isa<MatrixSubscriptExpr>(base)) {
4630     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4631         << SourceRange(base->getBeginLoc(), rbLoc);
4632     return ExprError();
4633   }
4634   // If the base is a MatrixSubscriptExpr, try to create a new
4635   // MatrixSubscriptExpr.
4636   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4637   if (matSubscriptE) {
4638     if (CheckAndReportCommaError(idx))
4639       return ExprError();
4640 
4641     assert(matSubscriptE->isIncomplete() &&
4642            "base has to be an incomplete matrix subscript");
4643     return CreateBuiltinMatrixSubscriptExpr(
4644         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4645   }
4646 
4647   // Handle any non-overload placeholder types in the base and index
4648   // expressions.  We can't handle overloads here because the other
4649   // operand might be an overloadable type, in which case the overload
4650   // resolution for the operator overload should get the first crack
4651   // at the overload.
4652   bool IsMSPropertySubscript = false;
4653   if (base->getType()->isNonOverloadPlaceholderType()) {
4654     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4655     if (!IsMSPropertySubscript) {
4656       ExprResult result = CheckPlaceholderExpr(base);
4657       if (result.isInvalid())
4658         return ExprError();
4659       base = result.get();
4660     }
4661   }
4662 
4663   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4664   if (base->getType()->isMatrixType()) {
4665     if (CheckAndReportCommaError(idx))
4666       return ExprError();
4667 
4668     return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4669   }
4670 
4671   // A comma-expression as the index is deprecated in C++2a onwards.
4672   if (getLangOpts().CPlusPlus20 &&
4673       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4674        (isa<CXXOperatorCallExpr>(idx) &&
4675         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4676     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4677         << SourceRange(base->getBeginLoc(), rbLoc);
4678   }
4679 
4680   if (idx->getType()->isNonOverloadPlaceholderType()) {
4681     ExprResult result = CheckPlaceholderExpr(idx);
4682     if (result.isInvalid()) return ExprError();
4683     idx = result.get();
4684   }
4685 
4686   // Build an unanalyzed expression if either operand is type-dependent.
4687   if (getLangOpts().CPlusPlus &&
4688       (base->isTypeDependent() || idx->isTypeDependent())) {
4689     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4690                                             VK_LValue, OK_Ordinary, rbLoc);
4691   }
4692 
4693   // MSDN, property (C++)
4694   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4695   // This attribute can also be used in the declaration of an empty array in a
4696   // class or structure definition. For example:
4697   // __declspec(property(get=GetX, put=PutX)) int x[];
4698   // The above statement indicates that x[] can be used with one or more array
4699   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4700   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4701   if (IsMSPropertySubscript) {
4702     // Build MS property subscript expression if base is MS property reference
4703     // or MS property subscript.
4704     return new (Context) MSPropertySubscriptExpr(
4705         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4706   }
4707 
4708   // Use C++ overloaded-operator rules if either operand has record
4709   // type.  The spec says to do this if either type is *overloadable*,
4710   // but enum types can't declare subscript operators or conversion
4711   // operators, so there's nothing interesting for overload resolution
4712   // to do if there aren't any record types involved.
4713   //
4714   // ObjC pointers have their own subscripting logic that is not tied
4715   // to overload resolution and so should not take this path.
4716   if (getLangOpts().CPlusPlus &&
4717       (base->getType()->isRecordType() ||
4718        (!base->getType()->isObjCObjectPointerType() &&
4719         idx->getType()->isRecordType()))) {
4720     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4721   }
4722 
4723   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4724 
4725   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4726     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4727 
4728   return Res;
4729 }
4730 
4731 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4732   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4733   InitializationKind Kind =
4734       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4735   InitializationSequence InitSeq(*this, Entity, Kind, E);
4736   return InitSeq.Perform(*this, Entity, Kind, E);
4737 }
4738 
4739 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4740                                                   Expr *ColumnIdx,
4741                                                   SourceLocation RBLoc) {
4742   ExprResult BaseR = CheckPlaceholderExpr(Base);
4743   if (BaseR.isInvalid())
4744     return BaseR;
4745   Base = BaseR.get();
4746 
4747   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4748   if (RowR.isInvalid())
4749     return RowR;
4750   RowIdx = RowR.get();
4751 
4752   if (!ColumnIdx)
4753     return new (Context) MatrixSubscriptExpr(
4754         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4755 
4756   // Build an unanalyzed expression if any of the operands is type-dependent.
4757   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4758       ColumnIdx->isTypeDependent())
4759     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4760                                              Context.DependentTy, RBLoc);
4761 
4762   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4763   if (ColumnR.isInvalid())
4764     return ColumnR;
4765   ColumnIdx = ColumnR.get();
4766 
4767   // Check that IndexExpr is an integer expression. If it is a constant
4768   // expression, check that it is less than Dim (= the number of elements in the
4769   // corresponding dimension).
4770   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4771                           bool IsColumnIdx) -> Expr * {
4772     if (!IndexExpr->getType()->isIntegerType() &&
4773         !IndexExpr->isTypeDependent()) {
4774       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4775           << IsColumnIdx;
4776       return nullptr;
4777     }
4778 
4779     if (Optional<llvm::APSInt> Idx =
4780             IndexExpr->getIntegerConstantExpr(Context)) {
4781       if ((*Idx < 0 || *Idx >= Dim)) {
4782         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4783             << IsColumnIdx << Dim;
4784         return nullptr;
4785       }
4786     }
4787 
4788     ExprResult ConvExpr =
4789         tryConvertExprToType(IndexExpr, Context.getSizeType());
4790     assert(!ConvExpr.isInvalid() &&
4791            "should be able to convert any integer type to size type");
4792     return ConvExpr.get();
4793   };
4794 
4795   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4796   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4797   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4798   if (!RowIdx || !ColumnIdx)
4799     return ExprError();
4800 
4801   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4802                                            MTy->getElementType(), RBLoc);
4803 }
4804 
4805 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4806   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4807   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4808 
4809   // For expressions like `&(*s).b`, the base is recorded and what should be
4810   // checked.
4811   const MemberExpr *Member = nullptr;
4812   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4813     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4814 
4815   LastRecord.PossibleDerefs.erase(StrippedExpr);
4816 }
4817 
4818 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4819   if (isUnevaluatedContext())
4820     return;
4821 
4822   QualType ResultTy = E->getType();
4823   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4824 
4825   // Bail if the element is an array since it is not memory access.
4826   if (isa<ArrayType>(ResultTy))
4827     return;
4828 
4829   if (ResultTy->hasAttr(attr::NoDeref)) {
4830     LastRecord.PossibleDerefs.insert(E);
4831     return;
4832   }
4833 
4834   // Check if the base type is a pointer to a member access of a struct
4835   // marked with noderef.
4836   const Expr *Base = E->getBase();
4837   QualType BaseTy = Base->getType();
4838   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4839     // Not a pointer access
4840     return;
4841 
4842   const MemberExpr *Member = nullptr;
4843   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4844          Member->isArrow())
4845     Base = Member->getBase();
4846 
4847   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4848     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4849       LastRecord.PossibleDerefs.insert(E);
4850   }
4851 }
4852 
4853 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4854                                           Expr *LowerBound,
4855                                           SourceLocation ColonLocFirst,
4856                                           SourceLocation ColonLocSecond,
4857                                           Expr *Length, Expr *Stride,
4858                                           SourceLocation RBLoc) {
4859   if (Base->getType()->isPlaceholderType() &&
4860       !Base->getType()->isSpecificPlaceholderType(
4861           BuiltinType::OMPArraySection)) {
4862     ExprResult Result = CheckPlaceholderExpr(Base);
4863     if (Result.isInvalid())
4864       return ExprError();
4865     Base = Result.get();
4866   }
4867   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4868     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4869     if (Result.isInvalid())
4870       return ExprError();
4871     Result = DefaultLvalueConversion(Result.get());
4872     if (Result.isInvalid())
4873       return ExprError();
4874     LowerBound = Result.get();
4875   }
4876   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4877     ExprResult Result = CheckPlaceholderExpr(Length);
4878     if (Result.isInvalid())
4879       return ExprError();
4880     Result = DefaultLvalueConversion(Result.get());
4881     if (Result.isInvalid())
4882       return ExprError();
4883     Length = Result.get();
4884   }
4885   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4886     ExprResult Result = CheckPlaceholderExpr(Stride);
4887     if (Result.isInvalid())
4888       return ExprError();
4889     Result = DefaultLvalueConversion(Result.get());
4890     if (Result.isInvalid())
4891       return ExprError();
4892     Stride = Result.get();
4893   }
4894 
4895   // Build an unanalyzed expression if either operand is type-dependent.
4896   if (Base->isTypeDependent() ||
4897       (LowerBound &&
4898        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4899       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4900       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4901     return new (Context) OMPArraySectionExpr(
4902         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4903         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4904   }
4905 
4906   // Perform default conversions.
4907   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4908   QualType ResultTy;
4909   if (OriginalTy->isAnyPointerType()) {
4910     ResultTy = OriginalTy->getPointeeType();
4911   } else if (OriginalTy->isArrayType()) {
4912     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4913   } else {
4914     return ExprError(
4915         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4916         << Base->getSourceRange());
4917   }
4918   // C99 6.5.2.1p1
4919   if (LowerBound) {
4920     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4921                                                       LowerBound);
4922     if (Res.isInvalid())
4923       return ExprError(Diag(LowerBound->getExprLoc(),
4924                             diag::err_omp_typecheck_section_not_integer)
4925                        << 0 << LowerBound->getSourceRange());
4926     LowerBound = Res.get();
4927 
4928     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4929         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4930       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4931           << 0 << LowerBound->getSourceRange();
4932   }
4933   if (Length) {
4934     auto Res =
4935         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4936     if (Res.isInvalid())
4937       return ExprError(Diag(Length->getExprLoc(),
4938                             diag::err_omp_typecheck_section_not_integer)
4939                        << 1 << Length->getSourceRange());
4940     Length = Res.get();
4941 
4942     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4943         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4944       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4945           << 1 << Length->getSourceRange();
4946   }
4947   if (Stride) {
4948     ExprResult Res =
4949         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4950     if (Res.isInvalid())
4951       return ExprError(Diag(Stride->getExprLoc(),
4952                             diag::err_omp_typecheck_section_not_integer)
4953                        << 1 << Stride->getSourceRange());
4954     Stride = Res.get();
4955 
4956     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4957         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4958       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4959           << 1 << Stride->getSourceRange();
4960   }
4961 
4962   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4963   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4964   // type. Note that functions are not objects, and that (in C99 parlance)
4965   // incomplete types are not object types.
4966   if (ResultTy->isFunctionType()) {
4967     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4968         << ResultTy << Base->getSourceRange();
4969     return ExprError();
4970   }
4971 
4972   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4973                           diag::err_omp_section_incomplete_type, Base))
4974     return ExprError();
4975 
4976   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4977     Expr::EvalResult Result;
4978     if (LowerBound->EvaluateAsInt(Result, Context)) {
4979       // OpenMP 5.0, [2.1.5 Array Sections]
4980       // The array section must be a subset of the original array.
4981       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4982       if (LowerBoundValue.isNegative()) {
4983         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4984             << LowerBound->getSourceRange();
4985         return ExprError();
4986       }
4987     }
4988   }
4989 
4990   if (Length) {
4991     Expr::EvalResult Result;
4992     if (Length->EvaluateAsInt(Result, Context)) {
4993       // OpenMP 5.0, [2.1.5 Array Sections]
4994       // The length must evaluate to non-negative integers.
4995       llvm::APSInt LengthValue = Result.Val.getInt();
4996       if (LengthValue.isNegative()) {
4997         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4998             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4999             << Length->getSourceRange();
5000         return ExprError();
5001       }
5002     }
5003   } else if (ColonLocFirst.isValid() &&
5004              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5005                                       !OriginalTy->isVariableArrayType()))) {
5006     // OpenMP 5.0, [2.1.5 Array Sections]
5007     // When the size of the array dimension is not known, the length must be
5008     // specified explicitly.
5009     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5010         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5011     return ExprError();
5012   }
5013 
5014   if (Stride) {
5015     Expr::EvalResult Result;
5016     if (Stride->EvaluateAsInt(Result, Context)) {
5017       // OpenMP 5.0, [2.1.5 Array Sections]
5018       // The stride must evaluate to a positive integer.
5019       llvm::APSInt StrideValue = Result.Val.getInt();
5020       if (!StrideValue.isStrictlyPositive()) {
5021         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5022             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5023             << Stride->getSourceRange();
5024         return ExprError();
5025       }
5026     }
5027   }
5028 
5029   if (!Base->getType()->isSpecificPlaceholderType(
5030           BuiltinType::OMPArraySection)) {
5031     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5032     if (Result.isInvalid())
5033       return ExprError();
5034     Base = Result.get();
5035   }
5036   return new (Context) OMPArraySectionExpr(
5037       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5038       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5039 }
5040 
5041 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5042                                           SourceLocation RParenLoc,
5043                                           ArrayRef<Expr *> Dims,
5044                                           ArrayRef<SourceRange> Brackets) {
5045   if (Base->getType()->isPlaceholderType()) {
5046     ExprResult Result = CheckPlaceholderExpr(Base);
5047     if (Result.isInvalid())
5048       return ExprError();
5049     Result = DefaultLvalueConversion(Result.get());
5050     if (Result.isInvalid())
5051       return ExprError();
5052     Base = Result.get();
5053   }
5054   QualType BaseTy = Base->getType();
5055   // Delay analysis of the types/expressions if instantiation/specialization is
5056   // required.
5057   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5058     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5059                                        LParenLoc, RParenLoc, Dims, Brackets);
5060   if (!BaseTy->isPointerType() ||
5061       (!Base->isTypeDependent() &&
5062        BaseTy->getPointeeType()->isIncompleteType()))
5063     return ExprError(Diag(Base->getExprLoc(),
5064                           diag::err_omp_non_pointer_type_array_shaping_base)
5065                      << Base->getSourceRange());
5066 
5067   SmallVector<Expr *, 4> NewDims;
5068   bool ErrorFound = false;
5069   for (Expr *Dim : Dims) {
5070     if (Dim->getType()->isPlaceholderType()) {
5071       ExprResult Result = CheckPlaceholderExpr(Dim);
5072       if (Result.isInvalid()) {
5073         ErrorFound = true;
5074         continue;
5075       }
5076       Result = DefaultLvalueConversion(Result.get());
5077       if (Result.isInvalid()) {
5078         ErrorFound = true;
5079         continue;
5080       }
5081       Dim = Result.get();
5082     }
5083     if (!Dim->isTypeDependent()) {
5084       ExprResult Result =
5085           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5086       if (Result.isInvalid()) {
5087         ErrorFound = true;
5088         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5089             << Dim->getSourceRange();
5090         continue;
5091       }
5092       Dim = Result.get();
5093       Expr::EvalResult EvResult;
5094       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5095         // OpenMP 5.0, [2.1.4 Array Shaping]
5096         // Each si is an integral type expression that must evaluate to a
5097         // positive integer.
5098         llvm::APSInt Value = EvResult.Val.getInt();
5099         if (!Value.isStrictlyPositive()) {
5100           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5101               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5102               << Dim->getSourceRange();
5103           ErrorFound = true;
5104           continue;
5105         }
5106       }
5107     }
5108     NewDims.push_back(Dim);
5109   }
5110   if (ErrorFound)
5111     return ExprError();
5112   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5113                                      LParenLoc, RParenLoc, NewDims, Brackets);
5114 }
5115 
5116 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5117                                       SourceLocation LLoc, SourceLocation RLoc,
5118                                       ArrayRef<OMPIteratorData> Data) {
5119   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5120   bool IsCorrect = true;
5121   for (const OMPIteratorData &D : Data) {
5122     TypeSourceInfo *TInfo = nullptr;
5123     SourceLocation StartLoc;
5124     QualType DeclTy;
5125     if (!D.Type.getAsOpaquePtr()) {
5126       // OpenMP 5.0, 2.1.6 Iterators
5127       // In an iterator-specifier, if the iterator-type is not specified then
5128       // the type of that iterator is of int type.
5129       DeclTy = Context.IntTy;
5130       StartLoc = D.DeclIdentLoc;
5131     } else {
5132       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5133       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5134     }
5135 
5136     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5137                              DeclTy->containsUnexpandedParameterPack() ||
5138                              DeclTy->isInstantiationDependentType();
5139     if (!IsDeclTyDependent) {
5140       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5141         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5142         // The iterator-type must be an integral or pointer type.
5143         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5144             << DeclTy;
5145         IsCorrect = false;
5146         continue;
5147       }
5148       if (DeclTy.isConstant(Context)) {
5149         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5150         // The iterator-type must not be const qualified.
5151         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5152             << DeclTy;
5153         IsCorrect = false;
5154         continue;
5155       }
5156     }
5157 
5158     // Iterator declaration.
5159     assert(D.DeclIdent && "Identifier expected.");
5160     // Always try to create iterator declarator to avoid extra error messages
5161     // about unknown declarations use.
5162     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5163                                D.DeclIdent, DeclTy, TInfo, SC_None);
5164     VD->setImplicit();
5165     if (S) {
5166       // Check for conflicting previous declaration.
5167       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5168       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5169                             ForVisibleRedeclaration);
5170       Previous.suppressDiagnostics();
5171       LookupName(Previous, S);
5172 
5173       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5174                            /*AllowInlineNamespace=*/false);
5175       if (!Previous.empty()) {
5176         NamedDecl *Old = Previous.getRepresentativeDecl();
5177         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5178         Diag(Old->getLocation(), diag::note_previous_definition);
5179       } else {
5180         PushOnScopeChains(VD, S);
5181       }
5182     } else {
5183       CurContext->addDecl(VD);
5184     }
5185     Expr *Begin = D.Range.Begin;
5186     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5187       ExprResult BeginRes =
5188           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5189       Begin = BeginRes.get();
5190     }
5191     Expr *End = D.Range.End;
5192     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5193       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5194       End = EndRes.get();
5195     }
5196     Expr *Step = D.Range.Step;
5197     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5198       if (!Step->getType()->isIntegralType(Context)) {
5199         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5200             << Step << Step->getSourceRange();
5201         IsCorrect = false;
5202         continue;
5203       }
5204       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5205       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5206       // If the step expression of a range-specification equals zero, the
5207       // behavior is unspecified.
5208       if (Result && Result->isNullValue()) {
5209         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5210             << Step << Step->getSourceRange();
5211         IsCorrect = false;
5212         continue;
5213       }
5214     }
5215     if (!Begin || !End || !IsCorrect) {
5216       IsCorrect = false;
5217       continue;
5218     }
5219     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5220     IDElem.IteratorDecl = VD;
5221     IDElem.AssignmentLoc = D.AssignLoc;
5222     IDElem.Range.Begin = Begin;
5223     IDElem.Range.End = End;
5224     IDElem.Range.Step = Step;
5225     IDElem.ColonLoc = D.ColonLoc;
5226     IDElem.SecondColonLoc = D.SecColonLoc;
5227   }
5228   if (!IsCorrect) {
5229     // Invalidate all created iterator declarations if error is found.
5230     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5231       if (Decl *ID = D.IteratorDecl)
5232         ID->setInvalidDecl();
5233     }
5234     return ExprError();
5235   }
5236   SmallVector<OMPIteratorHelperData, 4> Helpers;
5237   if (!CurContext->isDependentContext()) {
5238     // Build number of ityeration for each iteration range.
5239     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5240     // ((Begini-Stepi-1-Endi) / -Stepi);
5241     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5242       // (Endi - Begini)
5243       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5244                                           D.Range.Begin);
5245       if(!Res.isUsable()) {
5246         IsCorrect = false;
5247         continue;
5248       }
5249       ExprResult St, St1;
5250       if (D.Range.Step) {
5251         St = D.Range.Step;
5252         // (Endi - Begini) + Stepi
5253         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5254         if (!Res.isUsable()) {
5255           IsCorrect = false;
5256           continue;
5257         }
5258         // (Endi - Begini) + Stepi - 1
5259         Res =
5260             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5261                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5262         if (!Res.isUsable()) {
5263           IsCorrect = false;
5264           continue;
5265         }
5266         // ((Endi - Begini) + Stepi - 1) / Stepi
5267         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5268         if (!Res.isUsable()) {
5269           IsCorrect = false;
5270           continue;
5271         }
5272         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5273         // (Begini - Endi)
5274         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5275                                              D.Range.Begin, D.Range.End);
5276         if (!Res1.isUsable()) {
5277           IsCorrect = false;
5278           continue;
5279         }
5280         // (Begini - Endi) - Stepi
5281         Res1 =
5282             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5283         if (!Res1.isUsable()) {
5284           IsCorrect = false;
5285           continue;
5286         }
5287         // (Begini - Endi) - Stepi - 1
5288         Res1 =
5289             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5290                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5291         if (!Res1.isUsable()) {
5292           IsCorrect = false;
5293           continue;
5294         }
5295         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5296         Res1 =
5297             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5298         if (!Res1.isUsable()) {
5299           IsCorrect = false;
5300           continue;
5301         }
5302         // Stepi > 0.
5303         ExprResult CmpRes =
5304             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5305                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5306         if (!CmpRes.isUsable()) {
5307           IsCorrect = false;
5308           continue;
5309         }
5310         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5311                                  Res.get(), Res1.get());
5312         if (!Res.isUsable()) {
5313           IsCorrect = false;
5314           continue;
5315         }
5316       }
5317       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5318       if (!Res.isUsable()) {
5319         IsCorrect = false;
5320         continue;
5321       }
5322 
5323       // Build counter update.
5324       // Build counter.
5325       auto *CounterVD =
5326           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5327                           D.IteratorDecl->getBeginLoc(), nullptr,
5328                           Res.get()->getType(), nullptr, SC_None);
5329       CounterVD->setImplicit();
5330       ExprResult RefRes =
5331           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5332                            D.IteratorDecl->getBeginLoc());
5333       // Build counter update.
5334       // I = Begini + counter * Stepi;
5335       ExprResult UpdateRes;
5336       if (D.Range.Step) {
5337         UpdateRes = CreateBuiltinBinOp(
5338             D.AssignmentLoc, BO_Mul,
5339             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5340       } else {
5341         UpdateRes = DefaultLvalueConversion(RefRes.get());
5342       }
5343       if (!UpdateRes.isUsable()) {
5344         IsCorrect = false;
5345         continue;
5346       }
5347       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5348                                      UpdateRes.get());
5349       if (!UpdateRes.isUsable()) {
5350         IsCorrect = false;
5351         continue;
5352       }
5353       ExprResult VDRes =
5354           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5355                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5356                            D.IteratorDecl->getBeginLoc());
5357       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5358                                      UpdateRes.get());
5359       if (!UpdateRes.isUsable()) {
5360         IsCorrect = false;
5361         continue;
5362       }
5363       UpdateRes =
5364           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5365       if (!UpdateRes.isUsable()) {
5366         IsCorrect = false;
5367         continue;
5368       }
5369       ExprResult CounterUpdateRes =
5370           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5371       if (!CounterUpdateRes.isUsable()) {
5372         IsCorrect = false;
5373         continue;
5374       }
5375       CounterUpdateRes =
5376           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5377       if (!CounterUpdateRes.isUsable()) {
5378         IsCorrect = false;
5379         continue;
5380       }
5381       OMPIteratorHelperData &HD = Helpers.emplace_back();
5382       HD.CounterVD = CounterVD;
5383       HD.Upper = Res.get();
5384       HD.Update = UpdateRes.get();
5385       HD.CounterUpdate = CounterUpdateRes.get();
5386     }
5387   } else {
5388     Helpers.assign(ID.size(), {});
5389   }
5390   if (!IsCorrect) {
5391     // Invalidate all created iterator declarations if error is found.
5392     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5393       if (Decl *ID = D.IteratorDecl)
5394         ID->setInvalidDecl();
5395     }
5396     return ExprError();
5397   }
5398   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5399                                  LLoc, RLoc, ID, Helpers);
5400 }
5401 
5402 ExprResult
5403 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5404                                       Expr *Idx, SourceLocation RLoc) {
5405   Expr *LHSExp = Base;
5406   Expr *RHSExp = Idx;
5407 
5408   ExprValueKind VK = VK_LValue;
5409   ExprObjectKind OK = OK_Ordinary;
5410 
5411   // Per C++ core issue 1213, the result is an xvalue if either operand is
5412   // a non-lvalue array, and an lvalue otherwise.
5413   if (getLangOpts().CPlusPlus11) {
5414     for (auto *Op : {LHSExp, RHSExp}) {
5415       Op = Op->IgnoreImplicit();
5416       if (Op->getType()->isArrayType() && !Op->isLValue())
5417         VK = VK_XValue;
5418     }
5419   }
5420 
5421   // Perform default conversions.
5422   if (!LHSExp->getType()->getAs<VectorType>()) {
5423     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5424     if (Result.isInvalid())
5425       return ExprError();
5426     LHSExp = Result.get();
5427   }
5428   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5429   if (Result.isInvalid())
5430     return ExprError();
5431   RHSExp = Result.get();
5432 
5433   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5434 
5435   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5436   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5437   // in the subscript position. As a result, we need to derive the array base
5438   // and index from the expression types.
5439   Expr *BaseExpr, *IndexExpr;
5440   QualType ResultType;
5441   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5442     BaseExpr = LHSExp;
5443     IndexExpr = RHSExp;
5444     ResultType = Context.DependentTy;
5445   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5446     BaseExpr = LHSExp;
5447     IndexExpr = RHSExp;
5448     ResultType = PTy->getPointeeType();
5449   } else if (const ObjCObjectPointerType *PTy =
5450                LHSTy->getAs<ObjCObjectPointerType>()) {
5451     BaseExpr = LHSExp;
5452     IndexExpr = RHSExp;
5453 
5454     // Use custom logic if this should be the pseudo-object subscript
5455     // expression.
5456     if (!LangOpts.isSubscriptPointerArithmetic())
5457       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5458                                           nullptr);
5459 
5460     ResultType = PTy->getPointeeType();
5461   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5462      // Handle the uncommon case of "123[Ptr]".
5463     BaseExpr = RHSExp;
5464     IndexExpr = LHSExp;
5465     ResultType = PTy->getPointeeType();
5466   } else if (const ObjCObjectPointerType *PTy =
5467                RHSTy->getAs<ObjCObjectPointerType>()) {
5468      // Handle the uncommon case of "123[Ptr]".
5469     BaseExpr = RHSExp;
5470     IndexExpr = LHSExp;
5471     ResultType = PTy->getPointeeType();
5472     if (!LangOpts.isSubscriptPointerArithmetic()) {
5473       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5474         << ResultType << BaseExpr->getSourceRange();
5475       return ExprError();
5476     }
5477   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5478     BaseExpr = LHSExp;    // vectors: V[123]
5479     IndexExpr = RHSExp;
5480     // We apply C++ DR1213 to vector subscripting too.
5481     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5482       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5483       if (Materialized.isInvalid())
5484         return ExprError();
5485       LHSExp = Materialized.get();
5486     }
5487     VK = LHSExp->getValueKind();
5488     if (VK != VK_RValue)
5489       OK = OK_VectorComponent;
5490 
5491     ResultType = VTy->getElementType();
5492     QualType BaseType = BaseExpr->getType();
5493     Qualifiers BaseQuals = BaseType.getQualifiers();
5494     Qualifiers MemberQuals = ResultType.getQualifiers();
5495     Qualifiers Combined = BaseQuals + MemberQuals;
5496     if (Combined != MemberQuals)
5497       ResultType = Context.getQualifiedType(ResultType, Combined);
5498   } else if (LHSTy->isArrayType()) {
5499     // If we see an array that wasn't promoted by
5500     // DefaultFunctionArrayLvalueConversion, it must be an array that
5501     // wasn't promoted because of the C90 rule that doesn't
5502     // allow promoting non-lvalue arrays.  Warn, then
5503     // force the promotion here.
5504     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5505         << LHSExp->getSourceRange();
5506     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5507                                CK_ArrayToPointerDecay).get();
5508     LHSTy = LHSExp->getType();
5509 
5510     BaseExpr = LHSExp;
5511     IndexExpr = RHSExp;
5512     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5513   } else if (RHSTy->isArrayType()) {
5514     // Same as previous, except for 123[f().a] case
5515     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5516         << RHSExp->getSourceRange();
5517     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5518                                CK_ArrayToPointerDecay).get();
5519     RHSTy = RHSExp->getType();
5520 
5521     BaseExpr = RHSExp;
5522     IndexExpr = LHSExp;
5523     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5524   } else {
5525     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5526        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5527   }
5528   // C99 6.5.2.1p1
5529   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5530     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5531                      << IndexExpr->getSourceRange());
5532 
5533   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5534        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5535          && !IndexExpr->isTypeDependent())
5536     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5537 
5538   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5539   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5540   // type. Note that Functions are not objects, and that (in C99 parlance)
5541   // incomplete types are not object types.
5542   if (ResultType->isFunctionType()) {
5543     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5544         << ResultType << BaseExpr->getSourceRange();
5545     return ExprError();
5546   }
5547 
5548   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5549     // GNU extension: subscripting on pointer to void
5550     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5551       << BaseExpr->getSourceRange();
5552 
5553     // C forbids expressions of unqualified void type from being l-values.
5554     // See IsCForbiddenLValueType.
5555     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5556   } else if (!ResultType->isDependentType() &&
5557              RequireCompleteSizedType(
5558                  LLoc, ResultType,
5559                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5560     return ExprError();
5561 
5562   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5563          !ResultType.isCForbiddenLValueType());
5564 
5565   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5566       FunctionScopes.size() > 1) {
5567     if (auto *TT =
5568             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5569       for (auto I = FunctionScopes.rbegin(),
5570                 E = std::prev(FunctionScopes.rend());
5571            I != E; ++I) {
5572         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5573         if (CSI == nullptr)
5574           break;
5575         DeclContext *DC = nullptr;
5576         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5577           DC = LSI->CallOperator;
5578         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5579           DC = CRSI->TheCapturedDecl;
5580         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5581           DC = BSI->TheDecl;
5582         if (DC) {
5583           if (DC->containsDecl(TT->getDecl()))
5584             break;
5585           captureVariablyModifiedType(
5586               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5587         }
5588       }
5589     }
5590   }
5591 
5592   return new (Context)
5593       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5594 }
5595 
5596 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5597                                   ParmVarDecl *Param) {
5598   if (Param->hasUnparsedDefaultArg()) {
5599     // If we've already cleared out the location for the default argument,
5600     // that means we're parsing it right now.
5601     if (!UnparsedDefaultArgLocs.count(Param)) {
5602       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5603       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5604       Param->setInvalidDecl();
5605       return true;
5606     }
5607 
5608     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5609         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5610     Diag(UnparsedDefaultArgLocs[Param],
5611          diag::note_default_argument_declared_here);
5612     return true;
5613   }
5614 
5615   if (Param->hasUninstantiatedDefaultArg() &&
5616       InstantiateDefaultArgument(CallLoc, FD, Param))
5617     return true;
5618 
5619   assert(Param->hasInit() && "default argument but no initializer?");
5620 
5621   // If the default expression creates temporaries, we need to
5622   // push them to the current stack of expression temporaries so they'll
5623   // be properly destroyed.
5624   // FIXME: We should really be rebuilding the default argument with new
5625   // bound temporaries; see the comment in PR5810.
5626   // We don't need to do that with block decls, though, because
5627   // blocks in default argument expression can never capture anything.
5628   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5629     // Set the "needs cleanups" bit regardless of whether there are
5630     // any explicit objects.
5631     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5632 
5633     // Append all the objects to the cleanup list.  Right now, this
5634     // should always be a no-op, because blocks in default argument
5635     // expressions should never be able to capture anything.
5636     assert(!Init->getNumObjects() &&
5637            "default argument expression has capturing blocks?");
5638   }
5639 
5640   // We already type-checked the argument, so we know it works.
5641   // Just mark all of the declarations in this potentially-evaluated expression
5642   // as being "referenced".
5643   EnterExpressionEvaluationContext EvalContext(
5644       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5645   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5646                                    /*SkipLocalVariables=*/true);
5647   return false;
5648 }
5649 
5650 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5651                                         FunctionDecl *FD, ParmVarDecl *Param) {
5652   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5653   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5654     return ExprError();
5655   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5656 }
5657 
5658 Sema::VariadicCallType
5659 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5660                           Expr *Fn) {
5661   if (Proto && Proto->isVariadic()) {
5662     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5663       return VariadicConstructor;
5664     else if (Fn && Fn->getType()->isBlockPointerType())
5665       return VariadicBlock;
5666     else if (FDecl) {
5667       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5668         if (Method->isInstance())
5669           return VariadicMethod;
5670     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5671       return VariadicMethod;
5672     return VariadicFunction;
5673   }
5674   return VariadicDoesNotApply;
5675 }
5676 
5677 namespace {
5678 class FunctionCallCCC final : public FunctionCallFilterCCC {
5679 public:
5680   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5681                   unsigned NumArgs, MemberExpr *ME)
5682       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5683         FunctionName(FuncName) {}
5684 
5685   bool ValidateCandidate(const TypoCorrection &candidate) override {
5686     if (!candidate.getCorrectionSpecifier() ||
5687         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5688       return false;
5689     }
5690 
5691     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5692   }
5693 
5694   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5695     return std::make_unique<FunctionCallCCC>(*this);
5696   }
5697 
5698 private:
5699   const IdentifierInfo *const FunctionName;
5700 };
5701 }
5702 
5703 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5704                                                FunctionDecl *FDecl,
5705                                                ArrayRef<Expr *> Args) {
5706   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5707   DeclarationName FuncName = FDecl->getDeclName();
5708   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5709 
5710   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5711   if (TypoCorrection Corrected = S.CorrectTypo(
5712           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5713           S.getScopeForContext(S.CurContext), nullptr, CCC,
5714           Sema::CTK_ErrorRecovery)) {
5715     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5716       if (Corrected.isOverloaded()) {
5717         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5718         OverloadCandidateSet::iterator Best;
5719         for (NamedDecl *CD : Corrected) {
5720           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5721             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5722                                    OCS);
5723         }
5724         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5725         case OR_Success:
5726           ND = Best->FoundDecl;
5727           Corrected.setCorrectionDecl(ND);
5728           break;
5729         default:
5730           break;
5731         }
5732       }
5733       ND = ND->getUnderlyingDecl();
5734       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5735         return Corrected;
5736     }
5737   }
5738   return TypoCorrection();
5739 }
5740 
5741 /// ConvertArgumentsForCall - Converts the arguments specified in
5742 /// Args/NumArgs to the parameter types of the function FDecl with
5743 /// function prototype Proto. Call is the call expression itself, and
5744 /// Fn is the function expression. For a C++ member function, this
5745 /// routine does not attempt to convert the object argument. Returns
5746 /// true if the call is ill-formed.
5747 bool
5748 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5749                               FunctionDecl *FDecl,
5750                               const FunctionProtoType *Proto,
5751                               ArrayRef<Expr *> Args,
5752                               SourceLocation RParenLoc,
5753                               bool IsExecConfig) {
5754   // Bail out early if calling a builtin with custom typechecking.
5755   if (FDecl)
5756     if (unsigned ID = FDecl->getBuiltinID())
5757       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5758         return false;
5759 
5760   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5761   // assignment, to the types of the corresponding parameter, ...
5762   unsigned NumParams = Proto->getNumParams();
5763   bool Invalid = false;
5764   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5765   unsigned FnKind = Fn->getType()->isBlockPointerType()
5766                        ? 1 /* block */
5767                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5768                                        : 0 /* function */);
5769 
5770   // If too few arguments are available (and we don't have default
5771   // arguments for the remaining parameters), don't make the call.
5772   if (Args.size() < NumParams) {
5773     if (Args.size() < MinArgs) {
5774       TypoCorrection TC;
5775       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5776         unsigned diag_id =
5777             MinArgs == NumParams && !Proto->isVariadic()
5778                 ? diag::err_typecheck_call_too_few_args_suggest
5779                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5780         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5781                                         << static_cast<unsigned>(Args.size())
5782                                         << TC.getCorrectionRange());
5783       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5784         Diag(RParenLoc,
5785              MinArgs == NumParams && !Proto->isVariadic()
5786                  ? diag::err_typecheck_call_too_few_args_one
5787                  : diag::err_typecheck_call_too_few_args_at_least_one)
5788             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5789       else
5790         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5791                             ? diag::err_typecheck_call_too_few_args
5792                             : diag::err_typecheck_call_too_few_args_at_least)
5793             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5794             << Fn->getSourceRange();
5795 
5796       // Emit the location of the prototype.
5797       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5798         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5799 
5800       return true;
5801     }
5802     // We reserve space for the default arguments when we create
5803     // the call expression, before calling ConvertArgumentsForCall.
5804     assert((Call->getNumArgs() == NumParams) &&
5805            "We should have reserved space for the default arguments before!");
5806   }
5807 
5808   // If too many are passed and not variadic, error on the extras and drop
5809   // them.
5810   if (Args.size() > NumParams) {
5811     if (!Proto->isVariadic()) {
5812       TypoCorrection TC;
5813       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5814         unsigned diag_id =
5815             MinArgs == NumParams && !Proto->isVariadic()
5816                 ? diag::err_typecheck_call_too_many_args_suggest
5817                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5818         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5819                                         << static_cast<unsigned>(Args.size())
5820                                         << TC.getCorrectionRange());
5821       } else if (NumParams == 1 && FDecl &&
5822                  FDecl->getParamDecl(0)->getDeclName())
5823         Diag(Args[NumParams]->getBeginLoc(),
5824              MinArgs == NumParams
5825                  ? diag::err_typecheck_call_too_many_args_one
5826                  : diag::err_typecheck_call_too_many_args_at_most_one)
5827             << FnKind << FDecl->getParamDecl(0)
5828             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5829             << SourceRange(Args[NumParams]->getBeginLoc(),
5830                            Args.back()->getEndLoc());
5831       else
5832         Diag(Args[NumParams]->getBeginLoc(),
5833              MinArgs == NumParams
5834                  ? diag::err_typecheck_call_too_many_args
5835                  : diag::err_typecheck_call_too_many_args_at_most)
5836             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5837             << Fn->getSourceRange()
5838             << SourceRange(Args[NumParams]->getBeginLoc(),
5839                            Args.back()->getEndLoc());
5840 
5841       // Emit the location of the prototype.
5842       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5843         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5844 
5845       // This deletes the extra arguments.
5846       Call->shrinkNumArgs(NumParams);
5847       return true;
5848     }
5849   }
5850   SmallVector<Expr *, 8> AllArgs;
5851   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5852 
5853   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5854                                    AllArgs, CallType);
5855   if (Invalid)
5856     return true;
5857   unsigned TotalNumArgs = AllArgs.size();
5858   for (unsigned i = 0; i < TotalNumArgs; ++i)
5859     Call->setArg(i, AllArgs[i]);
5860 
5861   return false;
5862 }
5863 
5864 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5865                                   const FunctionProtoType *Proto,
5866                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5867                                   SmallVectorImpl<Expr *> &AllArgs,
5868                                   VariadicCallType CallType, bool AllowExplicit,
5869                                   bool IsListInitialization) {
5870   unsigned NumParams = Proto->getNumParams();
5871   bool Invalid = false;
5872   size_t ArgIx = 0;
5873   // Continue to check argument types (even if we have too few/many args).
5874   for (unsigned i = FirstParam; i < NumParams; i++) {
5875     QualType ProtoArgType = Proto->getParamType(i);
5876 
5877     Expr *Arg;
5878     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5879     if (ArgIx < Args.size()) {
5880       Arg = Args[ArgIx++];
5881 
5882       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5883                               diag::err_call_incomplete_argument, Arg))
5884         return true;
5885 
5886       // Strip the unbridged-cast placeholder expression off, if applicable.
5887       bool CFAudited = false;
5888       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5889           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5890           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5891         Arg = stripARCUnbridgedCast(Arg);
5892       else if (getLangOpts().ObjCAutoRefCount &&
5893                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5894                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5895         CFAudited = true;
5896 
5897       if (Proto->getExtParameterInfo(i).isNoEscape())
5898         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5899           BE->getBlockDecl()->setDoesNotEscape();
5900 
5901       InitializedEntity Entity =
5902           Param ? InitializedEntity::InitializeParameter(Context, Param,
5903                                                          ProtoArgType)
5904                 : InitializedEntity::InitializeParameter(
5905                       Context, ProtoArgType, Proto->isParamConsumed(i));
5906 
5907       // Remember that parameter belongs to a CF audited API.
5908       if (CFAudited)
5909         Entity.setParameterCFAudited();
5910 
5911       ExprResult ArgE = PerformCopyInitialization(
5912           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5913       if (ArgE.isInvalid())
5914         return true;
5915 
5916       Arg = ArgE.getAs<Expr>();
5917     } else {
5918       assert(Param && "can't use default arguments without a known callee");
5919 
5920       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5921       if (ArgExpr.isInvalid())
5922         return true;
5923 
5924       Arg = ArgExpr.getAs<Expr>();
5925     }
5926 
5927     // Check for array bounds violations for each argument to the call. This
5928     // check only triggers warnings when the argument isn't a more complex Expr
5929     // with its own checking, such as a BinaryOperator.
5930     CheckArrayAccess(Arg);
5931 
5932     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5933     CheckStaticArrayArgument(CallLoc, Param, Arg);
5934 
5935     AllArgs.push_back(Arg);
5936   }
5937 
5938   // If this is a variadic call, handle args passed through "...".
5939   if (CallType != VariadicDoesNotApply) {
5940     // Assume that extern "C" functions with variadic arguments that
5941     // return __unknown_anytype aren't *really* variadic.
5942     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5943         FDecl->isExternC()) {
5944       for (Expr *A : Args.slice(ArgIx)) {
5945         QualType paramType; // ignored
5946         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5947         Invalid |= arg.isInvalid();
5948         AllArgs.push_back(arg.get());
5949       }
5950 
5951     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5952     } else {
5953       for (Expr *A : Args.slice(ArgIx)) {
5954         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5955         Invalid |= Arg.isInvalid();
5956         AllArgs.push_back(Arg.get());
5957       }
5958     }
5959 
5960     // Check for array bounds violations.
5961     for (Expr *A : Args.slice(ArgIx))
5962       CheckArrayAccess(A);
5963   }
5964   return Invalid;
5965 }
5966 
5967 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5968   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5969   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5970     TL = DTL.getOriginalLoc();
5971   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5972     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5973       << ATL.getLocalSourceRange();
5974 }
5975 
5976 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5977 /// array parameter, check that it is non-null, and that if it is formed by
5978 /// array-to-pointer decay, the underlying array is sufficiently large.
5979 ///
5980 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5981 /// array type derivation, then for each call to the function, the value of the
5982 /// corresponding actual argument shall provide access to the first element of
5983 /// an array with at least as many elements as specified by the size expression.
5984 void
5985 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5986                                ParmVarDecl *Param,
5987                                const Expr *ArgExpr) {
5988   // Static array parameters are not supported in C++.
5989   if (!Param || getLangOpts().CPlusPlus)
5990     return;
5991 
5992   QualType OrigTy = Param->getOriginalType();
5993 
5994   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5995   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5996     return;
5997 
5998   if (ArgExpr->isNullPointerConstant(Context,
5999                                      Expr::NPC_NeverValueDependent)) {
6000     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6001     DiagnoseCalleeStaticArrayParam(*this, Param);
6002     return;
6003   }
6004 
6005   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6006   if (!CAT)
6007     return;
6008 
6009   const ConstantArrayType *ArgCAT =
6010     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6011   if (!ArgCAT)
6012     return;
6013 
6014   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6015                                              ArgCAT->getElementType())) {
6016     if (ArgCAT->getSize().ult(CAT->getSize())) {
6017       Diag(CallLoc, diag::warn_static_array_too_small)
6018           << ArgExpr->getSourceRange()
6019           << (unsigned)ArgCAT->getSize().getZExtValue()
6020           << (unsigned)CAT->getSize().getZExtValue() << 0;
6021       DiagnoseCalleeStaticArrayParam(*this, Param);
6022     }
6023     return;
6024   }
6025 
6026   Optional<CharUnits> ArgSize =
6027       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6028   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6029   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6030     Diag(CallLoc, diag::warn_static_array_too_small)
6031         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6032         << (unsigned)ParmSize->getQuantity() << 1;
6033     DiagnoseCalleeStaticArrayParam(*this, Param);
6034   }
6035 }
6036 
6037 /// Given a function expression of unknown-any type, try to rebuild it
6038 /// to have a function type.
6039 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6040 
6041 /// Is the given type a placeholder that we need to lower out
6042 /// immediately during argument processing?
6043 static bool isPlaceholderToRemoveAsArg(QualType type) {
6044   // Placeholders are never sugared.
6045   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6046   if (!placeholder) return false;
6047 
6048   switch (placeholder->getKind()) {
6049   // Ignore all the non-placeholder types.
6050 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6051   case BuiltinType::Id:
6052 #include "clang/Basic/OpenCLImageTypes.def"
6053 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6054   case BuiltinType::Id:
6055 #include "clang/Basic/OpenCLExtensionTypes.def"
6056   // In practice we'll never use this, since all SVE types are sugared
6057   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6058 #define SVE_TYPE(Name, Id, SingletonId) \
6059   case BuiltinType::Id:
6060 #include "clang/Basic/AArch64SVEACLETypes.def"
6061 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6062   case BuiltinType::Id:
6063 #include "clang/Basic/PPCTypes.def"
6064 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6065 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6066 #include "clang/AST/BuiltinTypes.def"
6067     return false;
6068 
6069   // We cannot lower out overload sets; they might validly be resolved
6070   // by the call machinery.
6071   case BuiltinType::Overload:
6072     return false;
6073 
6074   // Unbridged casts in ARC can be handled in some call positions and
6075   // should be left in place.
6076   case BuiltinType::ARCUnbridgedCast:
6077     return false;
6078 
6079   // Pseudo-objects should be converted as soon as possible.
6080   case BuiltinType::PseudoObject:
6081     return true;
6082 
6083   // The debugger mode could theoretically but currently does not try
6084   // to resolve unknown-typed arguments based on known parameter types.
6085   case BuiltinType::UnknownAny:
6086     return true;
6087 
6088   // These are always invalid as call arguments and should be reported.
6089   case BuiltinType::BoundMember:
6090   case BuiltinType::BuiltinFn:
6091   case BuiltinType::IncompleteMatrixIdx:
6092   case BuiltinType::OMPArraySection:
6093   case BuiltinType::OMPArrayShaping:
6094   case BuiltinType::OMPIterator:
6095     return true;
6096 
6097   }
6098   llvm_unreachable("bad builtin type kind");
6099 }
6100 
6101 /// Check an argument list for placeholders that we won't try to
6102 /// handle later.
6103 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6104   // Apply this processing to all the arguments at once instead of
6105   // dying at the first failure.
6106   bool hasInvalid = false;
6107   for (size_t i = 0, e = args.size(); i != e; i++) {
6108     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6109       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6110       if (result.isInvalid()) hasInvalid = true;
6111       else args[i] = result.get();
6112     }
6113   }
6114   return hasInvalid;
6115 }
6116 
6117 /// If a builtin function has a pointer argument with no explicit address
6118 /// space, then it should be able to accept a pointer to any address
6119 /// space as input.  In order to do this, we need to replace the
6120 /// standard builtin declaration with one that uses the same address space
6121 /// as the call.
6122 ///
6123 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6124 ///                  it does not contain any pointer arguments without
6125 ///                  an address space qualifer.  Otherwise the rewritten
6126 ///                  FunctionDecl is returned.
6127 /// TODO: Handle pointer return types.
6128 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6129                                                 FunctionDecl *FDecl,
6130                                                 MultiExprArg ArgExprs) {
6131 
6132   QualType DeclType = FDecl->getType();
6133   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6134 
6135   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6136       ArgExprs.size() < FT->getNumParams())
6137     return nullptr;
6138 
6139   bool NeedsNewDecl = false;
6140   unsigned i = 0;
6141   SmallVector<QualType, 8> OverloadParams;
6142 
6143   for (QualType ParamType : FT->param_types()) {
6144 
6145     // Convert array arguments to pointer to simplify type lookup.
6146     ExprResult ArgRes =
6147         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6148     if (ArgRes.isInvalid())
6149       return nullptr;
6150     Expr *Arg = ArgRes.get();
6151     QualType ArgType = Arg->getType();
6152     if (!ParamType->isPointerType() ||
6153         ParamType.hasAddressSpace() ||
6154         !ArgType->isPointerType() ||
6155         !ArgType->getPointeeType().hasAddressSpace()) {
6156       OverloadParams.push_back(ParamType);
6157       continue;
6158     }
6159 
6160     QualType PointeeType = ParamType->getPointeeType();
6161     if (PointeeType.hasAddressSpace())
6162       continue;
6163 
6164     NeedsNewDecl = true;
6165     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6166 
6167     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6168     OverloadParams.push_back(Context.getPointerType(PointeeType));
6169   }
6170 
6171   if (!NeedsNewDecl)
6172     return nullptr;
6173 
6174   FunctionProtoType::ExtProtoInfo EPI;
6175   EPI.Variadic = FT->isVariadic();
6176   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6177                                                 OverloadParams, EPI);
6178   DeclContext *Parent = FDecl->getParent();
6179   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6180                                                     FDecl->getLocation(),
6181                                                     FDecl->getLocation(),
6182                                                     FDecl->getIdentifier(),
6183                                                     OverloadTy,
6184                                                     /*TInfo=*/nullptr,
6185                                                     SC_Extern, false,
6186                                                     /*hasPrototype=*/true);
6187   SmallVector<ParmVarDecl*, 16> Params;
6188   FT = cast<FunctionProtoType>(OverloadTy);
6189   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6190     QualType ParamType = FT->getParamType(i);
6191     ParmVarDecl *Parm =
6192         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6193                                 SourceLocation(), nullptr, ParamType,
6194                                 /*TInfo=*/nullptr, SC_None, nullptr);
6195     Parm->setScopeInfo(0, i);
6196     Params.push_back(Parm);
6197   }
6198   OverloadDecl->setParams(Params);
6199   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6200   return OverloadDecl;
6201 }
6202 
6203 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6204                                     FunctionDecl *Callee,
6205                                     MultiExprArg ArgExprs) {
6206   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6207   // similar attributes) really don't like it when functions are called with an
6208   // invalid number of args.
6209   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6210                          /*PartialOverloading=*/false) &&
6211       !Callee->isVariadic())
6212     return;
6213   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6214     return;
6215 
6216   if (const EnableIfAttr *Attr =
6217           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6218     S.Diag(Fn->getBeginLoc(),
6219            isa<CXXMethodDecl>(Callee)
6220                ? diag::err_ovl_no_viable_member_function_in_call
6221                : diag::err_ovl_no_viable_function_in_call)
6222         << Callee << Callee->getSourceRange();
6223     S.Diag(Callee->getLocation(),
6224            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6225         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6226     return;
6227   }
6228 }
6229 
6230 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6231     const UnresolvedMemberExpr *const UME, Sema &S) {
6232 
6233   const auto GetFunctionLevelDCIfCXXClass =
6234       [](Sema &S) -> const CXXRecordDecl * {
6235     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6236     if (!DC || !DC->getParent())
6237       return nullptr;
6238 
6239     // If the call to some member function was made from within a member
6240     // function body 'M' return return 'M's parent.
6241     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6242       return MD->getParent()->getCanonicalDecl();
6243     // else the call was made from within a default member initializer of a
6244     // class, so return the class.
6245     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6246       return RD->getCanonicalDecl();
6247     return nullptr;
6248   };
6249   // If our DeclContext is neither a member function nor a class (in the
6250   // case of a lambda in a default member initializer), we can't have an
6251   // enclosing 'this'.
6252 
6253   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6254   if (!CurParentClass)
6255     return false;
6256 
6257   // The naming class for implicit member functions call is the class in which
6258   // name lookup starts.
6259   const CXXRecordDecl *const NamingClass =
6260       UME->getNamingClass()->getCanonicalDecl();
6261   assert(NamingClass && "Must have naming class even for implicit access");
6262 
6263   // If the unresolved member functions were found in a 'naming class' that is
6264   // related (either the same or derived from) to the class that contains the
6265   // member function that itself contained the implicit member access.
6266 
6267   return CurParentClass == NamingClass ||
6268          CurParentClass->isDerivedFrom(NamingClass);
6269 }
6270 
6271 static void
6272 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6273     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6274 
6275   if (!UME)
6276     return;
6277 
6278   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6279   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6280   // already been captured, or if this is an implicit member function call (if
6281   // it isn't, an attempt to capture 'this' should already have been made).
6282   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6283       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6284     return;
6285 
6286   // Check if the naming class in which the unresolved members were found is
6287   // related (same as or is a base of) to the enclosing class.
6288 
6289   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6290     return;
6291 
6292 
6293   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6294   // If the enclosing function is not dependent, then this lambda is
6295   // capture ready, so if we can capture this, do so.
6296   if (!EnclosingFunctionCtx->isDependentContext()) {
6297     // If the current lambda and all enclosing lambdas can capture 'this' -
6298     // then go ahead and capture 'this' (since our unresolved overload set
6299     // contains at least one non-static member function).
6300     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6301       S.CheckCXXThisCapture(CallLoc);
6302   } else if (S.CurContext->isDependentContext()) {
6303     // ... since this is an implicit member reference, that might potentially
6304     // involve a 'this' capture, mark 'this' for potential capture in
6305     // enclosing lambdas.
6306     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6307       CurLSI->addPotentialThisCapture(CallLoc);
6308   }
6309 }
6310 
6311 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6312                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6313                                Expr *ExecConfig) {
6314   ExprResult Call =
6315       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6316                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6317   if (Call.isInvalid())
6318     return Call;
6319 
6320   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6321   // language modes.
6322   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6323     if (ULE->hasExplicitTemplateArgs() &&
6324         ULE->decls_begin() == ULE->decls_end()) {
6325       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6326                                  ? diag::warn_cxx17_compat_adl_only_template_id
6327                                  : diag::ext_adl_only_template_id)
6328           << ULE->getName();
6329     }
6330   }
6331 
6332   if (LangOpts.OpenMP)
6333     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6334                            ExecConfig);
6335 
6336   return Call;
6337 }
6338 
6339 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6340 /// This provides the location of the left/right parens and a list of comma
6341 /// locations.
6342 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6343                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6344                                Expr *ExecConfig, bool IsExecConfig,
6345                                bool AllowRecovery) {
6346   // Since this might be a postfix expression, get rid of ParenListExprs.
6347   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6348   if (Result.isInvalid()) return ExprError();
6349   Fn = Result.get();
6350 
6351   if (checkArgsForPlaceholders(*this, ArgExprs))
6352     return ExprError();
6353 
6354   if (getLangOpts().CPlusPlus) {
6355     // If this is a pseudo-destructor expression, build the call immediately.
6356     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6357       if (!ArgExprs.empty()) {
6358         // Pseudo-destructor calls should not have any arguments.
6359         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6360             << FixItHint::CreateRemoval(
6361                    SourceRange(ArgExprs.front()->getBeginLoc(),
6362                                ArgExprs.back()->getEndLoc()));
6363       }
6364 
6365       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6366                               VK_RValue, RParenLoc, CurFPFeatureOverrides());
6367     }
6368     if (Fn->getType() == Context.PseudoObjectTy) {
6369       ExprResult result = CheckPlaceholderExpr(Fn);
6370       if (result.isInvalid()) return ExprError();
6371       Fn = result.get();
6372     }
6373 
6374     // Determine whether this is a dependent call inside a C++ template,
6375     // in which case we won't do any semantic analysis now.
6376     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6377       if (ExecConfig) {
6378         return CUDAKernelCallExpr::Create(
6379             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6380             Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6381       } else {
6382 
6383         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6384             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6385             Fn->getBeginLoc());
6386 
6387         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6388                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6389       }
6390     }
6391 
6392     // Determine whether this is a call to an object (C++ [over.call.object]).
6393     if (Fn->getType()->isRecordType())
6394       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6395                                           RParenLoc);
6396 
6397     if (Fn->getType() == Context.UnknownAnyTy) {
6398       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6399       if (result.isInvalid()) return ExprError();
6400       Fn = result.get();
6401     }
6402 
6403     if (Fn->getType() == Context.BoundMemberTy) {
6404       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6405                                        RParenLoc, AllowRecovery);
6406     }
6407   }
6408 
6409   // Check for overloaded calls.  This can happen even in C due to extensions.
6410   if (Fn->getType() == Context.OverloadTy) {
6411     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6412 
6413     // We aren't supposed to apply this logic if there's an '&' involved.
6414     if (!find.HasFormOfMemberPointer) {
6415       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6416         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6417                                 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6418       OverloadExpr *ovl = find.Expression;
6419       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6420         return BuildOverloadedCallExpr(
6421             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6422             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6423       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6424                                        RParenLoc, AllowRecovery);
6425     }
6426   }
6427 
6428   // If we're directly calling a function, get the appropriate declaration.
6429   if (Fn->getType() == Context.UnknownAnyTy) {
6430     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6431     if (result.isInvalid()) return ExprError();
6432     Fn = result.get();
6433   }
6434 
6435   Expr *NakedFn = Fn->IgnoreParens();
6436 
6437   bool CallingNDeclIndirectly = false;
6438   NamedDecl *NDecl = nullptr;
6439   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6440     if (UnOp->getOpcode() == UO_AddrOf) {
6441       CallingNDeclIndirectly = true;
6442       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6443     }
6444   }
6445 
6446   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6447     NDecl = DRE->getDecl();
6448 
6449     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6450     if (FDecl && FDecl->getBuiltinID()) {
6451       // Rewrite the function decl for this builtin by replacing parameters
6452       // with no explicit address space with the address space of the arguments
6453       // in ArgExprs.
6454       if ((FDecl =
6455                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6456         NDecl = FDecl;
6457         Fn = DeclRefExpr::Create(
6458             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6459             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6460             nullptr, DRE->isNonOdrUse());
6461       }
6462     }
6463   } else if (isa<MemberExpr>(NakedFn))
6464     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6465 
6466   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6467     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6468                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6469       return ExprError();
6470 
6471     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6472       return ExprError();
6473 
6474     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6475   }
6476 
6477   if (Context.isDependenceAllowed() &&
6478       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6479     assert(!getLangOpts().CPlusPlus);
6480     assert((Fn->containsErrors() ||
6481             llvm::any_of(ArgExprs,
6482                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6483            "should only occur in error-recovery path.");
6484     QualType ReturnType =
6485         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6486             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6487             : Context.DependentTy;
6488     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6489                             Expr::getValueKindForType(ReturnType), RParenLoc,
6490                             CurFPFeatureOverrides());
6491   }
6492   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6493                                ExecConfig, IsExecConfig);
6494 }
6495 
6496 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6497 ///
6498 /// __builtin_astype( value, dst type )
6499 ///
6500 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6501                                  SourceLocation BuiltinLoc,
6502                                  SourceLocation RParenLoc) {
6503   ExprValueKind VK = VK_RValue;
6504   ExprObjectKind OK = OK_Ordinary;
6505   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6506   QualType SrcTy = E->getType();
6507   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6508     return ExprError(Diag(BuiltinLoc,
6509                           diag::err_invalid_astype_of_different_size)
6510                      << DstTy
6511                      << SrcTy
6512                      << E->getSourceRange());
6513   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6514 }
6515 
6516 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6517 /// provided arguments.
6518 ///
6519 /// __builtin_convertvector( value, dst type )
6520 ///
6521 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6522                                         SourceLocation BuiltinLoc,
6523                                         SourceLocation RParenLoc) {
6524   TypeSourceInfo *TInfo;
6525   GetTypeFromParser(ParsedDestTy, &TInfo);
6526   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6527 }
6528 
6529 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6530 /// i.e. an expression not of \p OverloadTy.  The expression should
6531 /// unary-convert to an expression of function-pointer or
6532 /// block-pointer type.
6533 ///
6534 /// \param NDecl the declaration being called, if available
6535 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6536                                        SourceLocation LParenLoc,
6537                                        ArrayRef<Expr *> Args,
6538                                        SourceLocation RParenLoc, Expr *Config,
6539                                        bool IsExecConfig, ADLCallKind UsesADL) {
6540   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6541   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6542 
6543   // Functions with 'interrupt' attribute cannot be called directly.
6544   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6545     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6546     return ExprError();
6547   }
6548 
6549   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6550   // so there's some risk when calling out to non-interrupt handler functions
6551   // that the callee might not preserve them. This is easy to diagnose here,
6552   // but can be very challenging to debug.
6553   if (auto *Caller = getCurFunctionDecl())
6554     if (Caller->hasAttr<ARMInterruptAttr>()) {
6555       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6556       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6557         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6558     }
6559 
6560   // Promote the function operand.
6561   // We special-case function promotion here because we only allow promoting
6562   // builtin functions to function pointers in the callee of a call.
6563   ExprResult Result;
6564   QualType ResultTy;
6565   if (BuiltinID &&
6566       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6567     // Extract the return type from the (builtin) function pointer type.
6568     // FIXME Several builtins still have setType in
6569     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6570     // Builtins.def to ensure they are correct before removing setType calls.
6571     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6572     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6573     ResultTy = FDecl->getCallResultType();
6574   } else {
6575     Result = CallExprUnaryConversions(Fn);
6576     ResultTy = Context.BoolTy;
6577   }
6578   if (Result.isInvalid())
6579     return ExprError();
6580   Fn = Result.get();
6581 
6582   // Check for a valid function type, but only if it is not a builtin which
6583   // requires custom type checking. These will be handled by
6584   // CheckBuiltinFunctionCall below just after creation of the call expression.
6585   const FunctionType *FuncT = nullptr;
6586   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6587   retry:
6588     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6589       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6590       // have type pointer to function".
6591       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6592       if (!FuncT)
6593         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6594                          << Fn->getType() << Fn->getSourceRange());
6595     } else if (const BlockPointerType *BPT =
6596                    Fn->getType()->getAs<BlockPointerType>()) {
6597       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6598     } else {
6599       // Handle calls to expressions of unknown-any type.
6600       if (Fn->getType() == Context.UnknownAnyTy) {
6601         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6602         if (rewrite.isInvalid())
6603           return ExprError();
6604         Fn = rewrite.get();
6605         goto retry;
6606       }
6607 
6608       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6609                        << Fn->getType() << Fn->getSourceRange());
6610     }
6611   }
6612 
6613   // Get the number of parameters in the function prototype, if any.
6614   // We will allocate space for max(Args.size(), NumParams) arguments
6615   // in the call expression.
6616   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6617   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6618 
6619   CallExpr *TheCall;
6620   if (Config) {
6621     assert(UsesADL == ADLCallKind::NotADL &&
6622            "CUDAKernelCallExpr should not use ADL");
6623     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6624                                          Args, ResultTy, VK_RValue, RParenLoc,
6625                                          CurFPFeatureOverrides(), NumParams);
6626   } else {
6627     TheCall =
6628         CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6629                          CurFPFeatureOverrides(), NumParams, UsesADL);
6630   }
6631 
6632   if (!Context.isDependenceAllowed()) {
6633     // Forget about the nulled arguments since typo correction
6634     // do not handle them well.
6635     TheCall->shrinkNumArgs(Args.size());
6636     // C cannot always handle TypoExpr nodes in builtin calls and direct
6637     // function calls as their argument checking don't necessarily handle
6638     // dependent types properly, so make sure any TypoExprs have been
6639     // dealt with.
6640     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6641     if (!Result.isUsable()) return ExprError();
6642     CallExpr *TheOldCall = TheCall;
6643     TheCall = dyn_cast<CallExpr>(Result.get());
6644     bool CorrectedTypos = TheCall != TheOldCall;
6645     if (!TheCall) return Result;
6646     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6647 
6648     // A new call expression node was created if some typos were corrected.
6649     // However it may not have been constructed with enough storage. In this
6650     // case, rebuild the node with enough storage. The waste of space is
6651     // immaterial since this only happens when some typos were corrected.
6652     if (CorrectedTypos && Args.size() < NumParams) {
6653       if (Config)
6654         TheCall = CUDAKernelCallExpr::Create(
6655             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6656             RParenLoc, CurFPFeatureOverrides(), NumParams);
6657       else
6658         TheCall =
6659             CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6660                              CurFPFeatureOverrides(), NumParams, UsesADL);
6661     }
6662     // We can now handle the nulled arguments for the default arguments.
6663     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6664   }
6665 
6666   // Bail out early if calling a builtin with custom type checking.
6667   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6668     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6669 
6670   if (getLangOpts().CUDA) {
6671     if (Config) {
6672       // CUDA: Kernel calls must be to global functions
6673       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6674         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6675             << FDecl << Fn->getSourceRange());
6676 
6677       // CUDA: Kernel function must have 'void' return type
6678       if (!FuncT->getReturnType()->isVoidType() &&
6679           !FuncT->getReturnType()->getAs<AutoType>() &&
6680           !FuncT->getReturnType()->isInstantiationDependentType())
6681         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6682             << Fn->getType() << Fn->getSourceRange());
6683     } else {
6684       // CUDA: Calls to global functions must be configured
6685       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6686         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6687             << FDecl << Fn->getSourceRange());
6688     }
6689   }
6690 
6691   // Check for a valid return type
6692   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6693                           FDecl))
6694     return ExprError();
6695 
6696   // We know the result type of the call, set it.
6697   TheCall->setType(FuncT->getCallResultType(Context));
6698   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6699 
6700   if (Proto) {
6701     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6702                                 IsExecConfig))
6703       return ExprError();
6704   } else {
6705     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6706 
6707     if (FDecl) {
6708       // Check if we have too few/too many template arguments, based
6709       // on our knowledge of the function definition.
6710       const FunctionDecl *Def = nullptr;
6711       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6712         Proto = Def->getType()->getAs<FunctionProtoType>();
6713        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6714           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6715           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6716       }
6717 
6718       // If the function we're calling isn't a function prototype, but we have
6719       // a function prototype from a prior declaratiom, use that prototype.
6720       if (!FDecl->hasPrototype())
6721         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6722     }
6723 
6724     // Promote the arguments (C99 6.5.2.2p6).
6725     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6726       Expr *Arg = Args[i];
6727 
6728       if (Proto && i < Proto->getNumParams()) {
6729         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6730             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6731         ExprResult ArgE =
6732             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6733         if (ArgE.isInvalid())
6734           return true;
6735 
6736         Arg = ArgE.getAs<Expr>();
6737 
6738       } else {
6739         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6740 
6741         if (ArgE.isInvalid())
6742           return true;
6743 
6744         Arg = ArgE.getAs<Expr>();
6745       }
6746 
6747       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6748                               diag::err_call_incomplete_argument, Arg))
6749         return ExprError();
6750 
6751       TheCall->setArg(i, Arg);
6752     }
6753   }
6754 
6755   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6756     if (!Method->isStatic())
6757       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6758         << Fn->getSourceRange());
6759 
6760   // Check for sentinels
6761   if (NDecl)
6762     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6763 
6764   // Warn for unions passing across security boundary (CMSE).
6765   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6766     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6767       if (const auto *RT =
6768               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6769         if (RT->getDecl()->isOrContainsUnion())
6770           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6771               << 0 << i;
6772       }
6773     }
6774   }
6775 
6776   // Do special checking on direct calls to functions.
6777   if (FDecl) {
6778     if (CheckFunctionCall(FDecl, TheCall, Proto))
6779       return ExprError();
6780 
6781     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6782 
6783     if (BuiltinID)
6784       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6785   } else if (NDecl) {
6786     if (CheckPointerCall(NDecl, TheCall, Proto))
6787       return ExprError();
6788   } else {
6789     if (CheckOtherCall(TheCall, Proto))
6790       return ExprError();
6791   }
6792 
6793   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6794 }
6795 
6796 ExprResult
6797 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6798                            SourceLocation RParenLoc, Expr *InitExpr) {
6799   assert(Ty && "ActOnCompoundLiteral(): missing type");
6800   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6801 
6802   TypeSourceInfo *TInfo;
6803   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6804   if (!TInfo)
6805     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6806 
6807   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6808 }
6809 
6810 ExprResult
6811 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6812                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6813   QualType literalType = TInfo->getType();
6814 
6815   if (literalType->isArrayType()) {
6816     if (RequireCompleteSizedType(
6817             LParenLoc, Context.getBaseElementType(literalType),
6818             diag::err_array_incomplete_or_sizeless_type,
6819             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6820       return ExprError();
6821     if (literalType->isVariableArrayType())
6822       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6823         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6824   } else if (!literalType->isDependentType() &&
6825              RequireCompleteType(LParenLoc, literalType,
6826                diag::err_typecheck_decl_incomplete_type,
6827                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6828     return ExprError();
6829 
6830   InitializedEntity Entity
6831     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6832   InitializationKind Kind
6833     = InitializationKind::CreateCStyleCast(LParenLoc,
6834                                            SourceRange(LParenLoc, RParenLoc),
6835                                            /*InitList=*/true);
6836   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6837   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6838                                       &literalType);
6839   if (Result.isInvalid())
6840     return ExprError();
6841   LiteralExpr = Result.get();
6842 
6843   bool isFileScope = !CurContext->isFunctionOrMethod();
6844 
6845   // In C, compound literals are l-values for some reason.
6846   // For GCC compatibility, in C++, file-scope array compound literals with
6847   // constant initializers are also l-values, and compound literals are
6848   // otherwise prvalues.
6849   //
6850   // (GCC also treats C++ list-initialized file-scope array prvalues with
6851   // constant initializers as l-values, but that's non-conforming, so we don't
6852   // follow it there.)
6853   //
6854   // FIXME: It would be better to handle the lvalue cases as materializing and
6855   // lifetime-extending a temporary object, but our materialized temporaries
6856   // representation only supports lifetime extension from a variable, not "out
6857   // of thin air".
6858   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6859   // is bound to the result of applying array-to-pointer decay to the compound
6860   // literal.
6861   // FIXME: GCC supports compound literals of reference type, which should
6862   // obviously have a value kind derived from the kind of reference involved.
6863   ExprValueKind VK =
6864       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6865           ? VK_RValue
6866           : VK_LValue;
6867 
6868   if (isFileScope)
6869     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6870       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6871         Expr *Init = ILE->getInit(i);
6872         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6873       }
6874 
6875   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6876                                               VK, LiteralExpr, isFileScope);
6877   if (isFileScope) {
6878     if (!LiteralExpr->isTypeDependent() &&
6879         !LiteralExpr->isValueDependent() &&
6880         !literalType->isDependentType()) // C99 6.5.2.5p3
6881       if (CheckForConstantInitializer(LiteralExpr, literalType))
6882         return ExprError();
6883   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6884              literalType.getAddressSpace() != LangAS::Default) {
6885     // Embedded-C extensions to C99 6.5.2.5:
6886     //   "If the compound literal occurs inside the body of a function, the
6887     //   type name shall not be qualified by an address-space qualifier."
6888     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6889       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6890     return ExprError();
6891   }
6892 
6893   if (!isFileScope && !getLangOpts().CPlusPlus) {
6894     // Compound literals that have automatic storage duration are destroyed at
6895     // the end of the scope in C; in C++, they're just temporaries.
6896 
6897     // Emit diagnostics if it is or contains a C union type that is non-trivial
6898     // to destruct.
6899     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6900       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6901                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6902 
6903     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6904     if (literalType.isDestructedType()) {
6905       Cleanup.setExprNeedsCleanups(true);
6906       ExprCleanupObjects.push_back(E);
6907       getCurFunction()->setHasBranchProtectedScope();
6908     }
6909   }
6910 
6911   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6912       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6913     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6914                                        E->getInitializer()->getExprLoc());
6915 
6916   return MaybeBindToTemporary(E);
6917 }
6918 
6919 ExprResult
6920 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6921                     SourceLocation RBraceLoc) {
6922   // Only produce each kind of designated initialization diagnostic once.
6923   SourceLocation FirstDesignator;
6924   bool DiagnosedArrayDesignator = false;
6925   bool DiagnosedNestedDesignator = false;
6926   bool DiagnosedMixedDesignator = false;
6927 
6928   // Check that any designated initializers are syntactically valid in the
6929   // current language mode.
6930   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6931     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6932       if (FirstDesignator.isInvalid())
6933         FirstDesignator = DIE->getBeginLoc();
6934 
6935       if (!getLangOpts().CPlusPlus)
6936         break;
6937 
6938       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6939         DiagnosedNestedDesignator = true;
6940         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6941           << DIE->getDesignatorsSourceRange();
6942       }
6943 
6944       for (auto &Desig : DIE->designators()) {
6945         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6946           DiagnosedArrayDesignator = true;
6947           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6948             << Desig.getSourceRange();
6949         }
6950       }
6951 
6952       if (!DiagnosedMixedDesignator &&
6953           !isa<DesignatedInitExpr>(InitArgList[0])) {
6954         DiagnosedMixedDesignator = true;
6955         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6956           << DIE->getSourceRange();
6957         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6958           << InitArgList[0]->getSourceRange();
6959       }
6960     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6961                isa<DesignatedInitExpr>(InitArgList[0])) {
6962       DiagnosedMixedDesignator = true;
6963       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6964       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6965         << DIE->getSourceRange();
6966       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6967         << InitArgList[I]->getSourceRange();
6968     }
6969   }
6970 
6971   if (FirstDesignator.isValid()) {
6972     // Only diagnose designated initiaization as a C++20 extension if we didn't
6973     // already diagnose use of (non-C++20) C99 designator syntax.
6974     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6975         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6976       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6977                                 ? diag::warn_cxx17_compat_designated_init
6978                                 : diag::ext_cxx_designated_init);
6979     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6980       Diag(FirstDesignator, diag::ext_designated_init);
6981     }
6982   }
6983 
6984   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6985 }
6986 
6987 ExprResult
6988 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6989                     SourceLocation RBraceLoc) {
6990   // Semantic analysis for initializers is done by ActOnDeclarator() and
6991   // CheckInitializer() - it requires knowledge of the object being initialized.
6992 
6993   // Immediately handle non-overload placeholders.  Overloads can be
6994   // resolved contextually, but everything else here can't.
6995   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6996     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6997       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6998 
6999       // Ignore failures; dropping the entire initializer list because
7000       // of one failure would be terrible for indexing/etc.
7001       if (result.isInvalid()) continue;
7002 
7003       InitArgList[I] = result.get();
7004     }
7005   }
7006 
7007   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7008                                                RBraceLoc);
7009   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7010   return E;
7011 }
7012 
7013 /// Do an explicit extend of the given block pointer if we're in ARC.
7014 void Sema::maybeExtendBlockObject(ExprResult &E) {
7015   assert(E.get()->getType()->isBlockPointerType());
7016   assert(E.get()->isRValue());
7017 
7018   // Only do this in an r-value context.
7019   if (!getLangOpts().ObjCAutoRefCount) return;
7020 
7021   E = ImplicitCastExpr::Create(
7022       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7023       /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7024   Cleanup.setExprNeedsCleanups(true);
7025 }
7026 
7027 /// Prepare a conversion of the given expression to an ObjC object
7028 /// pointer type.
7029 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7030   QualType type = E.get()->getType();
7031   if (type->isObjCObjectPointerType()) {
7032     return CK_BitCast;
7033   } else if (type->isBlockPointerType()) {
7034     maybeExtendBlockObject(E);
7035     return CK_BlockPointerToObjCPointerCast;
7036   } else {
7037     assert(type->isPointerType());
7038     return CK_CPointerToObjCPointerCast;
7039   }
7040 }
7041 
7042 /// Prepares for a scalar cast, performing all the necessary stages
7043 /// except the final cast and returning the kind required.
7044 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7045   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7046   // Also, callers should have filtered out the invalid cases with
7047   // pointers.  Everything else should be possible.
7048 
7049   QualType SrcTy = Src.get()->getType();
7050   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7051     return CK_NoOp;
7052 
7053   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7054   case Type::STK_MemberPointer:
7055     llvm_unreachable("member pointer type in C");
7056 
7057   case Type::STK_CPointer:
7058   case Type::STK_BlockPointer:
7059   case Type::STK_ObjCObjectPointer:
7060     switch (DestTy->getScalarTypeKind()) {
7061     case Type::STK_CPointer: {
7062       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7063       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7064       if (SrcAS != DestAS)
7065         return CK_AddressSpaceConversion;
7066       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7067         return CK_NoOp;
7068       return CK_BitCast;
7069     }
7070     case Type::STK_BlockPointer:
7071       return (SrcKind == Type::STK_BlockPointer
7072                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7073     case Type::STK_ObjCObjectPointer:
7074       if (SrcKind == Type::STK_ObjCObjectPointer)
7075         return CK_BitCast;
7076       if (SrcKind == Type::STK_CPointer)
7077         return CK_CPointerToObjCPointerCast;
7078       maybeExtendBlockObject(Src);
7079       return CK_BlockPointerToObjCPointerCast;
7080     case Type::STK_Bool:
7081       return CK_PointerToBoolean;
7082     case Type::STK_Integral:
7083       return CK_PointerToIntegral;
7084     case Type::STK_Floating:
7085     case Type::STK_FloatingComplex:
7086     case Type::STK_IntegralComplex:
7087     case Type::STK_MemberPointer:
7088     case Type::STK_FixedPoint:
7089       llvm_unreachable("illegal cast from pointer");
7090     }
7091     llvm_unreachable("Should have returned before this");
7092 
7093   case Type::STK_FixedPoint:
7094     switch (DestTy->getScalarTypeKind()) {
7095     case Type::STK_FixedPoint:
7096       return CK_FixedPointCast;
7097     case Type::STK_Bool:
7098       return CK_FixedPointToBoolean;
7099     case Type::STK_Integral:
7100       return CK_FixedPointToIntegral;
7101     case Type::STK_Floating:
7102       return CK_FixedPointToFloating;
7103     case Type::STK_IntegralComplex:
7104     case Type::STK_FloatingComplex:
7105       Diag(Src.get()->getExprLoc(),
7106            diag::err_unimplemented_conversion_with_fixed_point_type)
7107           << DestTy;
7108       return CK_IntegralCast;
7109     case Type::STK_CPointer:
7110     case Type::STK_ObjCObjectPointer:
7111     case Type::STK_BlockPointer:
7112     case Type::STK_MemberPointer:
7113       llvm_unreachable("illegal cast to pointer type");
7114     }
7115     llvm_unreachable("Should have returned before this");
7116 
7117   case Type::STK_Bool: // casting from bool is like casting from an integer
7118   case Type::STK_Integral:
7119     switch (DestTy->getScalarTypeKind()) {
7120     case Type::STK_CPointer:
7121     case Type::STK_ObjCObjectPointer:
7122     case Type::STK_BlockPointer:
7123       if (Src.get()->isNullPointerConstant(Context,
7124                                            Expr::NPC_ValueDependentIsNull))
7125         return CK_NullToPointer;
7126       return CK_IntegralToPointer;
7127     case Type::STK_Bool:
7128       return CK_IntegralToBoolean;
7129     case Type::STK_Integral:
7130       return CK_IntegralCast;
7131     case Type::STK_Floating:
7132       return CK_IntegralToFloating;
7133     case Type::STK_IntegralComplex:
7134       Src = ImpCastExprToType(Src.get(),
7135                       DestTy->castAs<ComplexType>()->getElementType(),
7136                       CK_IntegralCast);
7137       return CK_IntegralRealToComplex;
7138     case Type::STK_FloatingComplex:
7139       Src = ImpCastExprToType(Src.get(),
7140                       DestTy->castAs<ComplexType>()->getElementType(),
7141                       CK_IntegralToFloating);
7142       return CK_FloatingRealToComplex;
7143     case Type::STK_MemberPointer:
7144       llvm_unreachable("member pointer type in C");
7145     case Type::STK_FixedPoint:
7146       return CK_IntegralToFixedPoint;
7147     }
7148     llvm_unreachable("Should have returned before this");
7149 
7150   case Type::STK_Floating:
7151     switch (DestTy->getScalarTypeKind()) {
7152     case Type::STK_Floating:
7153       return CK_FloatingCast;
7154     case Type::STK_Bool:
7155       return CK_FloatingToBoolean;
7156     case Type::STK_Integral:
7157       return CK_FloatingToIntegral;
7158     case Type::STK_FloatingComplex:
7159       Src = ImpCastExprToType(Src.get(),
7160                               DestTy->castAs<ComplexType>()->getElementType(),
7161                               CK_FloatingCast);
7162       return CK_FloatingRealToComplex;
7163     case Type::STK_IntegralComplex:
7164       Src = ImpCastExprToType(Src.get(),
7165                               DestTy->castAs<ComplexType>()->getElementType(),
7166                               CK_FloatingToIntegral);
7167       return CK_IntegralRealToComplex;
7168     case Type::STK_CPointer:
7169     case Type::STK_ObjCObjectPointer:
7170     case Type::STK_BlockPointer:
7171       llvm_unreachable("valid float->pointer cast?");
7172     case Type::STK_MemberPointer:
7173       llvm_unreachable("member pointer type in C");
7174     case Type::STK_FixedPoint:
7175       return CK_FloatingToFixedPoint;
7176     }
7177     llvm_unreachable("Should have returned before this");
7178 
7179   case Type::STK_FloatingComplex:
7180     switch (DestTy->getScalarTypeKind()) {
7181     case Type::STK_FloatingComplex:
7182       return CK_FloatingComplexCast;
7183     case Type::STK_IntegralComplex:
7184       return CK_FloatingComplexToIntegralComplex;
7185     case Type::STK_Floating: {
7186       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7187       if (Context.hasSameType(ET, DestTy))
7188         return CK_FloatingComplexToReal;
7189       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7190       return CK_FloatingCast;
7191     }
7192     case Type::STK_Bool:
7193       return CK_FloatingComplexToBoolean;
7194     case Type::STK_Integral:
7195       Src = ImpCastExprToType(Src.get(),
7196                               SrcTy->castAs<ComplexType>()->getElementType(),
7197                               CK_FloatingComplexToReal);
7198       return CK_FloatingToIntegral;
7199     case Type::STK_CPointer:
7200     case Type::STK_ObjCObjectPointer:
7201     case Type::STK_BlockPointer:
7202       llvm_unreachable("valid complex float->pointer cast?");
7203     case Type::STK_MemberPointer:
7204       llvm_unreachable("member pointer type in C");
7205     case Type::STK_FixedPoint:
7206       Diag(Src.get()->getExprLoc(),
7207            diag::err_unimplemented_conversion_with_fixed_point_type)
7208           << SrcTy;
7209       return CK_IntegralCast;
7210     }
7211     llvm_unreachable("Should have returned before this");
7212 
7213   case Type::STK_IntegralComplex:
7214     switch (DestTy->getScalarTypeKind()) {
7215     case Type::STK_FloatingComplex:
7216       return CK_IntegralComplexToFloatingComplex;
7217     case Type::STK_IntegralComplex:
7218       return CK_IntegralComplexCast;
7219     case Type::STK_Integral: {
7220       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7221       if (Context.hasSameType(ET, DestTy))
7222         return CK_IntegralComplexToReal;
7223       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7224       return CK_IntegralCast;
7225     }
7226     case Type::STK_Bool:
7227       return CK_IntegralComplexToBoolean;
7228     case Type::STK_Floating:
7229       Src = ImpCastExprToType(Src.get(),
7230                               SrcTy->castAs<ComplexType>()->getElementType(),
7231                               CK_IntegralComplexToReal);
7232       return CK_IntegralToFloating;
7233     case Type::STK_CPointer:
7234     case Type::STK_ObjCObjectPointer:
7235     case Type::STK_BlockPointer:
7236       llvm_unreachable("valid complex int->pointer cast?");
7237     case Type::STK_MemberPointer:
7238       llvm_unreachable("member pointer type in C");
7239     case Type::STK_FixedPoint:
7240       Diag(Src.get()->getExprLoc(),
7241            diag::err_unimplemented_conversion_with_fixed_point_type)
7242           << SrcTy;
7243       return CK_IntegralCast;
7244     }
7245     llvm_unreachable("Should have returned before this");
7246   }
7247 
7248   llvm_unreachable("Unhandled scalar cast");
7249 }
7250 
7251 static bool breakDownVectorType(QualType type, uint64_t &len,
7252                                 QualType &eltType) {
7253   // Vectors are simple.
7254   if (const VectorType *vecType = type->getAs<VectorType>()) {
7255     len = vecType->getNumElements();
7256     eltType = vecType->getElementType();
7257     assert(eltType->isScalarType());
7258     return true;
7259   }
7260 
7261   // We allow lax conversion to and from non-vector types, but only if
7262   // they're real types (i.e. non-complex, non-pointer scalar types).
7263   if (!type->isRealType()) return false;
7264 
7265   len = 1;
7266   eltType = type;
7267   return true;
7268 }
7269 
7270 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7271 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7272 /// allowed?
7273 ///
7274 /// This will also return false if the two given types do not make sense from
7275 /// the perspective of SVE bitcasts.
7276 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7277   assert(srcTy->isVectorType() || destTy->isVectorType());
7278 
7279   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7280     if (!FirstType->isSizelessBuiltinType())
7281       return false;
7282 
7283     const auto *VecTy = SecondType->getAs<VectorType>();
7284     return VecTy &&
7285            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7286   };
7287 
7288   return ValidScalableConversion(srcTy, destTy) ||
7289          ValidScalableConversion(destTy, srcTy);
7290 }
7291 
7292 /// Are the two types lax-compatible vector types?  That is, given
7293 /// that one of them is a vector, do they have equal storage sizes,
7294 /// where the storage size is the number of elements times the element
7295 /// size?
7296 ///
7297 /// This will also return false if either of the types is neither a
7298 /// vector nor a real type.
7299 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7300   assert(destTy->isVectorType() || srcTy->isVectorType());
7301 
7302   // Disallow lax conversions between scalars and ExtVectors (these
7303   // conversions are allowed for other vector types because common headers
7304   // depend on them).  Most scalar OP ExtVector cases are handled by the
7305   // splat path anyway, which does what we want (convert, not bitcast).
7306   // What this rules out for ExtVectors is crazy things like char4*float.
7307   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7308   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7309 
7310   uint64_t srcLen, destLen;
7311   QualType srcEltTy, destEltTy;
7312   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7313   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7314 
7315   // ASTContext::getTypeSize will return the size rounded up to a
7316   // power of 2, so instead of using that, we need to use the raw
7317   // element size multiplied by the element count.
7318   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7319   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7320 
7321   return (srcLen * srcEltSize == destLen * destEltSize);
7322 }
7323 
7324 /// Is this a legal conversion between two types, one of which is
7325 /// known to be a vector type?
7326 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7327   assert(destTy->isVectorType() || srcTy->isVectorType());
7328 
7329   switch (Context.getLangOpts().getLaxVectorConversions()) {
7330   case LangOptions::LaxVectorConversionKind::None:
7331     return false;
7332 
7333   case LangOptions::LaxVectorConversionKind::Integer:
7334     if (!srcTy->isIntegralOrEnumerationType()) {
7335       auto *Vec = srcTy->getAs<VectorType>();
7336       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7337         return false;
7338     }
7339     if (!destTy->isIntegralOrEnumerationType()) {
7340       auto *Vec = destTy->getAs<VectorType>();
7341       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7342         return false;
7343     }
7344     // OK, integer (vector) -> integer (vector) bitcast.
7345     break;
7346 
7347     case LangOptions::LaxVectorConversionKind::All:
7348     break;
7349   }
7350 
7351   return areLaxCompatibleVectorTypes(srcTy, destTy);
7352 }
7353 
7354 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7355                            CastKind &Kind) {
7356   assert(VectorTy->isVectorType() && "Not a vector type!");
7357 
7358   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7359     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7360       return Diag(R.getBegin(),
7361                   Ty->isVectorType() ?
7362                   diag::err_invalid_conversion_between_vectors :
7363                   diag::err_invalid_conversion_between_vector_and_integer)
7364         << VectorTy << Ty << R;
7365   } else
7366     return Diag(R.getBegin(),
7367                 diag::err_invalid_conversion_between_vector_and_scalar)
7368       << VectorTy << Ty << R;
7369 
7370   Kind = CK_BitCast;
7371   return false;
7372 }
7373 
7374 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7375   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7376 
7377   if (DestElemTy == SplattedExpr->getType())
7378     return SplattedExpr;
7379 
7380   assert(DestElemTy->isFloatingType() ||
7381          DestElemTy->isIntegralOrEnumerationType());
7382 
7383   CastKind CK;
7384   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7385     // OpenCL requires that we convert `true` boolean expressions to -1, but
7386     // only when splatting vectors.
7387     if (DestElemTy->isFloatingType()) {
7388       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7389       // in two steps: boolean to signed integral, then to floating.
7390       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7391                                                  CK_BooleanToSignedIntegral);
7392       SplattedExpr = CastExprRes.get();
7393       CK = CK_IntegralToFloating;
7394     } else {
7395       CK = CK_BooleanToSignedIntegral;
7396     }
7397   } else {
7398     ExprResult CastExprRes = SplattedExpr;
7399     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7400     if (CastExprRes.isInvalid())
7401       return ExprError();
7402     SplattedExpr = CastExprRes.get();
7403   }
7404   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7405 }
7406 
7407 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7408                                     Expr *CastExpr, CastKind &Kind) {
7409   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7410 
7411   QualType SrcTy = CastExpr->getType();
7412 
7413   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7414   // an ExtVectorType.
7415   // In OpenCL, casts between vectors of different types are not allowed.
7416   // (See OpenCL 6.2).
7417   if (SrcTy->isVectorType()) {
7418     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7419         (getLangOpts().OpenCL &&
7420          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7421       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7422         << DestTy << SrcTy << R;
7423       return ExprError();
7424     }
7425     Kind = CK_BitCast;
7426     return CastExpr;
7427   }
7428 
7429   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7430   // conversion will take place first from scalar to elt type, and then
7431   // splat from elt type to vector.
7432   if (SrcTy->isPointerType())
7433     return Diag(R.getBegin(),
7434                 diag::err_invalid_conversion_between_vector_and_scalar)
7435       << DestTy << SrcTy << R;
7436 
7437   Kind = CK_VectorSplat;
7438   return prepareVectorSplat(DestTy, CastExpr);
7439 }
7440 
7441 ExprResult
7442 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7443                     Declarator &D, ParsedType &Ty,
7444                     SourceLocation RParenLoc, Expr *CastExpr) {
7445   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7446          "ActOnCastExpr(): missing type or expr");
7447 
7448   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7449   if (D.isInvalidType())
7450     return ExprError();
7451 
7452   if (getLangOpts().CPlusPlus) {
7453     // Check that there are no default arguments (C++ only).
7454     CheckExtraCXXDefaultArguments(D);
7455   } else {
7456     // Make sure any TypoExprs have been dealt with.
7457     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7458     if (!Res.isUsable())
7459       return ExprError();
7460     CastExpr = Res.get();
7461   }
7462 
7463   checkUnusedDeclAttributes(D);
7464 
7465   QualType castType = castTInfo->getType();
7466   Ty = CreateParsedType(castType, castTInfo);
7467 
7468   bool isVectorLiteral = false;
7469 
7470   // Check for an altivec or OpenCL literal,
7471   // i.e. all the elements are integer constants.
7472   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7473   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7474   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7475        && castType->isVectorType() && (PE || PLE)) {
7476     if (PLE && PLE->getNumExprs() == 0) {
7477       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7478       return ExprError();
7479     }
7480     if (PE || PLE->getNumExprs() == 1) {
7481       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7482       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7483         isVectorLiteral = true;
7484     }
7485     else
7486       isVectorLiteral = true;
7487   }
7488 
7489   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7490   // then handle it as such.
7491   if (isVectorLiteral)
7492     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7493 
7494   // If the Expr being casted is a ParenListExpr, handle it specially.
7495   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7496   // sequence of BinOp comma operators.
7497   if (isa<ParenListExpr>(CastExpr)) {
7498     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7499     if (Result.isInvalid()) return ExprError();
7500     CastExpr = Result.get();
7501   }
7502 
7503   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7504       !getSourceManager().isInSystemMacro(LParenLoc))
7505     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7506 
7507   CheckTollFreeBridgeCast(castType, CastExpr);
7508 
7509   CheckObjCBridgeRelatedCast(castType, CastExpr);
7510 
7511   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7512 
7513   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7514 }
7515 
7516 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7517                                     SourceLocation RParenLoc, Expr *E,
7518                                     TypeSourceInfo *TInfo) {
7519   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7520          "Expected paren or paren list expression");
7521 
7522   Expr **exprs;
7523   unsigned numExprs;
7524   Expr *subExpr;
7525   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7526   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7527     LiteralLParenLoc = PE->getLParenLoc();
7528     LiteralRParenLoc = PE->getRParenLoc();
7529     exprs = PE->getExprs();
7530     numExprs = PE->getNumExprs();
7531   } else { // isa<ParenExpr> by assertion at function entrance
7532     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7533     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7534     subExpr = cast<ParenExpr>(E)->getSubExpr();
7535     exprs = &subExpr;
7536     numExprs = 1;
7537   }
7538 
7539   QualType Ty = TInfo->getType();
7540   assert(Ty->isVectorType() && "Expected vector type");
7541 
7542   SmallVector<Expr *, 8> initExprs;
7543   const VectorType *VTy = Ty->castAs<VectorType>();
7544   unsigned numElems = VTy->getNumElements();
7545 
7546   // '(...)' form of vector initialization in AltiVec: the number of
7547   // initializers must be one or must match the size of the vector.
7548   // If a single value is specified in the initializer then it will be
7549   // replicated to all the components of the vector
7550   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7551     // The number of initializers must be one or must match the size of the
7552     // vector. If a single value is specified in the initializer then it will
7553     // be replicated to all the components of the vector
7554     if (numExprs == 1) {
7555       QualType ElemTy = VTy->getElementType();
7556       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7557       if (Literal.isInvalid())
7558         return ExprError();
7559       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7560                                   PrepareScalarCast(Literal, ElemTy));
7561       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7562     }
7563     else if (numExprs < numElems) {
7564       Diag(E->getExprLoc(),
7565            diag::err_incorrect_number_of_vector_initializers);
7566       return ExprError();
7567     }
7568     else
7569       initExprs.append(exprs, exprs + numExprs);
7570   }
7571   else {
7572     // For OpenCL, when the number of initializers is a single value,
7573     // it will be replicated to all components of the vector.
7574     if (getLangOpts().OpenCL &&
7575         VTy->getVectorKind() == VectorType::GenericVector &&
7576         numExprs == 1) {
7577         QualType ElemTy = VTy->getElementType();
7578         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7579         if (Literal.isInvalid())
7580           return ExprError();
7581         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7582                                     PrepareScalarCast(Literal, ElemTy));
7583         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7584     }
7585 
7586     initExprs.append(exprs, exprs + numExprs);
7587   }
7588   // FIXME: This means that pretty-printing the final AST will produce curly
7589   // braces instead of the original commas.
7590   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7591                                                    initExprs, LiteralRParenLoc);
7592   initE->setType(Ty);
7593   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7594 }
7595 
7596 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7597 /// the ParenListExpr into a sequence of comma binary operators.
7598 ExprResult
7599 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7600   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7601   if (!E)
7602     return OrigExpr;
7603 
7604   ExprResult Result(E->getExpr(0));
7605 
7606   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7607     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7608                         E->getExpr(i));
7609 
7610   if (Result.isInvalid()) return ExprError();
7611 
7612   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7613 }
7614 
7615 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7616                                     SourceLocation R,
7617                                     MultiExprArg Val) {
7618   return ParenListExpr::Create(Context, L, Val, R);
7619 }
7620 
7621 /// Emit a specialized diagnostic when one expression is a null pointer
7622 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7623 /// emitted.
7624 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7625                                       SourceLocation QuestionLoc) {
7626   Expr *NullExpr = LHSExpr;
7627   Expr *NonPointerExpr = RHSExpr;
7628   Expr::NullPointerConstantKind NullKind =
7629       NullExpr->isNullPointerConstant(Context,
7630                                       Expr::NPC_ValueDependentIsNotNull);
7631 
7632   if (NullKind == Expr::NPCK_NotNull) {
7633     NullExpr = RHSExpr;
7634     NonPointerExpr = LHSExpr;
7635     NullKind =
7636         NullExpr->isNullPointerConstant(Context,
7637                                         Expr::NPC_ValueDependentIsNotNull);
7638   }
7639 
7640   if (NullKind == Expr::NPCK_NotNull)
7641     return false;
7642 
7643   if (NullKind == Expr::NPCK_ZeroExpression)
7644     return false;
7645 
7646   if (NullKind == Expr::NPCK_ZeroLiteral) {
7647     // In this case, check to make sure that we got here from a "NULL"
7648     // string in the source code.
7649     NullExpr = NullExpr->IgnoreParenImpCasts();
7650     SourceLocation loc = NullExpr->getExprLoc();
7651     if (!findMacroSpelling(loc, "NULL"))
7652       return false;
7653   }
7654 
7655   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7656   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7657       << NonPointerExpr->getType() << DiagType
7658       << NonPointerExpr->getSourceRange();
7659   return true;
7660 }
7661 
7662 /// Return false if the condition expression is valid, true otherwise.
7663 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7664   QualType CondTy = Cond->getType();
7665 
7666   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7667   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7668     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7669       << CondTy << Cond->getSourceRange();
7670     return true;
7671   }
7672 
7673   // C99 6.5.15p2
7674   if (CondTy->isScalarType()) return false;
7675 
7676   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7677     << CondTy << Cond->getSourceRange();
7678   return true;
7679 }
7680 
7681 /// Handle when one or both operands are void type.
7682 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7683                                          ExprResult &RHS) {
7684     Expr *LHSExpr = LHS.get();
7685     Expr *RHSExpr = RHS.get();
7686 
7687     if (!LHSExpr->getType()->isVoidType())
7688       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7689           << RHSExpr->getSourceRange();
7690     if (!RHSExpr->getType()->isVoidType())
7691       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7692           << LHSExpr->getSourceRange();
7693     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7694     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7695     return S.Context.VoidTy;
7696 }
7697 
7698 /// Return false if the NullExpr can be promoted to PointerTy,
7699 /// true otherwise.
7700 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7701                                         QualType PointerTy) {
7702   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7703       !NullExpr.get()->isNullPointerConstant(S.Context,
7704                                             Expr::NPC_ValueDependentIsNull))
7705     return true;
7706 
7707   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7708   return false;
7709 }
7710 
7711 /// Checks compatibility between two pointers and return the resulting
7712 /// type.
7713 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7714                                                      ExprResult &RHS,
7715                                                      SourceLocation Loc) {
7716   QualType LHSTy = LHS.get()->getType();
7717   QualType RHSTy = RHS.get()->getType();
7718 
7719   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7720     // Two identical pointers types are always compatible.
7721     return LHSTy;
7722   }
7723 
7724   QualType lhptee, rhptee;
7725 
7726   // Get the pointee types.
7727   bool IsBlockPointer = false;
7728   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7729     lhptee = LHSBTy->getPointeeType();
7730     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7731     IsBlockPointer = true;
7732   } else {
7733     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7734     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7735   }
7736 
7737   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7738   // differently qualified versions of compatible types, the result type is
7739   // a pointer to an appropriately qualified version of the composite
7740   // type.
7741 
7742   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7743   // clause doesn't make sense for our extensions. E.g. address space 2 should
7744   // be incompatible with address space 3: they may live on different devices or
7745   // anything.
7746   Qualifiers lhQual = lhptee.getQualifiers();
7747   Qualifiers rhQual = rhptee.getQualifiers();
7748 
7749   LangAS ResultAddrSpace = LangAS::Default;
7750   LangAS LAddrSpace = lhQual.getAddressSpace();
7751   LangAS RAddrSpace = rhQual.getAddressSpace();
7752 
7753   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7754   // spaces is disallowed.
7755   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7756     ResultAddrSpace = LAddrSpace;
7757   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7758     ResultAddrSpace = RAddrSpace;
7759   else {
7760     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7761         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7762         << RHS.get()->getSourceRange();
7763     return QualType();
7764   }
7765 
7766   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7767   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7768   lhQual.removeCVRQualifiers();
7769   rhQual.removeCVRQualifiers();
7770 
7771   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7772   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7773   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7774   // qual types are compatible iff
7775   //  * corresponded types are compatible
7776   //  * CVR qualifiers are equal
7777   //  * address spaces are equal
7778   // Thus for conditional operator we merge CVR and address space unqualified
7779   // pointees and if there is a composite type we return a pointer to it with
7780   // merged qualifiers.
7781   LHSCastKind =
7782       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7783   RHSCastKind =
7784       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7785   lhQual.removeAddressSpace();
7786   rhQual.removeAddressSpace();
7787 
7788   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7789   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7790 
7791   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7792 
7793   if (CompositeTy.isNull()) {
7794     // In this situation, we assume void* type. No especially good
7795     // reason, but this is what gcc does, and we do have to pick
7796     // to get a consistent AST.
7797     QualType incompatTy;
7798     incompatTy = S.Context.getPointerType(
7799         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7800     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7801     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7802 
7803     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7804     // for casts between types with incompatible address space qualifiers.
7805     // For the following code the compiler produces casts between global and
7806     // local address spaces of the corresponded innermost pointees:
7807     // local int *global *a;
7808     // global int *global *b;
7809     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7810     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7811         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7812         << RHS.get()->getSourceRange();
7813 
7814     return incompatTy;
7815   }
7816 
7817   // The pointer types are compatible.
7818   // In case of OpenCL ResultTy should have the address space qualifier
7819   // which is a superset of address spaces of both the 2nd and the 3rd
7820   // operands of the conditional operator.
7821   QualType ResultTy = [&, ResultAddrSpace]() {
7822     if (S.getLangOpts().OpenCL) {
7823       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7824       CompositeQuals.setAddressSpace(ResultAddrSpace);
7825       return S.Context
7826           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7827           .withCVRQualifiers(MergedCVRQual);
7828     }
7829     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7830   }();
7831   if (IsBlockPointer)
7832     ResultTy = S.Context.getBlockPointerType(ResultTy);
7833   else
7834     ResultTy = S.Context.getPointerType(ResultTy);
7835 
7836   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7837   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7838   return ResultTy;
7839 }
7840 
7841 /// Return the resulting type when the operands are both block pointers.
7842 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7843                                                           ExprResult &LHS,
7844                                                           ExprResult &RHS,
7845                                                           SourceLocation Loc) {
7846   QualType LHSTy = LHS.get()->getType();
7847   QualType RHSTy = RHS.get()->getType();
7848 
7849   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7850     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7851       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7852       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7853       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7854       return destType;
7855     }
7856     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7857       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7858       << RHS.get()->getSourceRange();
7859     return QualType();
7860   }
7861 
7862   // We have 2 block pointer types.
7863   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7864 }
7865 
7866 /// Return the resulting type when the operands are both pointers.
7867 static QualType
7868 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7869                                             ExprResult &RHS,
7870                                             SourceLocation Loc) {
7871   // get the pointer types
7872   QualType LHSTy = LHS.get()->getType();
7873   QualType RHSTy = RHS.get()->getType();
7874 
7875   // get the "pointed to" types
7876   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7877   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7878 
7879   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7880   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7881     // Figure out necessary qualifiers (C99 6.5.15p6)
7882     QualType destPointee
7883       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7884     QualType destType = S.Context.getPointerType(destPointee);
7885     // Add qualifiers if necessary.
7886     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7887     // Promote to void*.
7888     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7889     return destType;
7890   }
7891   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7892     QualType destPointee
7893       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7894     QualType destType = S.Context.getPointerType(destPointee);
7895     // Add qualifiers if necessary.
7896     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7897     // Promote to void*.
7898     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7899     return destType;
7900   }
7901 
7902   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7903 }
7904 
7905 /// Return false if the first expression is not an integer and the second
7906 /// expression is not a pointer, true otherwise.
7907 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7908                                         Expr* PointerExpr, SourceLocation Loc,
7909                                         bool IsIntFirstExpr) {
7910   if (!PointerExpr->getType()->isPointerType() ||
7911       !Int.get()->getType()->isIntegerType())
7912     return false;
7913 
7914   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7915   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7916 
7917   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7918     << Expr1->getType() << Expr2->getType()
7919     << Expr1->getSourceRange() << Expr2->getSourceRange();
7920   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7921                             CK_IntegralToPointer);
7922   return true;
7923 }
7924 
7925 /// Simple conversion between integer and floating point types.
7926 ///
7927 /// Used when handling the OpenCL conditional operator where the
7928 /// condition is a vector while the other operands are scalar.
7929 ///
7930 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7931 /// types are either integer or floating type. Between the two
7932 /// operands, the type with the higher rank is defined as the "result
7933 /// type". The other operand needs to be promoted to the same type. No
7934 /// other type promotion is allowed. We cannot use
7935 /// UsualArithmeticConversions() for this purpose, since it always
7936 /// promotes promotable types.
7937 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7938                                             ExprResult &RHS,
7939                                             SourceLocation QuestionLoc) {
7940   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7941   if (LHS.isInvalid())
7942     return QualType();
7943   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7944   if (RHS.isInvalid())
7945     return QualType();
7946 
7947   // For conversion purposes, we ignore any qualifiers.
7948   // For example, "const float" and "float" are equivalent.
7949   QualType LHSType =
7950     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7951   QualType RHSType =
7952     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7953 
7954   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7955     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7956       << LHSType << LHS.get()->getSourceRange();
7957     return QualType();
7958   }
7959 
7960   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7961     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7962       << RHSType << RHS.get()->getSourceRange();
7963     return QualType();
7964   }
7965 
7966   // If both types are identical, no conversion is needed.
7967   if (LHSType == RHSType)
7968     return LHSType;
7969 
7970   // Now handle "real" floating types (i.e. float, double, long double).
7971   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7972     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7973                                  /*IsCompAssign = */ false);
7974 
7975   // Finally, we have two differing integer types.
7976   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7977   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7978 }
7979 
7980 /// Convert scalar operands to a vector that matches the
7981 ///        condition in length.
7982 ///
7983 /// Used when handling the OpenCL conditional operator where the
7984 /// condition is a vector while the other operands are scalar.
7985 ///
7986 /// We first compute the "result type" for the scalar operands
7987 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7988 /// into a vector of that type where the length matches the condition
7989 /// vector type. s6.11.6 requires that the element types of the result
7990 /// and the condition must have the same number of bits.
7991 static QualType
7992 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7993                               QualType CondTy, SourceLocation QuestionLoc) {
7994   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7995   if (ResTy.isNull()) return QualType();
7996 
7997   const VectorType *CV = CondTy->getAs<VectorType>();
7998   assert(CV);
7999 
8000   // Determine the vector result type
8001   unsigned NumElements = CV->getNumElements();
8002   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8003 
8004   // Ensure that all types have the same number of bits
8005   if (S.Context.getTypeSize(CV->getElementType())
8006       != S.Context.getTypeSize(ResTy)) {
8007     // Since VectorTy is created internally, it does not pretty print
8008     // with an OpenCL name. Instead, we just print a description.
8009     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8010     SmallString<64> Str;
8011     llvm::raw_svector_ostream OS(Str);
8012     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8013     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8014       << CondTy << OS.str();
8015     return QualType();
8016   }
8017 
8018   // Convert operands to the vector result type
8019   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8020   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8021 
8022   return VectorTy;
8023 }
8024 
8025 /// Return false if this is a valid OpenCL condition vector
8026 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8027                                        SourceLocation QuestionLoc) {
8028   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8029   // integral type.
8030   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8031   assert(CondTy);
8032   QualType EleTy = CondTy->getElementType();
8033   if (EleTy->isIntegerType()) return false;
8034 
8035   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8036     << Cond->getType() << Cond->getSourceRange();
8037   return true;
8038 }
8039 
8040 /// Return false if the vector condition type and the vector
8041 ///        result type are compatible.
8042 ///
8043 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8044 /// number of elements, and their element types have the same number
8045 /// of bits.
8046 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8047                               SourceLocation QuestionLoc) {
8048   const VectorType *CV = CondTy->getAs<VectorType>();
8049   const VectorType *RV = VecResTy->getAs<VectorType>();
8050   assert(CV && RV);
8051 
8052   if (CV->getNumElements() != RV->getNumElements()) {
8053     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8054       << CondTy << VecResTy;
8055     return true;
8056   }
8057 
8058   QualType CVE = CV->getElementType();
8059   QualType RVE = RV->getElementType();
8060 
8061   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8062     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8063       << CondTy << VecResTy;
8064     return true;
8065   }
8066 
8067   return false;
8068 }
8069 
8070 /// Return the resulting type for the conditional operator in
8071 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8072 ///        s6.3.i) when the condition is a vector type.
8073 static QualType
8074 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8075                              ExprResult &LHS, ExprResult &RHS,
8076                              SourceLocation QuestionLoc) {
8077   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8078   if (Cond.isInvalid())
8079     return QualType();
8080   QualType CondTy = Cond.get()->getType();
8081 
8082   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8083     return QualType();
8084 
8085   // If either operand is a vector then find the vector type of the
8086   // result as specified in OpenCL v1.1 s6.3.i.
8087   if (LHS.get()->getType()->isVectorType() ||
8088       RHS.get()->getType()->isVectorType()) {
8089     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8090                                               /*isCompAssign*/false,
8091                                               /*AllowBothBool*/true,
8092                                               /*AllowBoolConversions*/false);
8093     if (VecResTy.isNull()) return QualType();
8094     // The result type must match the condition type as specified in
8095     // OpenCL v1.1 s6.11.6.
8096     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8097       return QualType();
8098     return VecResTy;
8099   }
8100 
8101   // Both operands are scalar.
8102   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8103 }
8104 
8105 /// Return true if the Expr is block type
8106 static bool checkBlockType(Sema &S, const Expr *E) {
8107   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8108     QualType Ty = CE->getCallee()->getType();
8109     if (Ty->isBlockPointerType()) {
8110       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8111       return true;
8112     }
8113   }
8114   return false;
8115 }
8116 
8117 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8118 /// In that case, LHS = cond.
8119 /// C99 6.5.15
8120 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8121                                         ExprResult &RHS, ExprValueKind &VK,
8122                                         ExprObjectKind &OK,
8123                                         SourceLocation QuestionLoc) {
8124 
8125   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8126   if (!LHSResult.isUsable()) return QualType();
8127   LHS = LHSResult;
8128 
8129   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8130   if (!RHSResult.isUsable()) return QualType();
8131   RHS = RHSResult;
8132 
8133   // C++ is sufficiently different to merit its own checker.
8134   if (getLangOpts().CPlusPlus)
8135     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8136 
8137   VK = VK_RValue;
8138   OK = OK_Ordinary;
8139 
8140   if (Context.isDependenceAllowed() &&
8141       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8142        RHS.get()->isTypeDependent())) {
8143     assert(!getLangOpts().CPlusPlus);
8144     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8145             RHS.get()->containsErrors()) &&
8146            "should only occur in error-recovery path.");
8147     return Context.DependentTy;
8148   }
8149 
8150   // The OpenCL operator with a vector condition is sufficiently
8151   // different to merit its own checker.
8152   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8153       Cond.get()->getType()->isExtVectorType())
8154     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8155 
8156   // First, check the condition.
8157   Cond = UsualUnaryConversions(Cond.get());
8158   if (Cond.isInvalid())
8159     return QualType();
8160   if (checkCondition(*this, Cond.get(), QuestionLoc))
8161     return QualType();
8162 
8163   // Now check the two expressions.
8164   if (LHS.get()->getType()->isVectorType() ||
8165       RHS.get()->getType()->isVectorType())
8166     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8167                                /*AllowBothBool*/true,
8168                                /*AllowBoolConversions*/false);
8169 
8170   QualType ResTy =
8171       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8172   if (LHS.isInvalid() || RHS.isInvalid())
8173     return QualType();
8174 
8175   QualType LHSTy = LHS.get()->getType();
8176   QualType RHSTy = RHS.get()->getType();
8177 
8178   // Diagnose attempts to convert between __float128 and long double where
8179   // such conversions currently can't be handled.
8180   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8181     Diag(QuestionLoc,
8182          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8183       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8184     return QualType();
8185   }
8186 
8187   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8188   // selection operator (?:).
8189   if (getLangOpts().OpenCL &&
8190       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8191     return QualType();
8192   }
8193 
8194   // If both operands have arithmetic type, do the usual arithmetic conversions
8195   // to find a common type: C99 6.5.15p3,5.
8196   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8197     // Disallow invalid arithmetic conversions, such as those between ExtInts of
8198     // different sizes, or between ExtInts and other types.
8199     if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8200       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8201           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8202           << RHS.get()->getSourceRange();
8203       return QualType();
8204     }
8205 
8206     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8207     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8208 
8209     return ResTy;
8210   }
8211 
8212   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8213   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8214     return LHSTy;
8215   }
8216 
8217   // If both operands are the same structure or union type, the result is that
8218   // type.
8219   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8220     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8221       if (LHSRT->getDecl() == RHSRT->getDecl())
8222         // "If both the operands have structure or union type, the result has
8223         // that type."  This implies that CV qualifiers are dropped.
8224         return LHSTy.getUnqualifiedType();
8225     // FIXME: Type of conditional expression must be complete in C mode.
8226   }
8227 
8228   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8229   // The following || allows only one side to be void (a GCC-ism).
8230   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8231     return checkConditionalVoidType(*this, LHS, RHS);
8232   }
8233 
8234   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8235   // the type of the other operand."
8236   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8237   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8238 
8239   // All objective-c pointer type analysis is done here.
8240   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8241                                                         QuestionLoc);
8242   if (LHS.isInvalid() || RHS.isInvalid())
8243     return QualType();
8244   if (!compositeType.isNull())
8245     return compositeType;
8246 
8247 
8248   // Handle block pointer types.
8249   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8250     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8251                                                      QuestionLoc);
8252 
8253   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8254   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8255     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8256                                                        QuestionLoc);
8257 
8258   // GCC compatibility: soften pointer/integer mismatch.  Note that
8259   // null pointers have been filtered out by this point.
8260   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8261       /*IsIntFirstExpr=*/true))
8262     return RHSTy;
8263   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8264       /*IsIntFirstExpr=*/false))
8265     return LHSTy;
8266 
8267   // Allow ?: operations in which both operands have the same
8268   // built-in sizeless type.
8269   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8270     return LHSTy;
8271 
8272   // Emit a better diagnostic if one of the expressions is a null pointer
8273   // constant and the other is not a pointer type. In this case, the user most
8274   // likely forgot to take the address of the other expression.
8275   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8276     return QualType();
8277 
8278   // Otherwise, the operands are not compatible.
8279   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8280     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8281     << RHS.get()->getSourceRange();
8282   return QualType();
8283 }
8284 
8285 /// FindCompositeObjCPointerType - Helper method to find composite type of
8286 /// two objective-c pointer types of the two input expressions.
8287 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8288                                             SourceLocation QuestionLoc) {
8289   QualType LHSTy = LHS.get()->getType();
8290   QualType RHSTy = RHS.get()->getType();
8291 
8292   // Handle things like Class and struct objc_class*.  Here we case the result
8293   // to the pseudo-builtin, because that will be implicitly cast back to the
8294   // redefinition type if an attempt is made to access its fields.
8295   if (LHSTy->isObjCClassType() &&
8296       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8297     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8298     return LHSTy;
8299   }
8300   if (RHSTy->isObjCClassType() &&
8301       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8302     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8303     return RHSTy;
8304   }
8305   // And the same for struct objc_object* / id
8306   if (LHSTy->isObjCIdType() &&
8307       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8308     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8309     return LHSTy;
8310   }
8311   if (RHSTy->isObjCIdType() &&
8312       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8313     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8314     return RHSTy;
8315   }
8316   // And the same for struct objc_selector* / SEL
8317   if (Context.isObjCSelType(LHSTy) &&
8318       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8319     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8320     return LHSTy;
8321   }
8322   if (Context.isObjCSelType(RHSTy) &&
8323       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8324     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8325     return RHSTy;
8326   }
8327   // Check constraints for Objective-C object pointers types.
8328   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8329 
8330     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8331       // Two identical object pointer types are always compatible.
8332       return LHSTy;
8333     }
8334     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8335     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8336     QualType compositeType = LHSTy;
8337 
8338     // If both operands are interfaces and either operand can be
8339     // assigned to the other, use that type as the composite
8340     // type. This allows
8341     //   xxx ? (A*) a : (B*) b
8342     // where B is a subclass of A.
8343     //
8344     // Additionally, as for assignment, if either type is 'id'
8345     // allow silent coercion. Finally, if the types are
8346     // incompatible then make sure to use 'id' as the composite
8347     // type so the result is acceptable for sending messages to.
8348 
8349     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8350     // It could return the composite type.
8351     if (!(compositeType =
8352           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8353       // Nothing more to do.
8354     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8355       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8356     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8357       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8358     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8359                 RHSOPT->isObjCQualifiedIdType()) &&
8360                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8361                                                          true)) {
8362       // Need to handle "id<xx>" explicitly.
8363       // GCC allows qualified id and any Objective-C type to devolve to
8364       // id. Currently localizing to here until clear this should be
8365       // part of ObjCQualifiedIdTypesAreCompatible.
8366       compositeType = Context.getObjCIdType();
8367     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8368       compositeType = Context.getObjCIdType();
8369     } else {
8370       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8371       << LHSTy << RHSTy
8372       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8373       QualType incompatTy = Context.getObjCIdType();
8374       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8375       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8376       return incompatTy;
8377     }
8378     // The object pointer types are compatible.
8379     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8380     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8381     return compositeType;
8382   }
8383   // Check Objective-C object pointer types and 'void *'
8384   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8385     if (getLangOpts().ObjCAutoRefCount) {
8386       // ARC forbids the implicit conversion of object pointers to 'void *',
8387       // so these types are not compatible.
8388       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8389           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8390       LHS = RHS = true;
8391       return QualType();
8392     }
8393     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8394     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8395     QualType destPointee
8396     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8397     QualType destType = Context.getPointerType(destPointee);
8398     // Add qualifiers if necessary.
8399     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8400     // Promote to void*.
8401     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8402     return destType;
8403   }
8404   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8405     if (getLangOpts().ObjCAutoRefCount) {
8406       // ARC forbids the implicit conversion of object pointers to 'void *',
8407       // so these types are not compatible.
8408       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8409           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8410       LHS = RHS = true;
8411       return QualType();
8412     }
8413     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8414     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8415     QualType destPointee
8416     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8417     QualType destType = Context.getPointerType(destPointee);
8418     // Add qualifiers if necessary.
8419     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8420     // Promote to void*.
8421     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8422     return destType;
8423   }
8424   return QualType();
8425 }
8426 
8427 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8428 /// ParenRange in parentheses.
8429 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8430                                const PartialDiagnostic &Note,
8431                                SourceRange ParenRange) {
8432   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8433   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8434       EndLoc.isValid()) {
8435     Self.Diag(Loc, Note)
8436       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8437       << FixItHint::CreateInsertion(EndLoc, ")");
8438   } else {
8439     // We can't display the parentheses, so just show the bare note.
8440     Self.Diag(Loc, Note) << ParenRange;
8441   }
8442 }
8443 
8444 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8445   return BinaryOperator::isAdditiveOp(Opc) ||
8446          BinaryOperator::isMultiplicativeOp(Opc) ||
8447          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8448   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8449   // not any of the logical operators.  Bitwise-xor is commonly used as a
8450   // logical-xor because there is no logical-xor operator.  The logical
8451   // operators, including uses of xor, have a high false positive rate for
8452   // precedence warnings.
8453 }
8454 
8455 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8456 /// expression, either using a built-in or overloaded operator,
8457 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8458 /// expression.
8459 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8460                                    Expr **RHSExprs) {
8461   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8462   E = E->IgnoreImpCasts();
8463   E = E->IgnoreConversionOperatorSingleStep();
8464   E = E->IgnoreImpCasts();
8465   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8466     E = MTE->getSubExpr();
8467     E = E->IgnoreImpCasts();
8468   }
8469 
8470   // Built-in binary operator.
8471   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8472     if (IsArithmeticOp(OP->getOpcode())) {
8473       *Opcode = OP->getOpcode();
8474       *RHSExprs = OP->getRHS();
8475       return true;
8476     }
8477   }
8478 
8479   // Overloaded operator.
8480   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8481     if (Call->getNumArgs() != 2)
8482       return false;
8483 
8484     // Make sure this is really a binary operator that is safe to pass into
8485     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8486     OverloadedOperatorKind OO = Call->getOperator();
8487     if (OO < OO_Plus || OO > OO_Arrow ||
8488         OO == OO_PlusPlus || OO == OO_MinusMinus)
8489       return false;
8490 
8491     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8492     if (IsArithmeticOp(OpKind)) {
8493       *Opcode = OpKind;
8494       *RHSExprs = Call->getArg(1);
8495       return true;
8496     }
8497   }
8498 
8499   return false;
8500 }
8501 
8502 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8503 /// or is a logical expression such as (x==y) which has int type, but is
8504 /// commonly interpreted as boolean.
8505 static bool ExprLooksBoolean(Expr *E) {
8506   E = E->IgnoreParenImpCasts();
8507 
8508   if (E->getType()->isBooleanType())
8509     return true;
8510   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8511     return OP->isComparisonOp() || OP->isLogicalOp();
8512   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8513     return OP->getOpcode() == UO_LNot;
8514   if (E->getType()->isPointerType())
8515     return true;
8516   // FIXME: What about overloaded operator calls returning "unspecified boolean
8517   // type"s (commonly pointer-to-members)?
8518 
8519   return false;
8520 }
8521 
8522 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8523 /// and binary operator are mixed in a way that suggests the programmer assumed
8524 /// the conditional operator has higher precedence, for example:
8525 /// "int x = a + someBinaryCondition ? 1 : 2".
8526 static void DiagnoseConditionalPrecedence(Sema &Self,
8527                                           SourceLocation OpLoc,
8528                                           Expr *Condition,
8529                                           Expr *LHSExpr,
8530                                           Expr *RHSExpr) {
8531   BinaryOperatorKind CondOpcode;
8532   Expr *CondRHS;
8533 
8534   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8535     return;
8536   if (!ExprLooksBoolean(CondRHS))
8537     return;
8538 
8539   // The condition is an arithmetic binary expression, with a right-
8540   // hand side that looks boolean, so warn.
8541 
8542   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8543                         ? diag::warn_precedence_bitwise_conditional
8544                         : diag::warn_precedence_conditional;
8545 
8546   Self.Diag(OpLoc, DiagID)
8547       << Condition->getSourceRange()
8548       << BinaryOperator::getOpcodeStr(CondOpcode);
8549 
8550   SuggestParentheses(
8551       Self, OpLoc,
8552       Self.PDiag(diag::note_precedence_silence)
8553           << BinaryOperator::getOpcodeStr(CondOpcode),
8554       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8555 
8556   SuggestParentheses(Self, OpLoc,
8557                      Self.PDiag(diag::note_precedence_conditional_first),
8558                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8559 }
8560 
8561 /// Compute the nullability of a conditional expression.
8562 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8563                                               QualType LHSTy, QualType RHSTy,
8564                                               ASTContext &Ctx) {
8565   if (!ResTy->isAnyPointerType())
8566     return ResTy;
8567 
8568   auto GetNullability = [&Ctx](QualType Ty) {
8569     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8570     if (Kind) {
8571       // For our purposes, treat _Nullable_result as _Nullable.
8572       if (*Kind == NullabilityKind::NullableResult)
8573         return NullabilityKind::Nullable;
8574       return *Kind;
8575     }
8576     return NullabilityKind::Unspecified;
8577   };
8578 
8579   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8580   NullabilityKind MergedKind;
8581 
8582   // Compute nullability of a binary conditional expression.
8583   if (IsBin) {
8584     if (LHSKind == NullabilityKind::NonNull)
8585       MergedKind = NullabilityKind::NonNull;
8586     else
8587       MergedKind = RHSKind;
8588   // Compute nullability of a normal conditional expression.
8589   } else {
8590     if (LHSKind == NullabilityKind::Nullable ||
8591         RHSKind == NullabilityKind::Nullable)
8592       MergedKind = NullabilityKind::Nullable;
8593     else if (LHSKind == NullabilityKind::NonNull)
8594       MergedKind = RHSKind;
8595     else if (RHSKind == NullabilityKind::NonNull)
8596       MergedKind = LHSKind;
8597     else
8598       MergedKind = NullabilityKind::Unspecified;
8599   }
8600 
8601   // Return if ResTy already has the correct nullability.
8602   if (GetNullability(ResTy) == MergedKind)
8603     return ResTy;
8604 
8605   // Strip all nullability from ResTy.
8606   while (ResTy->getNullability(Ctx))
8607     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8608 
8609   // Create a new AttributedType with the new nullability kind.
8610   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8611   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8612 }
8613 
8614 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8615 /// in the case of a the GNU conditional expr extension.
8616 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8617                                     SourceLocation ColonLoc,
8618                                     Expr *CondExpr, Expr *LHSExpr,
8619                                     Expr *RHSExpr) {
8620   if (!Context.isDependenceAllowed()) {
8621     // C cannot handle TypoExpr nodes in the condition because it
8622     // doesn't handle dependent types properly, so make sure any TypoExprs have
8623     // been dealt with before checking the operands.
8624     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8625     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8626     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8627 
8628     if (!CondResult.isUsable())
8629       return ExprError();
8630 
8631     if (LHSExpr) {
8632       if (!LHSResult.isUsable())
8633         return ExprError();
8634     }
8635 
8636     if (!RHSResult.isUsable())
8637       return ExprError();
8638 
8639     CondExpr = CondResult.get();
8640     LHSExpr = LHSResult.get();
8641     RHSExpr = RHSResult.get();
8642   }
8643 
8644   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8645   // was the condition.
8646   OpaqueValueExpr *opaqueValue = nullptr;
8647   Expr *commonExpr = nullptr;
8648   if (!LHSExpr) {
8649     commonExpr = CondExpr;
8650     // Lower out placeholder types first.  This is important so that we don't
8651     // try to capture a placeholder. This happens in few cases in C++; such
8652     // as Objective-C++'s dictionary subscripting syntax.
8653     if (commonExpr->hasPlaceholderType()) {
8654       ExprResult result = CheckPlaceholderExpr(commonExpr);
8655       if (!result.isUsable()) return ExprError();
8656       commonExpr = result.get();
8657     }
8658     // We usually want to apply unary conversions *before* saving, except
8659     // in the special case of a C++ l-value conditional.
8660     if (!(getLangOpts().CPlusPlus
8661           && !commonExpr->isTypeDependent()
8662           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8663           && commonExpr->isGLValue()
8664           && commonExpr->isOrdinaryOrBitFieldObject()
8665           && RHSExpr->isOrdinaryOrBitFieldObject()
8666           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8667       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8668       if (commonRes.isInvalid())
8669         return ExprError();
8670       commonExpr = commonRes.get();
8671     }
8672 
8673     // If the common expression is a class or array prvalue, materialize it
8674     // so that we can safely refer to it multiple times.
8675     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8676                                    commonExpr->getType()->isArrayType())) {
8677       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8678       if (MatExpr.isInvalid())
8679         return ExprError();
8680       commonExpr = MatExpr.get();
8681     }
8682 
8683     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8684                                                 commonExpr->getType(),
8685                                                 commonExpr->getValueKind(),
8686                                                 commonExpr->getObjectKind(),
8687                                                 commonExpr);
8688     LHSExpr = CondExpr = opaqueValue;
8689   }
8690 
8691   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8692   ExprValueKind VK = VK_RValue;
8693   ExprObjectKind OK = OK_Ordinary;
8694   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8695   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8696                                              VK, OK, QuestionLoc);
8697   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8698       RHS.isInvalid())
8699     return ExprError();
8700 
8701   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8702                                 RHS.get());
8703 
8704   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8705 
8706   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8707                                          Context);
8708 
8709   if (!commonExpr)
8710     return new (Context)
8711         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8712                             RHS.get(), result, VK, OK);
8713 
8714   return new (Context) BinaryConditionalOperator(
8715       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8716       ColonLoc, result, VK, OK);
8717 }
8718 
8719 // Check if we have a conversion between incompatible cmse function pointer
8720 // types, that is, a conversion between a function pointer with the
8721 // cmse_nonsecure_call attribute and one without.
8722 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8723                                           QualType ToType) {
8724   if (const auto *ToFn =
8725           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8726     if (const auto *FromFn =
8727             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8728       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8729       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8730 
8731       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8732     }
8733   }
8734   return false;
8735 }
8736 
8737 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8738 // being closely modeled after the C99 spec:-). The odd characteristic of this
8739 // routine is it effectively iqnores the qualifiers on the top level pointee.
8740 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8741 // FIXME: add a couple examples in this comment.
8742 static Sema::AssignConvertType
8743 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8744   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8745   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8746 
8747   // get the "pointed to" type (ignoring qualifiers at the top level)
8748   const Type *lhptee, *rhptee;
8749   Qualifiers lhq, rhq;
8750   std::tie(lhptee, lhq) =
8751       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8752   std::tie(rhptee, rhq) =
8753       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8754 
8755   Sema::AssignConvertType ConvTy = Sema::Compatible;
8756 
8757   // C99 6.5.16.1p1: This following citation is common to constraints
8758   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8759   // qualifiers of the type *pointed to* by the right;
8760 
8761   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8762   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8763       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8764     // Ignore lifetime for further calculation.
8765     lhq.removeObjCLifetime();
8766     rhq.removeObjCLifetime();
8767   }
8768 
8769   if (!lhq.compatiblyIncludes(rhq)) {
8770     // Treat address-space mismatches as fatal.
8771     if (!lhq.isAddressSpaceSupersetOf(rhq))
8772       return Sema::IncompatiblePointerDiscardsQualifiers;
8773 
8774     // It's okay to add or remove GC or lifetime qualifiers when converting to
8775     // and from void*.
8776     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8777                         .compatiblyIncludes(
8778                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8779              && (lhptee->isVoidType() || rhptee->isVoidType()))
8780       ; // keep old
8781 
8782     // Treat lifetime mismatches as fatal.
8783     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8784       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8785 
8786     // For GCC/MS compatibility, other qualifier mismatches are treated
8787     // as still compatible in C.
8788     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8789   }
8790 
8791   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8792   // incomplete type and the other is a pointer to a qualified or unqualified
8793   // version of void...
8794   if (lhptee->isVoidType()) {
8795     if (rhptee->isIncompleteOrObjectType())
8796       return ConvTy;
8797 
8798     // As an extension, we allow cast to/from void* to function pointer.
8799     assert(rhptee->isFunctionType());
8800     return Sema::FunctionVoidPointer;
8801   }
8802 
8803   if (rhptee->isVoidType()) {
8804     if (lhptee->isIncompleteOrObjectType())
8805       return ConvTy;
8806 
8807     // As an extension, we allow cast to/from void* to function pointer.
8808     assert(lhptee->isFunctionType());
8809     return Sema::FunctionVoidPointer;
8810   }
8811 
8812   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8813   // unqualified versions of compatible types, ...
8814   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8815   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8816     // Check if the pointee types are compatible ignoring the sign.
8817     // We explicitly check for char so that we catch "char" vs
8818     // "unsigned char" on systems where "char" is unsigned.
8819     if (lhptee->isCharType())
8820       ltrans = S.Context.UnsignedCharTy;
8821     else if (lhptee->hasSignedIntegerRepresentation())
8822       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8823 
8824     if (rhptee->isCharType())
8825       rtrans = S.Context.UnsignedCharTy;
8826     else if (rhptee->hasSignedIntegerRepresentation())
8827       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8828 
8829     if (ltrans == rtrans) {
8830       // Types are compatible ignoring the sign. Qualifier incompatibility
8831       // takes priority over sign incompatibility because the sign
8832       // warning can be disabled.
8833       if (ConvTy != Sema::Compatible)
8834         return ConvTy;
8835 
8836       return Sema::IncompatiblePointerSign;
8837     }
8838 
8839     // If we are a multi-level pointer, it's possible that our issue is simply
8840     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8841     // the eventual target type is the same and the pointers have the same
8842     // level of indirection, this must be the issue.
8843     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8844       do {
8845         std::tie(lhptee, lhq) =
8846           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8847         std::tie(rhptee, rhq) =
8848           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8849 
8850         // Inconsistent address spaces at this point is invalid, even if the
8851         // address spaces would be compatible.
8852         // FIXME: This doesn't catch address space mismatches for pointers of
8853         // different nesting levels, like:
8854         //   __local int *** a;
8855         //   int ** b = a;
8856         // It's not clear how to actually determine when such pointers are
8857         // invalidly incompatible.
8858         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8859           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8860 
8861       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8862 
8863       if (lhptee == rhptee)
8864         return Sema::IncompatibleNestedPointerQualifiers;
8865     }
8866 
8867     // General pointer incompatibility takes priority over qualifiers.
8868     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8869       return Sema::IncompatibleFunctionPointer;
8870     return Sema::IncompatiblePointer;
8871   }
8872   if (!S.getLangOpts().CPlusPlus &&
8873       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8874     return Sema::IncompatibleFunctionPointer;
8875   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8876     return Sema::IncompatibleFunctionPointer;
8877   return ConvTy;
8878 }
8879 
8880 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8881 /// block pointer types are compatible or whether a block and normal pointer
8882 /// are compatible. It is more restrict than comparing two function pointer
8883 // types.
8884 static Sema::AssignConvertType
8885 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8886                                     QualType RHSType) {
8887   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8888   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8889 
8890   QualType lhptee, rhptee;
8891 
8892   // get the "pointed to" type (ignoring qualifiers at the top level)
8893   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8894   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8895 
8896   // In C++, the types have to match exactly.
8897   if (S.getLangOpts().CPlusPlus)
8898     return Sema::IncompatibleBlockPointer;
8899 
8900   Sema::AssignConvertType ConvTy = Sema::Compatible;
8901 
8902   // For blocks we enforce that qualifiers are identical.
8903   Qualifiers LQuals = lhptee.getLocalQualifiers();
8904   Qualifiers RQuals = rhptee.getLocalQualifiers();
8905   if (S.getLangOpts().OpenCL) {
8906     LQuals.removeAddressSpace();
8907     RQuals.removeAddressSpace();
8908   }
8909   if (LQuals != RQuals)
8910     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8911 
8912   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8913   // assignment.
8914   // The current behavior is similar to C++ lambdas. A block might be
8915   // assigned to a variable iff its return type and parameters are compatible
8916   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8917   // an assignment. Presumably it should behave in way that a function pointer
8918   // assignment does in C, so for each parameter and return type:
8919   //  * CVR and address space of LHS should be a superset of CVR and address
8920   //  space of RHS.
8921   //  * unqualified types should be compatible.
8922   if (S.getLangOpts().OpenCL) {
8923     if (!S.Context.typesAreBlockPointerCompatible(
8924             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8925             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8926       return Sema::IncompatibleBlockPointer;
8927   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8928     return Sema::IncompatibleBlockPointer;
8929 
8930   return ConvTy;
8931 }
8932 
8933 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8934 /// for assignment compatibility.
8935 static Sema::AssignConvertType
8936 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8937                                    QualType RHSType) {
8938   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8939   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8940 
8941   if (LHSType->isObjCBuiltinType()) {
8942     // Class is not compatible with ObjC object pointers.
8943     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8944         !RHSType->isObjCQualifiedClassType())
8945       return Sema::IncompatiblePointer;
8946     return Sema::Compatible;
8947   }
8948   if (RHSType->isObjCBuiltinType()) {
8949     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8950         !LHSType->isObjCQualifiedClassType())
8951       return Sema::IncompatiblePointer;
8952     return Sema::Compatible;
8953   }
8954   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8955   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8956 
8957   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8958       // make an exception for id<P>
8959       !LHSType->isObjCQualifiedIdType())
8960     return Sema::CompatiblePointerDiscardsQualifiers;
8961 
8962   if (S.Context.typesAreCompatible(LHSType, RHSType))
8963     return Sema::Compatible;
8964   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8965     return Sema::IncompatibleObjCQualifiedId;
8966   return Sema::IncompatiblePointer;
8967 }
8968 
8969 Sema::AssignConvertType
8970 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8971                                  QualType LHSType, QualType RHSType) {
8972   // Fake up an opaque expression.  We don't actually care about what
8973   // cast operations are required, so if CheckAssignmentConstraints
8974   // adds casts to this they'll be wasted, but fortunately that doesn't
8975   // usually happen on valid code.
8976   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8977   ExprResult RHSPtr = &RHSExpr;
8978   CastKind K;
8979 
8980   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8981 }
8982 
8983 /// This helper function returns true if QT is a vector type that has element
8984 /// type ElementType.
8985 static bool isVector(QualType QT, QualType ElementType) {
8986   if (const VectorType *VT = QT->getAs<VectorType>())
8987     return VT->getElementType().getCanonicalType() == ElementType;
8988   return false;
8989 }
8990 
8991 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8992 /// has code to accommodate several GCC extensions when type checking
8993 /// pointers. Here are some objectionable examples that GCC considers warnings:
8994 ///
8995 ///  int a, *pint;
8996 ///  short *pshort;
8997 ///  struct foo *pfoo;
8998 ///
8999 ///  pint = pshort; // warning: assignment from incompatible pointer type
9000 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9001 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9002 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9003 ///
9004 /// As a result, the code for dealing with pointers is more complex than the
9005 /// C99 spec dictates.
9006 ///
9007 /// Sets 'Kind' for any result kind except Incompatible.
9008 Sema::AssignConvertType
9009 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9010                                  CastKind &Kind, bool ConvertRHS) {
9011   QualType RHSType = RHS.get()->getType();
9012   QualType OrigLHSType = LHSType;
9013 
9014   // Get canonical types.  We're not formatting these types, just comparing
9015   // them.
9016   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9017   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9018 
9019   // Common case: no conversion required.
9020   if (LHSType == RHSType) {
9021     Kind = CK_NoOp;
9022     return Compatible;
9023   }
9024 
9025   // If we have an atomic type, try a non-atomic assignment, then just add an
9026   // atomic qualification step.
9027   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9028     Sema::AssignConvertType result =
9029       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9030     if (result != Compatible)
9031       return result;
9032     if (Kind != CK_NoOp && ConvertRHS)
9033       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9034     Kind = CK_NonAtomicToAtomic;
9035     return Compatible;
9036   }
9037 
9038   // If the left-hand side is a reference type, then we are in a
9039   // (rare!) case where we've allowed the use of references in C,
9040   // e.g., as a parameter type in a built-in function. In this case,
9041   // just make sure that the type referenced is compatible with the
9042   // right-hand side type. The caller is responsible for adjusting
9043   // LHSType so that the resulting expression does not have reference
9044   // type.
9045   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9046     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9047       Kind = CK_LValueBitCast;
9048       return Compatible;
9049     }
9050     return Incompatible;
9051   }
9052 
9053   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9054   // to the same ExtVector type.
9055   if (LHSType->isExtVectorType()) {
9056     if (RHSType->isExtVectorType())
9057       return Incompatible;
9058     if (RHSType->isArithmeticType()) {
9059       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9060       if (ConvertRHS)
9061         RHS = prepareVectorSplat(LHSType, RHS.get());
9062       Kind = CK_VectorSplat;
9063       return Compatible;
9064     }
9065   }
9066 
9067   // Conversions to or from vector type.
9068   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9069     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9070       // Allow assignments of an AltiVec vector type to an equivalent GCC
9071       // vector type and vice versa
9072       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9073         Kind = CK_BitCast;
9074         return Compatible;
9075       }
9076 
9077       // If we are allowing lax vector conversions, and LHS and RHS are both
9078       // vectors, the total size only needs to be the same. This is a bitcast;
9079       // no bits are changed but the result type is different.
9080       if (isLaxVectorConversion(RHSType, LHSType)) {
9081         Kind = CK_BitCast;
9082         return IncompatibleVectors;
9083       }
9084     }
9085 
9086     // When the RHS comes from another lax conversion (e.g. binops between
9087     // scalars and vectors) the result is canonicalized as a vector. When the
9088     // LHS is also a vector, the lax is allowed by the condition above. Handle
9089     // the case where LHS is a scalar.
9090     if (LHSType->isScalarType()) {
9091       const VectorType *VecType = RHSType->getAs<VectorType>();
9092       if (VecType && VecType->getNumElements() == 1 &&
9093           isLaxVectorConversion(RHSType, LHSType)) {
9094         ExprResult *VecExpr = &RHS;
9095         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9096         Kind = CK_BitCast;
9097         return Compatible;
9098       }
9099     }
9100 
9101     // Allow assignments between fixed-length and sizeless SVE vectors.
9102     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9103         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9104       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9105           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9106         Kind = CK_BitCast;
9107         return Compatible;
9108       }
9109 
9110     return Incompatible;
9111   }
9112 
9113   // Diagnose attempts to convert between __float128 and long double where
9114   // such conversions currently can't be handled.
9115   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9116     return Incompatible;
9117 
9118   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9119   // discards the imaginary part.
9120   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9121       !LHSType->getAs<ComplexType>())
9122     return Incompatible;
9123 
9124   // Arithmetic conversions.
9125   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9126       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9127     if (ConvertRHS)
9128       Kind = PrepareScalarCast(RHS, LHSType);
9129     return Compatible;
9130   }
9131 
9132   // Conversions to normal pointers.
9133   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9134     // U* -> T*
9135     if (isa<PointerType>(RHSType)) {
9136       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9137       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9138       if (AddrSpaceL != AddrSpaceR)
9139         Kind = CK_AddressSpaceConversion;
9140       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9141         Kind = CK_NoOp;
9142       else
9143         Kind = CK_BitCast;
9144       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9145     }
9146 
9147     // int -> T*
9148     if (RHSType->isIntegerType()) {
9149       Kind = CK_IntegralToPointer; // FIXME: null?
9150       return IntToPointer;
9151     }
9152 
9153     // C pointers are not compatible with ObjC object pointers,
9154     // with two exceptions:
9155     if (isa<ObjCObjectPointerType>(RHSType)) {
9156       //  - conversions to void*
9157       if (LHSPointer->getPointeeType()->isVoidType()) {
9158         Kind = CK_BitCast;
9159         return Compatible;
9160       }
9161 
9162       //  - conversions from 'Class' to the redefinition type
9163       if (RHSType->isObjCClassType() &&
9164           Context.hasSameType(LHSType,
9165                               Context.getObjCClassRedefinitionType())) {
9166         Kind = CK_BitCast;
9167         return Compatible;
9168       }
9169 
9170       Kind = CK_BitCast;
9171       return IncompatiblePointer;
9172     }
9173 
9174     // U^ -> void*
9175     if (RHSType->getAs<BlockPointerType>()) {
9176       if (LHSPointer->getPointeeType()->isVoidType()) {
9177         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9178         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9179                                 ->getPointeeType()
9180                                 .getAddressSpace();
9181         Kind =
9182             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9183         return Compatible;
9184       }
9185     }
9186 
9187     return Incompatible;
9188   }
9189 
9190   // Conversions to block pointers.
9191   if (isa<BlockPointerType>(LHSType)) {
9192     // U^ -> T^
9193     if (RHSType->isBlockPointerType()) {
9194       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9195                               ->getPointeeType()
9196                               .getAddressSpace();
9197       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9198                               ->getPointeeType()
9199                               .getAddressSpace();
9200       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9201       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9202     }
9203 
9204     // int or null -> T^
9205     if (RHSType->isIntegerType()) {
9206       Kind = CK_IntegralToPointer; // FIXME: null
9207       return IntToBlockPointer;
9208     }
9209 
9210     // id -> T^
9211     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9212       Kind = CK_AnyPointerToBlockPointerCast;
9213       return Compatible;
9214     }
9215 
9216     // void* -> T^
9217     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9218       if (RHSPT->getPointeeType()->isVoidType()) {
9219         Kind = CK_AnyPointerToBlockPointerCast;
9220         return Compatible;
9221       }
9222 
9223     return Incompatible;
9224   }
9225 
9226   // Conversions to Objective-C pointers.
9227   if (isa<ObjCObjectPointerType>(LHSType)) {
9228     // A* -> B*
9229     if (RHSType->isObjCObjectPointerType()) {
9230       Kind = CK_BitCast;
9231       Sema::AssignConvertType result =
9232         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9233       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9234           result == Compatible &&
9235           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9236         result = IncompatibleObjCWeakRef;
9237       return result;
9238     }
9239 
9240     // int or null -> A*
9241     if (RHSType->isIntegerType()) {
9242       Kind = CK_IntegralToPointer; // FIXME: null
9243       return IntToPointer;
9244     }
9245 
9246     // In general, C pointers are not compatible with ObjC object pointers,
9247     // with two exceptions:
9248     if (isa<PointerType>(RHSType)) {
9249       Kind = CK_CPointerToObjCPointerCast;
9250 
9251       //  - conversions from 'void*'
9252       if (RHSType->isVoidPointerType()) {
9253         return Compatible;
9254       }
9255 
9256       //  - conversions to 'Class' from its redefinition type
9257       if (LHSType->isObjCClassType() &&
9258           Context.hasSameType(RHSType,
9259                               Context.getObjCClassRedefinitionType())) {
9260         return Compatible;
9261       }
9262 
9263       return IncompatiblePointer;
9264     }
9265 
9266     // Only under strict condition T^ is compatible with an Objective-C pointer.
9267     if (RHSType->isBlockPointerType() &&
9268         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9269       if (ConvertRHS)
9270         maybeExtendBlockObject(RHS);
9271       Kind = CK_BlockPointerToObjCPointerCast;
9272       return Compatible;
9273     }
9274 
9275     return Incompatible;
9276   }
9277 
9278   // Conversions from pointers that are not covered by the above.
9279   if (isa<PointerType>(RHSType)) {
9280     // T* -> _Bool
9281     if (LHSType == Context.BoolTy) {
9282       Kind = CK_PointerToBoolean;
9283       return Compatible;
9284     }
9285 
9286     // T* -> int
9287     if (LHSType->isIntegerType()) {
9288       Kind = CK_PointerToIntegral;
9289       return PointerToInt;
9290     }
9291 
9292     return Incompatible;
9293   }
9294 
9295   // Conversions from Objective-C pointers that are not covered by the above.
9296   if (isa<ObjCObjectPointerType>(RHSType)) {
9297     // T* -> _Bool
9298     if (LHSType == Context.BoolTy) {
9299       Kind = CK_PointerToBoolean;
9300       return Compatible;
9301     }
9302 
9303     // T* -> int
9304     if (LHSType->isIntegerType()) {
9305       Kind = CK_PointerToIntegral;
9306       return PointerToInt;
9307     }
9308 
9309     return Incompatible;
9310   }
9311 
9312   // struct A -> struct B
9313   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9314     if (Context.typesAreCompatible(LHSType, RHSType)) {
9315       Kind = CK_NoOp;
9316       return Compatible;
9317     }
9318   }
9319 
9320   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9321     Kind = CK_IntToOCLSampler;
9322     return Compatible;
9323   }
9324 
9325   return Incompatible;
9326 }
9327 
9328 /// Constructs a transparent union from an expression that is
9329 /// used to initialize the transparent union.
9330 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9331                                       ExprResult &EResult, QualType UnionType,
9332                                       FieldDecl *Field) {
9333   // Build an initializer list that designates the appropriate member
9334   // of the transparent union.
9335   Expr *E = EResult.get();
9336   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9337                                                    E, SourceLocation());
9338   Initializer->setType(UnionType);
9339   Initializer->setInitializedFieldInUnion(Field);
9340 
9341   // Build a compound literal constructing a value of the transparent
9342   // union type from this initializer list.
9343   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9344   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9345                                         VK_RValue, Initializer, false);
9346 }
9347 
9348 Sema::AssignConvertType
9349 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9350                                                ExprResult &RHS) {
9351   QualType RHSType = RHS.get()->getType();
9352 
9353   // If the ArgType is a Union type, we want to handle a potential
9354   // transparent_union GCC extension.
9355   const RecordType *UT = ArgType->getAsUnionType();
9356   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9357     return Incompatible;
9358 
9359   // The field to initialize within the transparent union.
9360   RecordDecl *UD = UT->getDecl();
9361   FieldDecl *InitField = nullptr;
9362   // It's compatible if the expression matches any of the fields.
9363   for (auto *it : UD->fields()) {
9364     if (it->getType()->isPointerType()) {
9365       // If the transparent union contains a pointer type, we allow:
9366       // 1) void pointer
9367       // 2) null pointer constant
9368       if (RHSType->isPointerType())
9369         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9370           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9371           InitField = it;
9372           break;
9373         }
9374 
9375       if (RHS.get()->isNullPointerConstant(Context,
9376                                            Expr::NPC_ValueDependentIsNull)) {
9377         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9378                                 CK_NullToPointer);
9379         InitField = it;
9380         break;
9381       }
9382     }
9383 
9384     CastKind Kind;
9385     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9386           == Compatible) {
9387       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9388       InitField = it;
9389       break;
9390     }
9391   }
9392 
9393   if (!InitField)
9394     return Incompatible;
9395 
9396   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9397   return Compatible;
9398 }
9399 
9400 Sema::AssignConvertType
9401 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9402                                        bool Diagnose,
9403                                        bool DiagnoseCFAudited,
9404                                        bool ConvertRHS) {
9405   // We need to be able to tell the caller whether we diagnosed a problem, if
9406   // they ask us to issue diagnostics.
9407   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9408 
9409   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9410   // we can't avoid *all* modifications at the moment, so we need some somewhere
9411   // to put the updated value.
9412   ExprResult LocalRHS = CallerRHS;
9413   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9414 
9415   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9416     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9417       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9418           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9419         Diag(RHS.get()->getExprLoc(),
9420              diag::warn_noderef_to_dereferenceable_pointer)
9421             << RHS.get()->getSourceRange();
9422       }
9423     }
9424   }
9425 
9426   if (getLangOpts().CPlusPlus) {
9427     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9428       // C++ 5.17p3: If the left operand is not of class type, the
9429       // expression is implicitly converted (C++ 4) to the
9430       // cv-unqualified type of the left operand.
9431       QualType RHSType = RHS.get()->getType();
9432       if (Diagnose) {
9433         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9434                                         AA_Assigning);
9435       } else {
9436         ImplicitConversionSequence ICS =
9437             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9438                                   /*SuppressUserConversions=*/false,
9439                                   AllowedExplicit::None,
9440                                   /*InOverloadResolution=*/false,
9441                                   /*CStyle=*/false,
9442                                   /*AllowObjCWritebackConversion=*/false);
9443         if (ICS.isFailure())
9444           return Incompatible;
9445         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9446                                         ICS, AA_Assigning);
9447       }
9448       if (RHS.isInvalid())
9449         return Incompatible;
9450       Sema::AssignConvertType result = Compatible;
9451       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9452           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9453         result = IncompatibleObjCWeakRef;
9454       return result;
9455     }
9456 
9457     // FIXME: Currently, we fall through and treat C++ classes like C
9458     // structures.
9459     // FIXME: We also fall through for atomics; not sure what should
9460     // happen there, though.
9461   } else if (RHS.get()->getType() == Context.OverloadTy) {
9462     // As a set of extensions to C, we support overloading on functions. These
9463     // functions need to be resolved here.
9464     DeclAccessPair DAP;
9465     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9466             RHS.get(), LHSType, /*Complain=*/false, DAP))
9467       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9468     else
9469       return Incompatible;
9470   }
9471 
9472   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9473   // a null pointer constant.
9474   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9475        LHSType->isBlockPointerType()) &&
9476       RHS.get()->isNullPointerConstant(Context,
9477                                        Expr::NPC_ValueDependentIsNull)) {
9478     if (Diagnose || ConvertRHS) {
9479       CastKind Kind;
9480       CXXCastPath Path;
9481       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9482                              /*IgnoreBaseAccess=*/false, Diagnose);
9483       if (ConvertRHS)
9484         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9485     }
9486     return Compatible;
9487   }
9488 
9489   // OpenCL queue_t type assignment.
9490   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9491                                  Context, Expr::NPC_ValueDependentIsNull)) {
9492     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9493     return Compatible;
9494   }
9495 
9496   // This check seems unnatural, however it is necessary to ensure the proper
9497   // conversion of functions/arrays. If the conversion were done for all
9498   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9499   // expressions that suppress this implicit conversion (&, sizeof).
9500   //
9501   // Suppress this for references: C++ 8.5.3p5.
9502   if (!LHSType->isReferenceType()) {
9503     // FIXME: We potentially allocate here even if ConvertRHS is false.
9504     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9505     if (RHS.isInvalid())
9506       return Incompatible;
9507   }
9508   CastKind Kind;
9509   Sema::AssignConvertType result =
9510     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9511 
9512   // C99 6.5.16.1p2: The value of the right operand is converted to the
9513   // type of the assignment expression.
9514   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9515   // so that we can use references in built-in functions even in C.
9516   // The getNonReferenceType() call makes sure that the resulting expression
9517   // does not have reference type.
9518   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9519     QualType Ty = LHSType.getNonLValueExprType(Context);
9520     Expr *E = RHS.get();
9521 
9522     // Check for various Objective-C errors. If we are not reporting
9523     // diagnostics and just checking for errors, e.g., during overload
9524     // resolution, return Incompatible to indicate the failure.
9525     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9526         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9527                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9528       if (!Diagnose)
9529         return Incompatible;
9530     }
9531     if (getLangOpts().ObjC &&
9532         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9533                                            E->getType(), E, Diagnose) ||
9534          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9535       if (!Diagnose)
9536         return Incompatible;
9537       // Replace the expression with a corrected version and continue so we
9538       // can find further errors.
9539       RHS = E;
9540       return Compatible;
9541     }
9542 
9543     if (ConvertRHS)
9544       RHS = ImpCastExprToType(E, Ty, Kind);
9545   }
9546 
9547   return result;
9548 }
9549 
9550 namespace {
9551 /// The original operand to an operator, prior to the application of the usual
9552 /// arithmetic conversions and converting the arguments of a builtin operator
9553 /// candidate.
9554 struct OriginalOperand {
9555   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9556     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9557       Op = MTE->getSubExpr();
9558     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9559       Op = BTE->getSubExpr();
9560     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9561       Orig = ICE->getSubExprAsWritten();
9562       Conversion = ICE->getConversionFunction();
9563     }
9564   }
9565 
9566   QualType getType() const { return Orig->getType(); }
9567 
9568   Expr *Orig;
9569   NamedDecl *Conversion;
9570 };
9571 }
9572 
9573 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9574                                ExprResult &RHS) {
9575   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9576 
9577   Diag(Loc, diag::err_typecheck_invalid_operands)
9578     << OrigLHS.getType() << OrigRHS.getType()
9579     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9580 
9581   // If a user-defined conversion was applied to either of the operands prior
9582   // to applying the built-in operator rules, tell the user about it.
9583   if (OrigLHS.Conversion) {
9584     Diag(OrigLHS.Conversion->getLocation(),
9585          diag::note_typecheck_invalid_operands_converted)
9586       << 0 << LHS.get()->getType();
9587   }
9588   if (OrigRHS.Conversion) {
9589     Diag(OrigRHS.Conversion->getLocation(),
9590          diag::note_typecheck_invalid_operands_converted)
9591       << 1 << RHS.get()->getType();
9592   }
9593 
9594   return QualType();
9595 }
9596 
9597 // Diagnose cases where a scalar was implicitly converted to a vector and
9598 // diagnose the underlying types. Otherwise, diagnose the error
9599 // as invalid vector logical operands for non-C++ cases.
9600 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9601                                             ExprResult &RHS) {
9602   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9603   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9604 
9605   bool LHSNatVec = LHSType->isVectorType();
9606   bool RHSNatVec = RHSType->isVectorType();
9607 
9608   if (!(LHSNatVec && RHSNatVec)) {
9609     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9610     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9611     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9612         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9613         << Vector->getSourceRange();
9614     return QualType();
9615   }
9616 
9617   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9618       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9619       << RHS.get()->getSourceRange();
9620 
9621   return QualType();
9622 }
9623 
9624 /// Try to convert a value of non-vector type to a vector type by converting
9625 /// the type to the element type of the vector and then performing a splat.
9626 /// If the language is OpenCL, we only use conversions that promote scalar
9627 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9628 /// for float->int.
9629 ///
9630 /// OpenCL V2.0 6.2.6.p2:
9631 /// An error shall occur if any scalar operand type has greater rank
9632 /// than the type of the vector element.
9633 ///
9634 /// \param scalar - if non-null, actually perform the conversions
9635 /// \return true if the operation fails (but without diagnosing the failure)
9636 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9637                                      QualType scalarTy,
9638                                      QualType vectorEltTy,
9639                                      QualType vectorTy,
9640                                      unsigned &DiagID) {
9641   // The conversion to apply to the scalar before splatting it,
9642   // if necessary.
9643   CastKind scalarCast = CK_NoOp;
9644 
9645   if (vectorEltTy->isIntegralType(S.Context)) {
9646     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9647         (scalarTy->isIntegerType() &&
9648          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9649       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9650       return true;
9651     }
9652     if (!scalarTy->isIntegralType(S.Context))
9653       return true;
9654     scalarCast = CK_IntegralCast;
9655   } else if (vectorEltTy->isRealFloatingType()) {
9656     if (scalarTy->isRealFloatingType()) {
9657       if (S.getLangOpts().OpenCL &&
9658           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9659         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9660         return true;
9661       }
9662       scalarCast = CK_FloatingCast;
9663     }
9664     else if (scalarTy->isIntegralType(S.Context))
9665       scalarCast = CK_IntegralToFloating;
9666     else
9667       return true;
9668   } else {
9669     return true;
9670   }
9671 
9672   // Adjust scalar if desired.
9673   if (scalar) {
9674     if (scalarCast != CK_NoOp)
9675       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9676     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9677   }
9678   return false;
9679 }
9680 
9681 /// Convert vector E to a vector with the same number of elements but different
9682 /// element type.
9683 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9684   const auto *VecTy = E->getType()->getAs<VectorType>();
9685   assert(VecTy && "Expression E must be a vector");
9686   QualType NewVecTy = S.Context.getVectorType(ElementType,
9687                                               VecTy->getNumElements(),
9688                                               VecTy->getVectorKind());
9689 
9690   // Look through the implicit cast. Return the subexpression if its type is
9691   // NewVecTy.
9692   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9693     if (ICE->getSubExpr()->getType() == NewVecTy)
9694       return ICE->getSubExpr();
9695 
9696   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9697   return S.ImpCastExprToType(E, NewVecTy, Cast);
9698 }
9699 
9700 /// Test if a (constant) integer Int can be casted to another integer type
9701 /// IntTy without losing precision.
9702 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9703                                       QualType OtherIntTy) {
9704   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9705 
9706   // Reject cases where the value of the Int is unknown as that would
9707   // possibly cause truncation, but accept cases where the scalar can be
9708   // demoted without loss of precision.
9709   Expr::EvalResult EVResult;
9710   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9711   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9712   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9713   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9714 
9715   if (CstInt) {
9716     // If the scalar is constant and is of a higher order and has more active
9717     // bits that the vector element type, reject it.
9718     llvm::APSInt Result = EVResult.Val.getInt();
9719     unsigned NumBits = IntSigned
9720                            ? (Result.isNegative() ? Result.getMinSignedBits()
9721                                                   : Result.getActiveBits())
9722                            : Result.getActiveBits();
9723     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9724       return true;
9725 
9726     // If the signedness of the scalar type and the vector element type
9727     // differs and the number of bits is greater than that of the vector
9728     // element reject it.
9729     return (IntSigned != OtherIntSigned &&
9730             NumBits > S.Context.getIntWidth(OtherIntTy));
9731   }
9732 
9733   // Reject cases where the value of the scalar is not constant and it's
9734   // order is greater than that of the vector element type.
9735   return (Order < 0);
9736 }
9737 
9738 /// Test if a (constant) integer Int can be casted to floating point type
9739 /// FloatTy without losing precision.
9740 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9741                                      QualType FloatTy) {
9742   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9743 
9744   // Determine if the integer constant can be expressed as a floating point
9745   // number of the appropriate type.
9746   Expr::EvalResult EVResult;
9747   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9748 
9749   uint64_t Bits = 0;
9750   if (CstInt) {
9751     // Reject constants that would be truncated if they were converted to
9752     // the floating point type. Test by simple to/from conversion.
9753     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9754     //        could be avoided if there was a convertFromAPInt method
9755     //        which could signal back if implicit truncation occurred.
9756     llvm::APSInt Result = EVResult.Val.getInt();
9757     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9758     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9759                            llvm::APFloat::rmTowardZero);
9760     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9761                              !IntTy->hasSignedIntegerRepresentation());
9762     bool Ignored = false;
9763     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9764                            &Ignored);
9765     if (Result != ConvertBack)
9766       return true;
9767   } else {
9768     // Reject types that cannot be fully encoded into the mantissa of
9769     // the float.
9770     Bits = S.Context.getTypeSize(IntTy);
9771     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9772         S.Context.getFloatTypeSemantics(FloatTy));
9773     if (Bits > FloatPrec)
9774       return true;
9775   }
9776 
9777   return false;
9778 }
9779 
9780 /// Attempt to convert and splat Scalar into a vector whose types matches
9781 /// Vector following GCC conversion rules. The rule is that implicit
9782 /// conversion can occur when Scalar can be casted to match Vector's element
9783 /// type without causing truncation of Scalar.
9784 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9785                                         ExprResult *Vector) {
9786   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9787   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9788   const VectorType *VT = VectorTy->getAs<VectorType>();
9789 
9790   assert(!isa<ExtVectorType>(VT) &&
9791          "ExtVectorTypes should not be handled here!");
9792 
9793   QualType VectorEltTy = VT->getElementType();
9794 
9795   // Reject cases where the vector element type or the scalar element type are
9796   // not integral or floating point types.
9797   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9798     return true;
9799 
9800   // The conversion to apply to the scalar before splatting it,
9801   // if necessary.
9802   CastKind ScalarCast = CK_NoOp;
9803 
9804   // Accept cases where the vector elements are integers and the scalar is
9805   // an integer.
9806   // FIXME: Notionally if the scalar was a floating point value with a precise
9807   //        integral representation, we could cast it to an appropriate integer
9808   //        type and then perform the rest of the checks here. GCC will perform
9809   //        this conversion in some cases as determined by the input language.
9810   //        We should accept it on a language independent basis.
9811   if (VectorEltTy->isIntegralType(S.Context) &&
9812       ScalarTy->isIntegralType(S.Context) &&
9813       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9814 
9815     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9816       return true;
9817 
9818     ScalarCast = CK_IntegralCast;
9819   } else if (VectorEltTy->isIntegralType(S.Context) &&
9820              ScalarTy->isRealFloatingType()) {
9821     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9822       ScalarCast = CK_FloatingToIntegral;
9823     else
9824       return true;
9825   } else if (VectorEltTy->isRealFloatingType()) {
9826     if (ScalarTy->isRealFloatingType()) {
9827 
9828       // Reject cases where the scalar type is not a constant and has a higher
9829       // Order than the vector element type.
9830       llvm::APFloat Result(0.0);
9831 
9832       // Determine whether this is a constant scalar. In the event that the
9833       // value is dependent (and thus cannot be evaluated by the constant
9834       // evaluator), skip the evaluation. This will then diagnose once the
9835       // expression is instantiated.
9836       bool CstScalar = Scalar->get()->isValueDependent() ||
9837                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9838       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9839       if (!CstScalar && Order < 0)
9840         return true;
9841 
9842       // If the scalar cannot be safely casted to the vector element type,
9843       // reject it.
9844       if (CstScalar) {
9845         bool Truncated = false;
9846         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9847                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9848         if (Truncated)
9849           return true;
9850       }
9851 
9852       ScalarCast = CK_FloatingCast;
9853     } else if (ScalarTy->isIntegralType(S.Context)) {
9854       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9855         return true;
9856 
9857       ScalarCast = CK_IntegralToFloating;
9858     } else
9859       return true;
9860   } else if (ScalarTy->isEnumeralType())
9861     return true;
9862 
9863   // Adjust scalar if desired.
9864   if (Scalar) {
9865     if (ScalarCast != CK_NoOp)
9866       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9867     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9868   }
9869   return false;
9870 }
9871 
9872 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9873                                    SourceLocation Loc, bool IsCompAssign,
9874                                    bool AllowBothBool,
9875                                    bool AllowBoolConversions) {
9876   if (!IsCompAssign) {
9877     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9878     if (LHS.isInvalid())
9879       return QualType();
9880   }
9881   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9882   if (RHS.isInvalid())
9883     return QualType();
9884 
9885   // For conversion purposes, we ignore any qualifiers.
9886   // For example, "const float" and "float" are equivalent.
9887   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9888   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9889 
9890   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9891   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9892   assert(LHSVecType || RHSVecType);
9893 
9894   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9895       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9896     return InvalidOperands(Loc, LHS, RHS);
9897 
9898   // AltiVec-style "vector bool op vector bool" combinations are allowed
9899   // for some operators but not others.
9900   if (!AllowBothBool &&
9901       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9902       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9903     return InvalidOperands(Loc, LHS, RHS);
9904 
9905   // If the vector types are identical, return.
9906   if (Context.hasSameType(LHSType, RHSType))
9907     return LHSType;
9908 
9909   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9910   if (LHSVecType && RHSVecType &&
9911       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9912     if (isa<ExtVectorType>(LHSVecType)) {
9913       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9914       return LHSType;
9915     }
9916 
9917     if (!IsCompAssign)
9918       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9919     return RHSType;
9920   }
9921 
9922   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9923   // can be mixed, with the result being the non-bool type.  The non-bool
9924   // operand must have integer element type.
9925   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9926       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9927       (Context.getTypeSize(LHSVecType->getElementType()) ==
9928        Context.getTypeSize(RHSVecType->getElementType()))) {
9929     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9930         LHSVecType->getElementType()->isIntegerType() &&
9931         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9932       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9933       return LHSType;
9934     }
9935     if (!IsCompAssign &&
9936         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9937         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9938         RHSVecType->getElementType()->isIntegerType()) {
9939       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9940       return RHSType;
9941     }
9942   }
9943 
9944   // Expressions containing fixed-length and sizeless SVE vectors are invalid
9945   // since the ambiguity can affect the ABI.
9946   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9947     const VectorType *VecType = SecondType->getAs<VectorType>();
9948     return FirstType->isSizelessBuiltinType() && VecType &&
9949            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9950             VecType->getVectorKind() ==
9951                 VectorType::SveFixedLengthPredicateVector);
9952   };
9953 
9954   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9955     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9956     return QualType();
9957   }
9958 
9959   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9960   // since the ambiguity can affect the ABI.
9961   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9962     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9963     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9964 
9965     if (FirstVecType && SecondVecType)
9966       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9967              (SecondVecType->getVectorKind() ==
9968                   VectorType::SveFixedLengthDataVector ||
9969               SecondVecType->getVectorKind() ==
9970                   VectorType::SveFixedLengthPredicateVector);
9971 
9972     return FirstType->isSizelessBuiltinType() && SecondVecType &&
9973            SecondVecType->getVectorKind() == VectorType::GenericVector;
9974   };
9975 
9976   if (IsSveGnuConversion(LHSType, RHSType) ||
9977       IsSveGnuConversion(RHSType, LHSType)) {
9978     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9979     return QualType();
9980   }
9981 
9982   // If there's a vector type and a scalar, try to convert the scalar to
9983   // the vector element type and splat.
9984   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9985   if (!RHSVecType) {
9986     if (isa<ExtVectorType>(LHSVecType)) {
9987       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9988                                     LHSVecType->getElementType(), LHSType,
9989                                     DiagID))
9990         return LHSType;
9991     } else {
9992       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9993         return LHSType;
9994     }
9995   }
9996   if (!LHSVecType) {
9997     if (isa<ExtVectorType>(RHSVecType)) {
9998       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9999                                     LHSType, RHSVecType->getElementType(),
10000                                     RHSType, DiagID))
10001         return RHSType;
10002     } else {
10003       if (LHS.get()->getValueKind() == VK_LValue ||
10004           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10005         return RHSType;
10006     }
10007   }
10008 
10009   // FIXME: The code below also handles conversion between vectors and
10010   // non-scalars, we should break this down into fine grained specific checks
10011   // and emit proper diagnostics.
10012   QualType VecType = LHSVecType ? LHSType : RHSType;
10013   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10014   QualType OtherType = LHSVecType ? RHSType : LHSType;
10015   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10016   if (isLaxVectorConversion(OtherType, VecType)) {
10017     // If we're allowing lax vector conversions, only the total (data) size
10018     // needs to be the same. For non compound assignment, if one of the types is
10019     // scalar, the result is always the vector type.
10020     if (!IsCompAssign) {
10021       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10022       return VecType;
10023     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10024     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10025     // type. Note that this is already done by non-compound assignments in
10026     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10027     // <1 x T> -> T. The result is also a vector type.
10028     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10029                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10030       ExprResult *RHSExpr = &RHS;
10031       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10032       return VecType;
10033     }
10034   }
10035 
10036   // Okay, the expression is invalid.
10037 
10038   // If there's a non-vector, non-real operand, diagnose that.
10039   if ((!RHSVecType && !RHSType->isRealType()) ||
10040       (!LHSVecType && !LHSType->isRealType())) {
10041     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10042       << LHSType << RHSType
10043       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10044     return QualType();
10045   }
10046 
10047   // OpenCL V1.1 6.2.6.p1:
10048   // If the operands are of more than one vector type, then an error shall
10049   // occur. Implicit conversions between vector types are not permitted, per
10050   // section 6.2.1.
10051   if (getLangOpts().OpenCL &&
10052       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10053       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10054     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10055                                                            << RHSType;
10056     return QualType();
10057   }
10058 
10059 
10060   // If there is a vector type that is not a ExtVector and a scalar, we reach
10061   // this point if scalar could not be converted to the vector's element type
10062   // without truncation.
10063   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10064       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10065     QualType Scalar = LHSVecType ? RHSType : LHSType;
10066     QualType Vector = LHSVecType ? LHSType : RHSType;
10067     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10068     Diag(Loc,
10069          diag::err_typecheck_vector_not_convertable_implict_truncation)
10070         << ScalarOrVector << Scalar << Vector;
10071 
10072     return QualType();
10073   }
10074 
10075   // Otherwise, use the generic diagnostic.
10076   Diag(Loc, DiagID)
10077     << LHSType << RHSType
10078     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10079   return QualType();
10080 }
10081 
10082 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10083 // expression.  These are mainly cases where the null pointer is used as an
10084 // integer instead of a pointer.
10085 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10086                                 SourceLocation Loc, bool IsCompare) {
10087   // The canonical way to check for a GNU null is with isNullPointerConstant,
10088   // but we use a bit of a hack here for speed; this is a relatively
10089   // hot path, and isNullPointerConstant is slow.
10090   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10091   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10092 
10093   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10094 
10095   // Avoid analyzing cases where the result will either be invalid (and
10096   // diagnosed as such) or entirely valid and not something to warn about.
10097   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10098       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10099     return;
10100 
10101   // Comparison operations would not make sense with a null pointer no matter
10102   // what the other expression is.
10103   if (!IsCompare) {
10104     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10105         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10106         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10107     return;
10108   }
10109 
10110   // The rest of the operations only make sense with a null pointer
10111   // if the other expression is a pointer.
10112   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10113       NonNullType->canDecayToPointerType())
10114     return;
10115 
10116   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10117       << LHSNull /* LHS is NULL */ << NonNullType
10118       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10119 }
10120 
10121 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10122                                           SourceLocation Loc) {
10123   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10124   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10125   if (!LUE || !RUE)
10126     return;
10127   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10128       RUE->getKind() != UETT_SizeOf)
10129     return;
10130 
10131   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10132   QualType LHSTy = LHSArg->getType();
10133   QualType RHSTy;
10134 
10135   if (RUE->isArgumentType())
10136     RHSTy = RUE->getArgumentType().getNonReferenceType();
10137   else
10138     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10139 
10140   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10141     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10142       return;
10143 
10144     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10145     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10146       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10147         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10148             << LHSArgDecl;
10149     }
10150   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10151     QualType ArrayElemTy = ArrayTy->getElementType();
10152     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10153         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10154         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10155         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10156       return;
10157     S.Diag(Loc, diag::warn_division_sizeof_array)
10158         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10159     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10160       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10161         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10162             << LHSArgDecl;
10163     }
10164 
10165     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10166   }
10167 }
10168 
10169 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10170                                                ExprResult &RHS,
10171                                                SourceLocation Loc, bool IsDiv) {
10172   // Check for division/remainder by zero.
10173   Expr::EvalResult RHSValue;
10174   if (!RHS.get()->isValueDependent() &&
10175       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10176       RHSValue.Val.getInt() == 0)
10177     S.DiagRuntimeBehavior(Loc, RHS.get(),
10178                           S.PDiag(diag::warn_remainder_division_by_zero)
10179                             << IsDiv << RHS.get()->getSourceRange());
10180 }
10181 
10182 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10183                                            SourceLocation Loc,
10184                                            bool IsCompAssign, bool IsDiv) {
10185   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10186 
10187   if (LHS.get()->getType()->isVectorType() ||
10188       RHS.get()->getType()->isVectorType())
10189     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10190                                /*AllowBothBool*/getLangOpts().AltiVec,
10191                                /*AllowBoolConversions*/false);
10192   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10193                  RHS.get()->getType()->isConstantMatrixType()))
10194     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10195 
10196   QualType compType = UsualArithmeticConversions(
10197       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10198   if (LHS.isInvalid() || RHS.isInvalid())
10199     return QualType();
10200 
10201 
10202   if (compType.isNull() || !compType->isArithmeticType())
10203     return InvalidOperands(Loc, LHS, RHS);
10204   if (IsDiv) {
10205     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10206     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10207   }
10208   return compType;
10209 }
10210 
10211 QualType Sema::CheckRemainderOperands(
10212   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10213   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10214 
10215   if (LHS.get()->getType()->isVectorType() ||
10216       RHS.get()->getType()->isVectorType()) {
10217     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10218         RHS.get()->getType()->hasIntegerRepresentation())
10219       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10220                                  /*AllowBothBool*/getLangOpts().AltiVec,
10221                                  /*AllowBoolConversions*/false);
10222     return InvalidOperands(Loc, LHS, RHS);
10223   }
10224 
10225   QualType compType = UsualArithmeticConversions(
10226       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10227   if (LHS.isInvalid() || RHS.isInvalid())
10228     return QualType();
10229 
10230   if (compType.isNull() || !compType->isIntegerType())
10231     return InvalidOperands(Loc, LHS, RHS);
10232   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10233   return compType;
10234 }
10235 
10236 /// Diagnose invalid arithmetic on two void pointers.
10237 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10238                                                 Expr *LHSExpr, Expr *RHSExpr) {
10239   S.Diag(Loc, S.getLangOpts().CPlusPlus
10240                 ? diag::err_typecheck_pointer_arith_void_type
10241                 : diag::ext_gnu_void_ptr)
10242     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10243                             << RHSExpr->getSourceRange();
10244 }
10245 
10246 /// Diagnose invalid arithmetic on a void pointer.
10247 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10248                                             Expr *Pointer) {
10249   S.Diag(Loc, S.getLangOpts().CPlusPlus
10250                 ? diag::err_typecheck_pointer_arith_void_type
10251                 : diag::ext_gnu_void_ptr)
10252     << 0 /* one pointer */ << Pointer->getSourceRange();
10253 }
10254 
10255 /// Diagnose invalid arithmetic on a null pointer.
10256 ///
10257 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10258 /// idiom, which we recognize as a GNU extension.
10259 ///
10260 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10261                                             Expr *Pointer, bool IsGNUIdiom) {
10262   if (IsGNUIdiom)
10263     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10264       << Pointer->getSourceRange();
10265   else
10266     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10267       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10268 }
10269 
10270 /// Diagnose invalid arithmetic on two function pointers.
10271 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10272                                                     Expr *LHS, Expr *RHS) {
10273   assert(LHS->getType()->isAnyPointerType());
10274   assert(RHS->getType()->isAnyPointerType());
10275   S.Diag(Loc, S.getLangOpts().CPlusPlus
10276                 ? diag::err_typecheck_pointer_arith_function_type
10277                 : diag::ext_gnu_ptr_func_arith)
10278     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10279     // We only show the second type if it differs from the first.
10280     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10281                                                    RHS->getType())
10282     << RHS->getType()->getPointeeType()
10283     << LHS->getSourceRange() << RHS->getSourceRange();
10284 }
10285 
10286 /// Diagnose invalid arithmetic on a function pointer.
10287 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10288                                                 Expr *Pointer) {
10289   assert(Pointer->getType()->isAnyPointerType());
10290   S.Diag(Loc, S.getLangOpts().CPlusPlus
10291                 ? diag::err_typecheck_pointer_arith_function_type
10292                 : diag::ext_gnu_ptr_func_arith)
10293     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10294     << 0 /* one pointer, so only one type */
10295     << Pointer->getSourceRange();
10296 }
10297 
10298 /// Emit error if Operand is incomplete pointer type
10299 ///
10300 /// \returns True if pointer has incomplete type
10301 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10302                                                  Expr *Operand) {
10303   QualType ResType = Operand->getType();
10304   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10305     ResType = ResAtomicType->getValueType();
10306 
10307   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10308   QualType PointeeTy = ResType->getPointeeType();
10309   return S.RequireCompleteSizedType(
10310       Loc, PointeeTy,
10311       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10312       Operand->getSourceRange());
10313 }
10314 
10315 /// Check the validity of an arithmetic pointer operand.
10316 ///
10317 /// If the operand has pointer type, this code will check for pointer types
10318 /// which are invalid in arithmetic operations. These will be diagnosed
10319 /// appropriately, including whether or not the use is supported as an
10320 /// extension.
10321 ///
10322 /// \returns True when the operand is valid to use (even if as an extension).
10323 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10324                                             Expr *Operand) {
10325   QualType ResType = Operand->getType();
10326   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10327     ResType = ResAtomicType->getValueType();
10328 
10329   if (!ResType->isAnyPointerType()) return true;
10330 
10331   QualType PointeeTy = ResType->getPointeeType();
10332   if (PointeeTy->isVoidType()) {
10333     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10334     return !S.getLangOpts().CPlusPlus;
10335   }
10336   if (PointeeTy->isFunctionType()) {
10337     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10338     return !S.getLangOpts().CPlusPlus;
10339   }
10340 
10341   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10342 
10343   return true;
10344 }
10345 
10346 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10347 /// operands.
10348 ///
10349 /// This routine will diagnose any invalid arithmetic on pointer operands much
10350 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10351 /// for emitting a single diagnostic even for operations where both LHS and RHS
10352 /// are (potentially problematic) pointers.
10353 ///
10354 /// \returns True when the operand is valid to use (even if as an extension).
10355 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10356                                                 Expr *LHSExpr, Expr *RHSExpr) {
10357   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10358   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10359   if (!isLHSPointer && !isRHSPointer) return true;
10360 
10361   QualType LHSPointeeTy, RHSPointeeTy;
10362   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10363   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10364 
10365   // if both are pointers check if operation is valid wrt address spaces
10366   if (isLHSPointer && isRHSPointer) {
10367     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10368       S.Diag(Loc,
10369              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10370           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10371           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10372       return false;
10373     }
10374   }
10375 
10376   // Check for arithmetic on pointers to incomplete types.
10377   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10378   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10379   if (isLHSVoidPtr || isRHSVoidPtr) {
10380     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10381     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10382     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10383 
10384     return !S.getLangOpts().CPlusPlus;
10385   }
10386 
10387   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10388   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10389   if (isLHSFuncPtr || isRHSFuncPtr) {
10390     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10391     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10392                                                                 RHSExpr);
10393     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10394 
10395     return !S.getLangOpts().CPlusPlus;
10396   }
10397 
10398   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10399     return false;
10400   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10401     return false;
10402 
10403   return true;
10404 }
10405 
10406 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10407 /// literal.
10408 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10409                                   Expr *LHSExpr, Expr *RHSExpr) {
10410   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10411   Expr* IndexExpr = RHSExpr;
10412   if (!StrExpr) {
10413     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10414     IndexExpr = LHSExpr;
10415   }
10416 
10417   bool IsStringPlusInt = StrExpr &&
10418       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10419   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10420     return;
10421 
10422   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10423   Self.Diag(OpLoc, diag::warn_string_plus_int)
10424       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10425 
10426   // Only print a fixit for "str" + int, not for int + "str".
10427   if (IndexExpr == RHSExpr) {
10428     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10429     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10430         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10431         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10432         << FixItHint::CreateInsertion(EndLoc, "]");
10433   } else
10434     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10435 }
10436 
10437 /// Emit a warning when adding a char literal to a string.
10438 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10439                                    Expr *LHSExpr, Expr *RHSExpr) {
10440   const Expr *StringRefExpr = LHSExpr;
10441   const CharacterLiteral *CharExpr =
10442       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10443 
10444   if (!CharExpr) {
10445     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10446     StringRefExpr = RHSExpr;
10447   }
10448 
10449   if (!CharExpr || !StringRefExpr)
10450     return;
10451 
10452   const QualType StringType = StringRefExpr->getType();
10453 
10454   // Return if not a PointerType.
10455   if (!StringType->isAnyPointerType())
10456     return;
10457 
10458   // Return if not a CharacterType.
10459   if (!StringType->getPointeeType()->isAnyCharacterType())
10460     return;
10461 
10462   ASTContext &Ctx = Self.getASTContext();
10463   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10464 
10465   const QualType CharType = CharExpr->getType();
10466   if (!CharType->isAnyCharacterType() &&
10467       CharType->isIntegerType() &&
10468       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10469     Self.Diag(OpLoc, diag::warn_string_plus_char)
10470         << DiagRange << Ctx.CharTy;
10471   } else {
10472     Self.Diag(OpLoc, diag::warn_string_plus_char)
10473         << DiagRange << CharExpr->getType();
10474   }
10475 
10476   // Only print a fixit for str + char, not for char + str.
10477   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10478     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10479     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10480         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10481         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10482         << FixItHint::CreateInsertion(EndLoc, "]");
10483   } else {
10484     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10485   }
10486 }
10487 
10488 /// Emit error when two pointers are incompatible.
10489 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10490                                            Expr *LHSExpr, Expr *RHSExpr) {
10491   assert(LHSExpr->getType()->isAnyPointerType());
10492   assert(RHSExpr->getType()->isAnyPointerType());
10493   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10494     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10495     << RHSExpr->getSourceRange();
10496 }
10497 
10498 // C99 6.5.6
10499 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10500                                      SourceLocation Loc, BinaryOperatorKind Opc,
10501                                      QualType* CompLHSTy) {
10502   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10503 
10504   if (LHS.get()->getType()->isVectorType() ||
10505       RHS.get()->getType()->isVectorType()) {
10506     QualType compType = CheckVectorOperands(
10507         LHS, RHS, Loc, CompLHSTy,
10508         /*AllowBothBool*/getLangOpts().AltiVec,
10509         /*AllowBoolConversions*/getLangOpts().ZVector);
10510     if (CompLHSTy) *CompLHSTy = compType;
10511     return compType;
10512   }
10513 
10514   if (LHS.get()->getType()->isConstantMatrixType() ||
10515       RHS.get()->getType()->isConstantMatrixType()) {
10516     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10517   }
10518 
10519   QualType compType = UsualArithmeticConversions(
10520       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10521   if (LHS.isInvalid() || RHS.isInvalid())
10522     return QualType();
10523 
10524   // Diagnose "string literal" '+' int and string '+' "char literal".
10525   if (Opc == BO_Add) {
10526     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10527     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10528   }
10529 
10530   // handle the common case first (both operands are arithmetic).
10531   if (!compType.isNull() && compType->isArithmeticType()) {
10532     if (CompLHSTy) *CompLHSTy = compType;
10533     return compType;
10534   }
10535 
10536   // Type-checking.  Ultimately the pointer's going to be in PExp;
10537   // note that we bias towards the LHS being the pointer.
10538   Expr *PExp = LHS.get(), *IExp = RHS.get();
10539 
10540   bool isObjCPointer;
10541   if (PExp->getType()->isPointerType()) {
10542     isObjCPointer = false;
10543   } else if (PExp->getType()->isObjCObjectPointerType()) {
10544     isObjCPointer = true;
10545   } else {
10546     std::swap(PExp, IExp);
10547     if (PExp->getType()->isPointerType()) {
10548       isObjCPointer = false;
10549     } else if (PExp->getType()->isObjCObjectPointerType()) {
10550       isObjCPointer = true;
10551     } else {
10552       return InvalidOperands(Loc, LHS, RHS);
10553     }
10554   }
10555   assert(PExp->getType()->isAnyPointerType());
10556 
10557   if (!IExp->getType()->isIntegerType())
10558     return InvalidOperands(Loc, LHS, RHS);
10559 
10560   // Adding to a null pointer results in undefined behavior.
10561   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10562           Context, Expr::NPC_ValueDependentIsNotNull)) {
10563     // In C++ adding zero to a null pointer is defined.
10564     Expr::EvalResult KnownVal;
10565     if (!getLangOpts().CPlusPlus ||
10566         (!IExp->isValueDependent() &&
10567          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10568           KnownVal.Val.getInt() != 0))) {
10569       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10570       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10571           Context, BO_Add, PExp, IExp);
10572       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10573     }
10574   }
10575 
10576   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10577     return QualType();
10578 
10579   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10580     return QualType();
10581 
10582   // Check array bounds for pointer arithemtic
10583   CheckArrayAccess(PExp, IExp);
10584 
10585   if (CompLHSTy) {
10586     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10587     if (LHSTy.isNull()) {
10588       LHSTy = LHS.get()->getType();
10589       if (LHSTy->isPromotableIntegerType())
10590         LHSTy = Context.getPromotedIntegerType(LHSTy);
10591     }
10592     *CompLHSTy = LHSTy;
10593   }
10594 
10595   return PExp->getType();
10596 }
10597 
10598 // C99 6.5.6
10599 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10600                                         SourceLocation Loc,
10601                                         QualType* CompLHSTy) {
10602   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10603 
10604   if (LHS.get()->getType()->isVectorType() ||
10605       RHS.get()->getType()->isVectorType()) {
10606     QualType compType = CheckVectorOperands(
10607         LHS, RHS, Loc, CompLHSTy,
10608         /*AllowBothBool*/getLangOpts().AltiVec,
10609         /*AllowBoolConversions*/getLangOpts().ZVector);
10610     if (CompLHSTy) *CompLHSTy = compType;
10611     return compType;
10612   }
10613 
10614   if (LHS.get()->getType()->isConstantMatrixType() ||
10615       RHS.get()->getType()->isConstantMatrixType()) {
10616     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10617   }
10618 
10619   QualType compType = UsualArithmeticConversions(
10620       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10621   if (LHS.isInvalid() || RHS.isInvalid())
10622     return QualType();
10623 
10624   // Enforce type constraints: C99 6.5.6p3.
10625 
10626   // Handle the common case first (both operands are arithmetic).
10627   if (!compType.isNull() && compType->isArithmeticType()) {
10628     if (CompLHSTy) *CompLHSTy = compType;
10629     return compType;
10630   }
10631 
10632   // Either ptr - int   or   ptr - ptr.
10633   if (LHS.get()->getType()->isAnyPointerType()) {
10634     QualType lpointee = LHS.get()->getType()->getPointeeType();
10635 
10636     // Diagnose bad cases where we step over interface counts.
10637     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10638         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10639       return QualType();
10640 
10641     // The result type of a pointer-int computation is the pointer type.
10642     if (RHS.get()->getType()->isIntegerType()) {
10643       // Subtracting from a null pointer should produce a warning.
10644       // The last argument to the diagnose call says this doesn't match the
10645       // GNU int-to-pointer idiom.
10646       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10647                                            Expr::NPC_ValueDependentIsNotNull)) {
10648         // In C++ adding zero to a null pointer is defined.
10649         Expr::EvalResult KnownVal;
10650         if (!getLangOpts().CPlusPlus ||
10651             (!RHS.get()->isValueDependent() &&
10652              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10653               KnownVal.Val.getInt() != 0))) {
10654           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10655         }
10656       }
10657 
10658       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10659         return QualType();
10660 
10661       // Check array bounds for pointer arithemtic
10662       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10663                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10664 
10665       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10666       return LHS.get()->getType();
10667     }
10668 
10669     // Handle pointer-pointer subtractions.
10670     if (const PointerType *RHSPTy
10671           = RHS.get()->getType()->getAs<PointerType>()) {
10672       QualType rpointee = RHSPTy->getPointeeType();
10673 
10674       if (getLangOpts().CPlusPlus) {
10675         // Pointee types must be the same: C++ [expr.add]
10676         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10677           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10678         }
10679       } else {
10680         // Pointee types must be compatible C99 6.5.6p3
10681         if (!Context.typesAreCompatible(
10682                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10683                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10684           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10685           return QualType();
10686         }
10687       }
10688 
10689       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10690                                                LHS.get(), RHS.get()))
10691         return QualType();
10692 
10693       // FIXME: Add warnings for nullptr - ptr.
10694 
10695       // The pointee type may have zero size.  As an extension, a structure or
10696       // union may have zero size or an array may have zero length.  In this
10697       // case subtraction does not make sense.
10698       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10699         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10700         if (ElementSize.isZero()) {
10701           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10702             << rpointee.getUnqualifiedType()
10703             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10704         }
10705       }
10706 
10707       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10708       return Context.getPointerDiffType();
10709     }
10710   }
10711 
10712   return InvalidOperands(Loc, LHS, RHS);
10713 }
10714 
10715 static bool isScopedEnumerationType(QualType T) {
10716   if (const EnumType *ET = T->getAs<EnumType>())
10717     return ET->getDecl()->isScoped();
10718   return false;
10719 }
10720 
10721 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10722                                    SourceLocation Loc, BinaryOperatorKind Opc,
10723                                    QualType LHSType) {
10724   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10725   // so skip remaining warnings as we don't want to modify values within Sema.
10726   if (S.getLangOpts().OpenCL)
10727     return;
10728 
10729   // Check right/shifter operand
10730   Expr::EvalResult RHSResult;
10731   if (RHS.get()->isValueDependent() ||
10732       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10733     return;
10734   llvm::APSInt Right = RHSResult.Val.getInt();
10735 
10736   if (Right.isNegative()) {
10737     S.DiagRuntimeBehavior(Loc, RHS.get(),
10738                           S.PDiag(diag::warn_shift_negative)
10739                             << RHS.get()->getSourceRange());
10740     return;
10741   }
10742 
10743   QualType LHSExprType = LHS.get()->getType();
10744   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10745   if (LHSExprType->isExtIntType())
10746     LeftSize = S.Context.getIntWidth(LHSExprType);
10747   else if (LHSExprType->isFixedPointType()) {
10748     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10749     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10750   }
10751   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10752   if (Right.uge(LeftBits)) {
10753     S.DiagRuntimeBehavior(Loc, RHS.get(),
10754                           S.PDiag(diag::warn_shift_gt_typewidth)
10755                             << RHS.get()->getSourceRange());
10756     return;
10757   }
10758 
10759   // FIXME: We probably need to handle fixed point types specially here.
10760   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10761     return;
10762 
10763   // When left shifting an ICE which is signed, we can check for overflow which
10764   // according to C++ standards prior to C++2a has undefined behavior
10765   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10766   // more than the maximum value representable in the result type, so never
10767   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10768   // expression is still probably a bug.)
10769   Expr::EvalResult LHSResult;
10770   if (LHS.get()->isValueDependent() ||
10771       LHSType->hasUnsignedIntegerRepresentation() ||
10772       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10773     return;
10774   llvm::APSInt Left = LHSResult.Val.getInt();
10775 
10776   // If LHS does not have a signed type and non-negative value
10777   // then, the behavior is undefined before C++2a. Warn about it.
10778   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10779       !S.getLangOpts().CPlusPlus20) {
10780     S.DiagRuntimeBehavior(Loc, LHS.get(),
10781                           S.PDiag(diag::warn_shift_lhs_negative)
10782                             << LHS.get()->getSourceRange());
10783     return;
10784   }
10785 
10786   llvm::APInt ResultBits =
10787       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10788   if (LeftBits.uge(ResultBits))
10789     return;
10790   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10791   Result = Result.shl(Right);
10792 
10793   // Print the bit representation of the signed integer as an unsigned
10794   // hexadecimal number.
10795   SmallString<40> HexResult;
10796   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10797 
10798   // If we are only missing a sign bit, this is less likely to result in actual
10799   // bugs -- if the result is cast back to an unsigned type, it will have the
10800   // expected value. Thus we place this behind a different warning that can be
10801   // turned off separately if needed.
10802   if (LeftBits == ResultBits - 1) {
10803     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10804         << HexResult << LHSType
10805         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10806     return;
10807   }
10808 
10809   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10810     << HexResult.str() << Result.getMinSignedBits() << LHSType
10811     << Left.getBitWidth() << LHS.get()->getSourceRange()
10812     << RHS.get()->getSourceRange();
10813 }
10814 
10815 /// Return the resulting type when a vector is shifted
10816 ///        by a scalar or vector shift amount.
10817 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10818                                  SourceLocation Loc, bool IsCompAssign) {
10819   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10820   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10821       !LHS.get()->getType()->isVectorType()) {
10822     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10823       << RHS.get()->getType() << LHS.get()->getType()
10824       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10825     return QualType();
10826   }
10827 
10828   if (!IsCompAssign) {
10829     LHS = S.UsualUnaryConversions(LHS.get());
10830     if (LHS.isInvalid()) return QualType();
10831   }
10832 
10833   RHS = S.UsualUnaryConversions(RHS.get());
10834   if (RHS.isInvalid()) return QualType();
10835 
10836   QualType LHSType = LHS.get()->getType();
10837   // Note that LHS might be a scalar because the routine calls not only in
10838   // OpenCL case.
10839   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10840   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10841 
10842   // Note that RHS might not be a vector.
10843   QualType RHSType = RHS.get()->getType();
10844   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10845   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10846 
10847   // The operands need to be integers.
10848   if (!LHSEleType->isIntegerType()) {
10849     S.Diag(Loc, diag::err_typecheck_expect_int)
10850       << LHS.get()->getType() << LHS.get()->getSourceRange();
10851     return QualType();
10852   }
10853 
10854   if (!RHSEleType->isIntegerType()) {
10855     S.Diag(Loc, diag::err_typecheck_expect_int)
10856       << RHS.get()->getType() << RHS.get()->getSourceRange();
10857     return QualType();
10858   }
10859 
10860   if (!LHSVecTy) {
10861     assert(RHSVecTy);
10862     if (IsCompAssign)
10863       return RHSType;
10864     if (LHSEleType != RHSEleType) {
10865       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10866       LHSEleType = RHSEleType;
10867     }
10868     QualType VecTy =
10869         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10870     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10871     LHSType = VecTy;
10872   } else if (RHSVecTy) {
10873     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10874     // are applied component-wise. So if RHS is a vector, then ensure
10875     // that the number of elements is the same as LHS...
10876     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10877       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10878         << LHS.get()->getType() << RHS.get()->getType()
10879         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10880       return QualType();
10881     }
10882     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10883       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10884       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10885       if (LHSBT != RHSBT &&
10886           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10887         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10888             << LHS.get()->getType() << RHS.get()->getType()
10889             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10890       }
10891     }
10892   } else {
10893     // ...else expand RHS to match the number of elements in LHS.
10894     QualType VecTy =
10895       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10896     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10897   }
10898 
10899   return LHSType;
10900 }
10901 
10902 // C99 6.5.7
10903 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10904                                   SourceLocation Loc, BinaryOperatorKind Opc,
10905                                   bool IsCompAssign) {
10906   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10907 
10908   // Vector shifts promote their scalar inputs to vector type.
10909   if (LHS.get()->getType()->isVectorType() ||
10910       RHS.get()->getType()->isVectorType()) {
10911     if (LangOpts.ZVector) {
10912       // The shift operators for the z vector extensions work basically
10913       // like general shifts, except that neither the LHS nor the RHS is
10914       // allowed to be a "vector bool".
10915       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10916         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10917           return InvalidOperands(Loc, LHS, RHS);
10918       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10919         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10920           return InvalidOperands(Loc, LHS, RHS);
10921     }
10922     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10923   }
10924 
10925   // Shifts don't perform usual arithmetic conversions, they just do integer
10926   // promotions on each operand. C99 6.5.7p3
10927 
10928   // For the LHS, do usual unary conversions, but then reset them away
10929   // if this is a compound assignment.
10930   ExprResult OldLHS = LHS;
10931   LHS = UsualUnaryConversions(LHS.get());
10932   if (LHS.isInvalid())
10933     return QualType();
10934   QualType LHSType = LHS.get()->getType();
10935   if (IsCompAssign) LHS = OldLHS;
10936 
10937   // The RHS is simpler.
10938   RHS = UsualUnaryConversions(RHS.get());
10939   if (RHS.isInvalid())
10940     return QualType();
10941   QualType RHSType = RHS.get()->getType();
10942 
10943   // C99 6.5.7p2: Each of the operands shall have integer type.
10944   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10945   if ((!LHSType->isFixedPointOrIntegerType() &&
10946        !LHSType->hasIntegerRepresentation()) ||
10947       !RHSType->hasIntegerRepresentation())
10948     return InvalidOperands(Loc, LHS, RHS);
10949 
10950   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10951   // hasIntegerRepresentation() above instead of this.
10952   if (isScopedEnumerationType(LHSType) ||
10953       isScopedEnumerationType(RHSType)) {
10954     return InvalidOperands(Loc, LHS, RHS);
10955   }
10956   // Sanity-check shift operands
10957   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10958 
10959   // "The type of the result is that of the promoted left operand."
10960   return LHSType;
10961 }
10962 
10963 /// Diagnose bad pointer comparisons.
10964 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10965                                               ExprResult &LHS, ExprResult &RHS,
10966                                               bool IsError) {
10967   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10968                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10969     << LHS.get()->getType() << RHS.get()->getType()
10970     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10971 }
10972 
10973 /// Returns false if the pointers are converted to a composite type,
10974 /// true otherwise.
10975 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10976                                            ExprResult &LHS, ExprResult &RHS) {
10977   // C++ [expr.rel]p2:
10978   //   [...] Pointer conversions (4.10) and qualification
10979   //   conversions (4.4) are performed on pointer operands (or on
10980   //   a pointer operand and a null pointer constant) to bring
10981   //   them to their composite pointer type. [...]
10982   //
10983   // C++ [expr.eq]p1 uses the same notion for (in)equality
10984   // comparisons of pointers.
10985 
10986   QualType LHSType = LHS.get()->getType();
10987   QualType RHSType = RHS.get()->getType();
10988   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10989          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10990 
10991   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10992   if (T.isNull()) {
10993     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10994         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10995       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10996     else
10997       S.InvalidOperands(Loc, LHS, RHS);
10998     return true;
10999   }
11000 
11001   return false;
11002 }
11003 
11004 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11005                                                     ExprResult &LHS,
11006                                                     ExprResult &RHS,
11007                                                     bool IsError) {
11008   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11009                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11010     << LHS.get()->getType() << RHS.get()->getType()
11011     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11012 }
11013 
11014 static bool isObjCObjectLiteral(ExprResult &E) {
11015   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11016   case Stmt::ObjCArrayLiteralClass:
11017   case Stmt::ObjCDictionaryLiteralClass:
11018   case Stmt::ObjCStringLiteralClass:
11019   case Stmt::ObjCBoxedExprClass:
11020     return true;
11021   default:
11022     // Note that ObjCBoolLiteral is NOT an object literal!
11023     return false;
11024   }
11025 }
11026 
11027 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11028   const ObjCObjectPointerType *Type =
11029     LHS->getType()->getAs<ObjCObjectPointerType>();
11030 
11031   // If this is not actually an Objective-C object, bail out.
11032   if (!Type)
11033     return false;
11034 
11035   // Get the LHS object's interface type.
11036   QualType InterfaceType = Type->getPointeeType();
11037 
11038   // If the RHS isn't an Objective-C object, bail out.
11039   if (!RHS->getType()->isObjCObjectPointerType())
11040     return false;
11041 
11042   // Try to find the -isEqual: method.
11043   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11044   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11045                                                       InterfaceType,
11046                                                       /*IsInstance=*/true);
11047   if (!Method) {
11048     if (Type->isObjCIdType()) {
11049       // For 'id', just check the global pool.
11050       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11051                                                   /*receiverId=*/true);
11052     } else {
11053       // Check protocols.
11054       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11055                                              /*IsInstance=*/true);
11056     }
11057   }
11058 
11059   if (!Method)
11060     return false;
11061 
11062   QualType T = Method->parameters()[0]->getType();
11063   if (!T->isObjCObjectPointerType())
11064     return false;
11065 
11066   QualType R = Method->getReturnType();
11067   if (!R->isScalarType())
11068     return false;
11069 
11070   return true;
11071 }
11072 
11073 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11074   FromE = FromE->IgnoreParenImpCasts();
11075   switch (FromE->getStmtClass()) {
11076     default:
11077       break;
11078     case Stmt::ObjCStringLiteralClass:
11079       // "string literal"
11080       return LK_String;
11081     case Stmt::ObjCArrayLiteralClass:
11082       // "array literal"
11083       return LK_Array;
11084     case Stmt::ObjCDictionaryLiteralClass:
11085       // "dictionary literal"
11086       return LK_Dictionary;
11087     case Stmt::BlockExprClass:
11088       return LK_Block;
11089     case Stmt::ObjCBoxedExprClass: {
11090       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11091       switch (Inner->getStmtClass()) {
11092         case Stmt::IntegerLiteralClass:
11093         case Stmt::FloatingLiteralClass:
11094         case Stmt::CharacterLiteralClass:
11095         case Stmt::ObjCBoolLiteralExprClass:
11096         case Stmt::CXXBoolLiteralExprClass:
11097           // "numeric literal"
11098           return LK_Numeric;
11099         case Stmt::ImplicitCastExprClass: {
11100           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11101           // Boolean literals can be represented by implicit casts.
11102           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11103             return LK_Numeric;
11104           break;
11105         }
11106         default:
11107           break;
11108       }
11109       return LK_Boxed;
11110     }
11111   }
11112   return LK_None;
11113 }
11114 
11115 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11116                                           ExprResult &LHS, ExprResult &RHS,
11117                                           BinaryOperator::Opcode Opc){
11118   Expr *Literal;
11119   Expr *Other;
11120   if (isObjCObjectLiteral(LHS)) {
11121     Literal = LHS.get();
11122     Other = RHS.get();
11123   } else {
11124     Literal = RHS.get();
11125     Other = LHS.get();
11126   }
11127 
11128   // Don't warn on comparisons against nil.
11129   Other = Other->IgnoreParenCasts();
11130   if (Other->isNullPointerConstant(S.getASTContext(),
11131                                    Expr::NPC_ValueDependentIsNotNull))
11132     return;
11133 
11134   // This should be kept in sync with warn_objc_literal_comparison.
11135   // LK_String should always be after the other literals, since it has its own
11136   // warning flag.
11137   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11138   assert(LiteralKind != Sema::LK_Block);
11139   if (LiteralKind == Sema::LK_None) {
11140     llvm_unreachable("Unknown Objective-C object literal kind");
11141   }
11142 
11143   if (LiteralKind == Sema::LK_String)
11144     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11145       << Literal->getSourceRange();
11146   else
11147     S.Diag(Loc, diag::warn_objc_literal_comparison)
11148       << LiteralKind << Literal->getSourceRange();
11149 
11150   if (BinaryOperator::isEqualityOp(Opc) &&
11151       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11152     SourceLocation Start = LHS.get()->getBeginLoc();
11153     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11154     CharSourceRange OpRange =
11155       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11156 
11157     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11158       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11159       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11160       << FixItHint::CreateInsertion(End, "]");
11161   }
11162 }
11163 
11164 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11165 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11166                                            ExprResult &RHS, SourceLocation Loc,
11167                                            BinaryOperatorKind Opc) {
11168   // Check that left hand side is !something.
11169   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11170   if (!UO || UO->getOpcode() != UO_LNot) return;
11171 
11172   // Only check if the right hand side is non-bool arithmetic type.
11173   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11174 
11175   // Make sure that the something in !something is not bool.
11176   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11177   if (SubExpr->isKnownToHaveBooleanValue()) return;
11178 
11179   // Emit warning.
11180   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11181   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11182       << Loc << IsBitwiseOp;
11183 
11184   // First note suggest !(x < y)
11185   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11186   SourceLocation FirstClose = RHS.get()->getEndLoc();
11187   FirstClose = S.getLocForEndOfToken(FirstClose);
11188   if (FirstClose.isInvalid())
11189     FirstOpen = SourceLocation();
11190   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11191       << IsBitwiseOp
11192       << FixItHint::CreateInsertion(FirstOpen, "(")
11193       << FixItHint::CreateInsertion(FirstClose, ")");
11194 
11195   // Second note suggests (!x) < y
11196   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11197   SourceLocation SecondClose = LHS.get()->getEndLoc();
11198   SecondClose = S.getLocForEndOfToken(SecondClose);
11199   if (SecondClose.isInvalid())
11200     SecondOpen = SourceLocation();
11201   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11202       << FixItHint::CreateInsertion(SecondOpen, "(")
11203       << FixItHint::CreateInsertion(SecondClose, ")");
11204 }
11205 
11206 // Returns true if E refers to a non-weak array.
11207 static bool checkForArray(const Expr *E) {
11208   const ValueDecl *D = nullptr;
11209   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11210     D = DR->getDecl();
11211   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11212     if (Mem->isImplicitAccess())
11213       D = Mem->getMemberDecl();
11214   }
11215   if (!D)
11216     return false;
11217   return D->getType()->isArrayType() && !D->isWeak();
11218 }
11219 
11220 /// Diagnose some forms of syntactically-obvious tautological comparison.
11221 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11222                                            Expr *LHS, Expr *RHS,
11223                                            BinaryOperatorKind Opc) {
11224   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11225   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11226 
11227   QualType LHSType = LHS->getType();
11228   QualType RHSType = RHS->getType();
11229   if (LHSType->hasFloatingRepresentation() ||
11230       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11231       S.inTemplateInstantiation())
11232     return;
11233 
11234   // Comparisons between two array types are ill-formed for operator<=>, so
11235   // we shouldn't emit any additional warnings about it.
11236   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11237     return;
11238 
11239   // For non-floating point types, check for self-comparisons of the form
11240   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11241   // often indicate logic errors in the program.
11242   //
11243   // NOTE: Don't warn about comparison expressions resulting from macro
11244   // expansion. Also don't warn about comparisons which are only self
11245   // comparisons within a template instantiation. The warnings should catch
11246   // obvious cases in the definition of the template anyways. The idea is to
11247   // warn when the typed comparison operator will always evaluate to the same
11248   // result.
11249 
11250   // Used for indexing into %select in warn_comparison_always
11251   enum {
11252     AlwaysConstant,
11253     AlwaysTrue,
11254     AlwaysFalse,
11255     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11256   };
11257 
11258   // C++2a [depr.array.comp]:
11259   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11260   //   operands of array type are deprecated.
11261   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11262       RHSStripped->getType()->isArrayType()) {
11263     S.Diag(Loc, diag::warn_depr_array_comparison)
11264         << LHS->getSourceRange() << RHS->getSourceRange()
11265         << LHSStripped->getType() << RHSStripped->getType();
11266     // Carry on to produce the tautological comparison warning, if this
11267     // expression is potentially-evaluated, we can resolve the array to a
11268     // non-weak declaration, and so on.
11269   }
11270 
11271   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11272     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11273       unsigned Result;
11274       switch (Opc) {
11275       case BO_EQ:
11276       case BO_LE:
11277       case BO_GE:
11278         Result = AlwaysTrue;
11279         break;
11280       case BO_NE:
11281       case BO_LT:
11282       case BO_GT:
11283         Result = AlwaysFalse;
11284         break;
11285       case BO_Cmp:
11286         Result = AlwaysEqual;
11287         break;
11288       default:
11289         Result = AlwaysConstant;
11290         break;
11291       }
11292       S.DiagRuntimeBehavior(Loc, nullptr,
11293                             S.PDiag(diag::warn_comparison_always)
11294                                 << 0 /*self-comparison*/
11295                                 << Result);
11296     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11297       // What is it always going to evaluate to?
11298       unsigned Result;
11299       switch (Opc) {
11300       case BO_EQ: // e.g. array1 == array2
11301         Result = AlwaysFalse;
11302         break;
11303       case BO_NE: // e.g. array1 != array2
11304         Result = AlwaysTrue;
11305         break;
11306       default: // e.g. array1 <= array2
11307         // The best we can say is 'a constant'
11308         Result = AlwaysConstant;
11309         break;
11310       }
11311       S.DiagRuntimeBehavior(Loc, nullptr,
11312                             S.PDiag(diag::warn_comparison_always)
11313                                 << 1 /*array comparison*/
11314                                 << Result);
11315     }
11316   }
11317 
11318   if (isa<CastExpr>(LHSStripped))
11319     LHSStripped = LHSStripped->IgnoreParenCasts();
11320   if (isa<CastExpr>(RHSStripped))
11321     RHSStripped = RHSStripped->IgnoreParenCasts();
11322 
11323   // Warn about comparisons against a string constant (unless the other
11324   // operand is null); the user probably wants string comparison function.
11325   Expr *LiteralString = nullptr;
11326   Expr *LiteralStringStripped = nullptr;
11327   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11328       !RHSStripped->isNullPointerConstant(S.Context,
11329                                           Expr::NPC_ValueDependentIsNull)) {
11330     LiteralString = LHS;
11331     LiteralStringStripped = LHSStripped;
11332   } else if ((isa<StringLiteral>(RHSStripped) ||
11333               isa<ObjCEncodeExpr>(RHSStripped)) &&
11334              !LHSStripped->isNullPointerConstant(S.Context,
11335                                           Expr::NPC_ValueDependentIsNull)) {
11336     LiteralString = RHS;
11337     LiteralStringStripped = RHSStripped;
11338   }
11339 
11340   if (LiteralString) {
11341     S.DiagRuntimeBehavior(Loc, nullptr,
11342                           S.PDiag(diag::warn_stringcompare)
11343                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11344                               << LiteralString->getSourceRange());
11345   }
11346 }
11347 
11348 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11349   switch (CK) {
11350   default: {
11351 #ifndef NDEBUG
11352     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11353                  << "\n";
11354 #endif
11355     llvm_unreachable("unhandled cast kind");
11356   }
11357   case CK_UserDefinedConversion:
11358     return ICK_Identity;
11359   case CK_LValueToRValue:
11360     return ICK_Lvalue_To_Rvalue;
11361   case CK_ArrayToPointerDecay:
11362     return ICK_Array_To_Pointer;
11363   case CK_FunctionToPointerDecay:
11364     return ICK_Function_To_Pointer;
11365   case CK_IntegralCast:
11366     return ICK_Integral_Conversion;
11367   case CK_FloatingCast:
11368     return ICK_Floating_Conversion;
11369   case CK_IntegralToFloating:
11370   case CK_FloatingToIntegral:
11371     return ICK_Floating_Integral;
11372   case CK_IntegralComplexCast:
11373   case CK_FloatingComplexCast:
11374   case CK_FloatingComplexToIntegralComplex:
11375   case CK_IntegralComplexToFloatingComplex:
11376     return ICK_Complex_Conversion;
11377   case CK_FloatingComplexToReal:
11378   case CK_FloatingRealToComplex:
11379   case CK_IntegralComplexToReal:
11380   case CK_IntegralRealToComplex:
11381     return ICK_Complex_Real;
11382   }
11383 }
11384 
11385 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11386                                              QualType FromType,
11387                                              SourceLocation Loc) {
11388   // Check for a narrowing implicit conversion.
11389   StandardConversionSequence SCS;
11390   SCS.setAsIdentityConversion();
11391   SCS.setToType(0, FromType);
11392   SCS.setToType(1, ToType);
11393   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11394     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11395 
11396   APValue PreNarrowingValue;
11397   QualType PreNarrowingType;
11398   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11399                                PreNarrowingType,
11400                                /*IgnoreFloatToIntegralConversion*/ true)) {
11401   case NK_Dependent_Narrowing:
11402     // Implicit conversion to a narrower type, but the expression is
11403     // value-dependent so we can't tell whether it's actually narrowing.
11404   case NK_Not_Narrowing:
11405     return false;
11406 
11407   case NK_Constant_Narrowing:
11408     // Implicit conversion to a narrower type, and the value is not a constant
11409     // expression.
11410     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11411         << /*Constant*/ 1
11412         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11413     return true;
11414 
11415   case NK_Variable_Narrowing:
11416     // Implicit conversion to a narrower type, and the value is not a constant
11417     // expression.
11418   case NK_Type_Narrowing:
11419     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11420         << /*Constant*/ 0 << FromType << ToType;
11421     // TODO: It's not a constant expression, but what if the user intended it
11422     // to be? Can we produce notes to help them figure out why it isn't?
11423     return true;
11424   }
11425   llvm_unreachable("unhandled case in switch");
11426 }
11427 
11428 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11429                                                          ExprResult &LHS,
11430                                                          ExprResult &RHS,
11431                                                          SourceLocation Loc) {
11432   QualType LHSType = LHS.get()->getType();
11433   QualType RHSType = RHS.get()->getType();
11434   // Dig out the original argument type and expression before implicit casts
11435   // were applied. These are the types/expressions we need to check the
11436   // [expr.spaceship] requirements against.
11437   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11438   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11439   QualType LHSStrippedType = LHSStripped.get()->getType();
11440   QualType RHSStrippedType = RHSStripped.get()->getType();
11441 
11442   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11443   // other is not, the program is ill-formed.
11444   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11445     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11446     return QualType();
11447   }
11448 
11449   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11450   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11451                     RHSStrippedType->isEnumeralType();
11452   if (NumEnumArgs == 1) {
11453     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11454     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11455     if (OtherTy->hasFloatingRepresentation()) {
11456       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11457       return QualType();
11458     }
11459   }
11460   if (NumEnumArgs == 2) {
11461     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11462     // type E, the operator yields the result of converting the operands
11463     // to the underlying type of E and applying <=> to the converted operands.
11464     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11465       S.InvalidOperands(Loc, LHS, RHS);
11466       return QualType();
11467     }
11468     QualType IntType =
11469         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11470     assert(IntType->isArithmeticType());
11471 
11472     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11473     // promote the boolean type, and all other promotable integer types, to
11474     // avoid this.
11475     if (IntType->isPromotableIntegerType())
11476       IntType = S.Context.getPromotedIntegerType(IntType);
11477 
11478     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11479     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11480     LHSType = RHSType = IntType;
11481   }
11482 
11483   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11484   // usual arithmetic conversions are applied to the operands.
11485   QualType Type =
11486       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11487   if (LHS.isInvalid() || RHS.isInvalid())
11488     return QualType();
11489   if (Type.isNull())
11490     return S.InvalidOperands(Loc, LHS, RHS);
11491 
11492   Optional<ComparisonCategoryType> CCT =
11493       getComparisonCategoryForBuiltinCmp(Type);
11494   if (!CCT)
11495     return S.InvalidOperands(Loc, LHS, RHS);
11496 
11497   bool HasNarrowing = checkThreeWayNarrowingConversion(
11498       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11499   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11500                                                    RHS.get()->getBeginLoc());
11501   if (HasNarrowing)
11502     return QualType();
11503 
11504   assert(!Type.isNull() && "composite type for <=> has not been set");
11505 
11506   return S.CheckComparisonCategoryType(
11507       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11508 }
11509 
11510 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11511                                                  ExprResult &RHS,
11512                                                  SourceLocation Loc,
11513                                                  BinaryOperatorKind Opc) {
11514   if (Opc == BO_Cmp)
11515     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11516 
11517   // C99 6.5.8p3 / C99 6.5.9p4
11518   QualType Type =
11519       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11520   if (LHS.isInvalid() || RHS.isInvalid())
11521     return QualType();
11522   if (Type.isNull())
11523     return S.InvalidOperands(Loc, LHS, RHS);
11524   assert(Type->isArithmeticType() || Type->isEnumeralType());
11525 
11526   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11527     return S.InvalidOperands(Loc, LHS, RHS);
11528 
11529   // Check for comparisons of floating point operands using != and ==.
11530   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11531     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11532 
11533   // The result of comparisons is 'bool' in C++, 'int' in C.
11534   return S.Context.getLogicalOperationType();
11535 }
11536 
11537 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11538   if (!NullE.get()->getType()->isAnyPointerType())
11539     return;
11540   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11541   if (!E.get()->getType()->isAnyPointerType() &&
11542       E.get()->isNullPointerConstant(Context,
11543                                      Expr::NPC_ValueDependentIsNotNull) ==
11544         Expr::NPCK_ZeroExpression) {
11545     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11546       if (CL->getValue() == 0)
11547         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11548             << NullValue
11549             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11550                                             NullValue ? "NULL" : "(void *)0");
11551     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11552         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11553         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11554         if (T == Context.CharTy)
11555           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11556               << NullValue
11557               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11558                                               NullValue ? "NULL" : "(void *)0");
11559       }
11560   }
11561 }
11562 
11563 // C99 6.5.8, C++ [expr.rel]
11564 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11565                                     SourceLocation Loc,
11566                                     BinaryOperatorKind Opc) {
11567   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11568   bool IsThreeWay = Opc == BO_Cmp;
11569   bool IsOrdered = IsRelational || IsThreeWay;
11570   auto IsAnyPointerType = [](ExprResult E) {
11571     QualType Ty = E.get()->getType();
11572     return Ty->isPointerType() || Ty->isMemberPointerType();
11573   };
11574 
11575   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11576   // type, array-to-pointer, ..., conversions are performed on both operands to
11577   // bring them to their composite type.
11578   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11579   // any type-related checks.
11580   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11581     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11582     if (LHS.isInvalid())
11583       return QualType();
11584     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11585     if (RHS.isInvalid())
11586       return QualType();
11587   } else {
11588     LHS = DefaultLvalueConversion(LHS.get());
11589     if (LHS.isInvalid())
11590       return QualType();
11591     RHS = DefaultLvalueConversion(RHS.get());
11592     if (RHS.isInvalid())
11593       return QualType();
11594   }
11595 
11596   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11597   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11598     CheckPtrComparisonWithNullChar(LHS, RHS);
11599     CheckPtrComparisonWithNullChar(RHS, LHS);
11600   }
11601 
11602   // Handle vector comparisons separately.
11603   if (LHS.get()->getType()->isVectorType() ||
11604       RHS.get()->getType()->isVectorType())
11605     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11606 
11607   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11608   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11609 
11610   QualType LHSType = LHS.get()->getType();
11611   QualType RHSType = RHS.get()->getType();
11612   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11613       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11614     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11615 
11616   const Expr::NullPointerConstantKind LHSNullKind =
11617       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11618   const Expr::NullPointerConstantKind RHSNullKind =
11619       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11620   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11621   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11622 
11623   auto computeResultTy = [&]() {
11624     if (Opc != BO_Cmp)
11625       return Context.getLogicalOperationType();
11626     assert(getLangOpts().CPlusPlus);
11627     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11628 
11629     QualType CompositeTy = LHS.get()->getType();
11630     assert(!CompositeTy->isReferenceType());
11631 
11632     Optional<ComparisonCategoryType> CCT =
11633         getComparisonCategoryForBuiltinCmp(CompositeTy);
11634     if (!CCT)
11635       return InvalidOperands(Loc, LHS, RHS);
11636 
11637     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11638       // P0946R0: Comparisons between a null pointer constant and an object
11639       // pointer result in std::strong_equality, which is ill-formed under
11640       // P1959R0.
11641       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11642           << (LHSIsNull ? LHS.get()->getSourceRange()
11643                         : RHS.get()->getSourceRange());
11644       return QualType();
11645     }
11646 
11647     return CheckComparisonCategoryType(
11648         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11649   };
11650 
11651   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11652     bool IsEquality = Opc == BO_EQ;
11653     if (RHSIsNull)
11654       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11655                                    RHS.get()->getSourceRange());
11656     else
11657       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11658                                    LHS.get()->getSourceRange());
11659   }
11660 
11661   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11662       (RHSType->isIntegerType() && !RHSIsNull)) {
11663     // Skip normal pointer conversion checks in this case; we have better
11664     // diagnostics for this below.
11665   } else if (getLangOpts().CPlusPlus) {
11666     // Equality comparison of a function pointer to a void pointer is invalid,
11667     // but we allow it as an extension.
11668     // FIXME: If we really want to allow this, should it be part of composite
11669     // pointer type computation so it works in conditionals too?
11670     if (!IsOrdered &&
11671         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11672          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11673       // This is a gcc extension compatibility comparison.
11674       // In a SFINAE context, we treat this as a hard error to maintain
11675       // conformance with the C++ standard.
11676       diagnoseFunctionPointerToVoidComparison(
11677           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11678 
11679       if (isSFINAEContext())
11680         return QualType();
11681 
11682       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11683       return computeResultTy();
11684     }
11685 
11686     // C++ [expr.eq]p2:
11687     //   If at least one operand is a pointer [...] bring them to their
11688     //   composite pointer type.
11689     // C++ [expr.spaceship]p6
11690     //  If at least one of the operands is of pointer type, [...] bring them
11691     //  to their composite pointer type.
11692     // C++ [expr.rel]p2:
11693     //   If both operands are pointers, [...] bring them to their composite
11694     //   pointer type.
11695     // For <=>, the only valid non-pointer types are arrays and functions, and
11696     // we already decayed those, so this is really the same as the relational
11697     // comparison rule.
11698     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11699             (IsOrdered ? 2 : 1) &&
11700         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11701                                          RHSType->isObjCObjectPointerType()))) {
11702       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11703         return QualType();
11704       return computeResultTy();
11705     }
11706   } else if (LHSType->isPointerType() &&
11707              RHSType->isPointerType()) { // C99 6.5.8p2
11708     // All of the following pointer-related warnings are GCC extensions, except
11709     // when handling null pointer constants.
11710     QualType LCanPointeeTy =
11711       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11712     QualType RCanPointeeTy =
11713       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11714 
11715     // C99 6.5.9p2 and C99 6.5.8p2
11716     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11717                                    RCanPointeeTy.getUnqualifiedType())) {
11718       if (IsRelational) {
11719         // Pointers both need to point to complete or incomplete types
11720         if ((LCanPointeeTy->isIncompleteType() !=
11721              RCanPointeeTy->isIncompleteType()) &&
11722             !getLangOpts().C11) {
11723           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11724               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11725               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11726               << RCanPointeeTy->isIncompleteType();
11727         }
11728         if (LCanPointeeTy->isFunctionType()) {
11729           // Valid unless a relational comparison of function pointers
11730           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11731               << LHSType << RHSType << LHS.get()->getSourceRange()
11732               << RHS.get()->getSourceRange();
11733         }
11734       }
11735     } else if (!IsRelational &&
11736                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11737       // Valid unless comparison between non-null pointer and function pointer
11738       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11739           && !LHSIsNull && !RHSIsNull)
11740         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11741                                                 /*isError*/false);
11742     } else {
11743       // Invalid
11744       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11745     }
11746     if (LCanPointeeTy != RCanPointeeTy) {
11747       // Treat NULL constant as a special case in OpenCL.
11748       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11749         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11750           Diag(Loc,
11751                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11752               << LHSType << RHSType << 0 /* comparison */
11753               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11754         }
11755       }
11756       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11757       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11758       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11759                                                : CK_BitCast;
11760       if (LHSIsNull && !RHSIsNull)
11761         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11762       else
11763         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11764     }
11765     return computeResultTy();
11766   }
11767 
11768   if (getLangOpts().CPlusPlus) {
11769     // C++ [expr.eq]p4:
11770     //   Two operands of type std::nullptr_t or one operand of type
11771     //   std::nullptr_t and the other a null pointer constant compare equal.
11772     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11773       if (LHSType->isNullPtrType()) {
11774         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11775         return computeResultTy();
11776       }
11777       if (RHSType->isNullPtrType()) {
11778         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11779         return computeResultTy();
11780       }
11781     }
11782 
11783     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11784     // These aren't covered by the composite pointer type rules.
11785     if (!IsOrdered && RHSType->isNullPtrType() &&
11786         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11787       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11788       return computeResultTy();
11789     }
11790     if (!IsOrdered && LHSType->isNullPtrType() &&
11791         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11792       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11793       return computeResultTy();
11794     }
11795 
11796     if (IsRelational &&
11797         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11798          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11799       // HACK: Relational comparison of nullptr_t against a pointer type is
11800       // invalid per DR583, but we allow it within std::less<> and friends,
11801       // since otherwise common uses of it break.
11802       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11803       // friends to have std::nullptr_t overload candidates.
11804       DeclContext *DC = CurContext;
11805       if (isa<FunctionDecl>(DC))
11806         DC = DC->getParent();
11807       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11808         if (CTSD->isInStdNamespace() &&
11809             llvm::StringSwitch<bool>(CTSD->getName())
11810                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11811                 .Default(false)) {
11812           if (RHSType->isNullPtrType())
11813             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11814           else
11815             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11816           return computeResultTy();
11817         }
11818       }
11819     }
11820 
11821     // C++ [expr.eq]p2:
11822     //   If at least one operand is a pointer to member, [...] bring them to
11823     //   their composite pointer type.
11824     if (!IsOrdered &&
11825         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11826       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11827         return QualType();
11828       else
11829         return computeResultTy();
11830     }
11831   }
11832 
11833   // Handle block pointer types.
11834   if (!IsOrdered && LHSType->isBlockPointerType() &&
11835       RHSType->isBlockPointerType()) {
11836     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11837     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11838 
11839     if (!LHSIsNull && !RHSIsNull &&
11840         !Context.typesAreCompatible(lpointee, rpointee)) {
11841       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11842         << LHSType << RHSType << LHS.get()->getSourceRange()
11843         << RHS.get()->getSourceRange();
11844     }
11845     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11846     return computeResultTy();
11847   }
11848 
11849   // Allow block pointers to be compared with null pointer constants.
11850   if (!IsOrdered
11851       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11852           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11853     if (!LHSIsNull && !RHSIsNull) {
11854       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11855              ->getPointeeType()->isVoidType())
11856             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11857                 ->getPointeeType()->isVoidType())))
11858         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11859           << LHSType << RHSType << LHS.get()->getSourceRange()
11860           << RHS.get()->getSourceRange();
11861     }
11862     if (LHSIsNull && !RHSIsNull)
11863       LHS = ImpCastExprToType(LHS.get(), RHSType,
11864                               RHSType->isPointerType() ? CK_BitCast
11865                                 : CK_AnyPointerToBlockPointerCast);
11866     else
11867       RHS = ImpCastExprToType(RHS.get(), LHSType,
11868                               LHSType->isPointerType() ? CK_BitCast
11869                                 : CK_AnyPointerToBlockPointerCast);
11870     return computeResultTy();
11871   }
11872 
11873   if (LHSType->isObjCObjectPointerType() ||
11874       RHSType->isObjCObjectPointerType()) {
11875     const PointerType *LPT = LHSType->getAs<PointerType>();
11876     const PointerType *RPT = RHSType->getAs<PointerType>();
11877     if (LPT || RPT) {
11878       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11879       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11880 
11881       if (!LPtrToVoid && !RPtrToVoid &&
11882           !Context.typesAreCompatible(LHSType, RHSType)) {
11883         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11884                                           /*isError*/false);
11885       }
11886       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11887       // the RHS, but we have test coverage for this behavior.
11888       // FIXME: Consider using convertPointersToCompositeType in C++.
11889       if (LHSIsNull && !RHSIsNull) {
11890         Expr *E = LHS.get();
11891         if (getLangOpts().ObjCAutoRefCount)
11892           CheckObjCConversion(SourceRange(), RHSType, E,
11893                               CCK_ImplicitConversion);
11894         LHS = ImpCastExprToType(E, RHSType,
11895                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11896       }
11897       else {
11898         Expr *E = RHS.get();
11899         if (getLangOpts().ObjCAutoRefCount)
11900           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11901                               /*Diagnose=*/true,
11902                               /*DiagnoseCFAudited=*/false, Opc);
11903         RHS = ImpCastExprToType(E, LHSType,
11904                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11905       }
11906       return computeResultTy();
11907     }
11908     if (LHSType->isObjCObjectPointerType() &&
11909         RHSType->isObjCObjectPointerType()) {
11910       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11911         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11912                                           /*isError*/false);
11913       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11914         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11915 
11916       if (LHSIsNull && !RHSIsNull)
11917         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11918       else
11919         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11920       return computeResultTy();
11921     }
11922 
11923     if (!IsOrdered && LHSType->isBlockPointerType() &&
11924         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11925       LHS = ImpCastExprToType(LHS.get(), RHSType,
11926                               CK_BlockPointerToObjCPointerCast);
11927       return computeResultTy();
11928     } else if (!IsOrdered &&
11929                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11930                RHSType->isBlockPointerType()) {
11931       RHS = ImpCastExprToType(RHS.get(), LHSType,
11932                               CK_BlockPointerToObjCPointerCast);
11933       return computeResultTy();
11934     }
11935   }
11936   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11937       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11938     unsigned DiagID = 0;
11939     bool isError = false;
11940     if (LangOpts.DebuggerSupport) {
11941       // Under a debugger, allow the comparison of pointers to integers,
11942       // since users tend to want to compare addresses.
11943     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11944                (RHSIsNull && RHSType->isIntegerType())) {
11945       if (IsOrdered) {
11946         isError = getLangOpts().CPlusPlus;
11947         DiagID =
11948           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11949                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11950       }
11951     } else if (getLangOpts().CPlusPlus) {
11952       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11953       isError = true;
11954     } else if (IsOrdered)
11955       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11956     else
11957       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11958 
11959     if (DiagID) {
11960       Diag(Loc, DiagID)
11961         << LHSType << RHSType << LHS.get()->getSourceRange()
11962         << RHS.get()->getSourceRange();
11963       if (isError)
11964         return QualType();
11965     }
11966 
11967     if (LHSType->isIntegerType())
11968       LHS = ImpCastExprToType(LHS.get(), RHSType,
11969                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11970     else
11971       RHS = ImpCastExprToType(RHS.get(), LHSType,
11972                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11973     return computeResultTy();
11974   }
11975 
11976   // Handle block pointers.
11977   if (!IsOrdered && RHSIsNull
11978       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11979     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11980     return computeResultTy();
11981   }
11982   if (!IsOrdered && LHSIsNull
11983       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11984     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11985     return computeResultTy();
11986   }
11987 
11988   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11989     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11990       return computeResultTy();
11991     }
11992 
11993     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11994       return computeResultTy();
11995     }
11996 
11997     if (LHSIsNull && RHSType->isQueueT()) {
11998       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11999       return computeResultTy();
12000     }
12001 
12002     if (LHSType->isQueueT() && RHSIsNull) {
12003       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12004       return computeResultTy();
12005     }
12006   }
12007 
12008   return InvalidOperands(Loc, LHS, RHS);
12009 }
12010 
12011 // Return a signed ext_vector_type that is of identical size and number of
12012 // elements. For floating point vectors, return an integer type of identical
12013 // size and number of elements. In the non ext_vector_type case, search from
12014 // the largest type to the smallest type to avoid cases where long long == long,
12015 // where long gets picked over long long.
12016 QualType Sema::GetSignedVectorType(QualType V) {
12017   const VectorType *VTy = V->castAs<VectorType>();
12018   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12019 
12020   if (isa<ExtVectorType>(VTy)) {
12021     if (TypeSize == Context.getTypeSize(Context.CharTy))
12022       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12023     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12024       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12025     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12026       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12027     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12028       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12029     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12030            "Unhandled vector element size in vector compare");
12031     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12032   }
12033 
12034   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12035     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12036                                  VectorType::GenericVector);
12037   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12038     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12039                                  VectorType::GenericVector);
12040   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12041     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12042                                  VectorType::GenericVector);
12043   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12044     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12045                                  VectorType::GenericVector);
12046   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12047          "Unhandled vector element size in vector compare");
12048   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12049                                VectorType::GenericVector);
12050 }
12051 
12052 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12053 /// operates on extended vector types.  Instead of producing an IntTy result,
12054 /// like a scalar comparison, a vector comparison produces a vector of integer
12055 /// types.
12056 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12057                                           SourceLocation Loc,
12058                                           BinaryOperatorKind Opc) {
12059   if (Opc == BO_Cmp) {
12060     Diag(Loc, diag::err_three_way_vector_comparison);
12061     return QualType();
12062   }
12063 
12064   // Check to make sure we're operating on vectors of the same type and width,
12065   // Allowing one side to be a scalar of element type.
12066   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12067                               /*AllowBothBool*/true,
12068                               /*AllowBoolConversions*/getLangOpts().ZVector);
12069   if (vType.isNull())
12070     return vType;
12071 
12072   QualType LHSType = LHS.get()->getType();
12073 
12074   // If AltiVec, the comparison results in a numeric type, i.e.
12075   // bool for C++, int for C
12076   if (getLangOpts().AltiVec &&
12077       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12078     return Context.getLogicalOperationType();
12079 
12080   // For non-floating point types, check for self-comparisons of the form
12081   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12082   // often indicate logic errors in the program.
12083   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12084 
12085   // Check for comparisons of floating point operands using != and ==.
12086   if (BinaryOperator::isEqualityOp(Opc) &&
12087       LHSType->hasFloatingRepresentation()) {
12088     assert(RHS.get()->getType()->hasFloatingRepresentation());
12089     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12090   }
12091 
12092   // Return a signed type for the vector.
12093   return GetSignedVectorType(vType);
12094 }
12095 
12096 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12097                                     const ExprResult &XorRHS,
12098                                     const SourceLocation Loc) {
12099   // Do not diagnose macros.
12100   if (Loc.isMacroID())
12101     return;
12102 
12103   bool Negative = false;
12104   bool ExplicitPlus = false;
12105   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12106   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12107 
12108   if (!LHSInt)
12109     return;
12110   if (!RHSInt) {
12111     // Check negative literals.
12112     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12113       UnaryOperatorKind Opc = UO->getOpcode();
12114       if (Opc != UO_Minus && Opc != UO_Plus)
12115         return;
12116       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12117       if (!RHSInt)
12118         return;
12119       Negative = (Opc == UO_Minus);
12120       ExplicitPlus = !Negative;
12121     } else {
12122       return;
12123     }
12124   }
12125 
12126   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12127   llvm::APInt RightSideValue = RHSInt->getValue();
12128   if (LeftSideValue != 2 && LeftSideValue != 10)
12129     return;
12130 
12131   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12132     return;
12133 
12134   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12135       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12136   llvm::StringRef ExprStr =
12137       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12138 
12139   CharSourceRange XorRange =
12140       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12141   llvm::StringRef XorStr =
12142       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12143   // Do not diagnose if xor keyword/macro is used.
12144   if (XorStr == "xor")
12145     return;
12146 
12147   std::string LHSStr = std::string(Lexer::getSourceText(
12148       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12149       S.getSourceManager(), S.getLangOpts()));
12150   std::string RHSStr = std::string(Lexer::getSourceText(
12151       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12152       S.getSourceManager(), S.getLangOpts()));
12153 
12154   if (Negative) {
12155     RightSideValue = -RightSideValue;
12156     RHSStr = "-" + RHSStr;
12157   } else if (ExplicitPlus) {
12158     RHSStr = "+" + RHSStr;
12159   }
12160 
12161   StringRef LHSStrRef = LHSStr;
12162   StringRef RHSStrRef = RHSStr;
12163   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12164   // literals.
12165   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12166       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12167       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12168       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12169       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12170       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12171       LHSStrRef.find('\'') != StringRef::npos ||
12172       RHSStrRef.find('\'') != StringRef::npos)
12173     return;
12174 
12175   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12176   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12177   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12178   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12179     std::string SuggestedExpr = "1 << " + RHSStr;
12180     bool Overflow = false;
12181     llvm::APInt One = (LeftSideValue - 1);
12182     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12183     if (Overflow) {
12184       if (RightSideIntValue < 64)
12185         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12186             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12187             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12188       else if (RightSideIntValue == 64)
12189         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12190       else
12191         return;
12192     } else {
12193       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12194           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12195           << PowValue.toString(10, true)
12196           << FixItHint::CreateReplacement(
12197                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12198     }
12199 
12200     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12201   } else if (LeftSideValue == 10) {
12202     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12203     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12204         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12205         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12206     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12207   }
12208 }
12209 
12210 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12211                                           SourceLocation Loc) {
12212   // Ensure that either both operands are of the same vector type, or
12213   // one operand is of a vector type and the other is of its element type.
12214   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12215                                        /*AllowBothBool*/true,
12216                                        /*AllowBoolConversions*/false);
12217   if (vType.isNull())
12218     return InvalidOperands(Loc, LHS, RHS);
12219   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12220       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12221     return InvalidOperands(Loc, LHS, RHS);
12222   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12223   //        usage of the logical operators && and || with vectors in C. This
12224   //        check could be notionally dropped.
12225   if (!getLangOpts().CPlusPlus &&
12226       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12227     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12228 
12229   return GetSignedVectorType(LHS.get()->getType());
12230 }
12231 
12232 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12233                                               SourceLocation Loc,
12234                                               bool IsCompAssign) {
12235   if (!IsCompAssign) {
12236     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12237     if (LHS.isInvalid())
12238       return QualType();
12239   }
12240   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12241   if (RHS.isInvalid())
12242     return QualType();
12243 
12244   // For conversion purposes, we ignore any qualifiers.
12245   // For example, "const float" and "float" are equivalent.
12246   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12247   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12248 
12249   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12250   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12251   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12252 
12253   if (Context.hasSameType(LHSType, RHSType))
12254     return LHSType;
12255 
12256   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12257   // case we have to return InvalidOperands.
12258   ExprResult OriginalLHS = LHS;
12259   ExprResult OriginalRHS = RHS;
12260   if (LHSMatType && !RHSMatType) {
12261     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12262     if (!RHS.isInvalid())
12263       return LHSType;
12264 
12265     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12266   }
12267 
12268   if (!LHSMatType && RHSMatType) {
12269     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12270     if (!LHS.isInvalid())
12271       return RHSType;
12272     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12273   }
12274 
12275   return InvalidOperands(Loc, LHS, RHS);
12276 }
12277 
12278 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12279                                            SourceLocation Loc,
12280                                            bool IsCompAssign) {
12281   if (!IsCompAssign) {
12282     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12283     if (LHS.isInvalid())
12284       return QualType();
12285   }
12286   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12287   if (RHS.isInvalid())
12288     return QualType();
12289 
12290   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12291   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12292   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12293 
12294   if (LHSMatType && RHSMatType) {
12295     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12296       return InvalidOperands(Loc, LHS, RHS);
12297 
12298     if (!Context.hasSameType(LHSMatType->getElementType(),
12299                              RHSMatType->getElementType()))
12300       return InvalidOperands(Loc, LHS, RHS);
12301 
12302     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12303                                          LHSMatType->getNumRows(),
12304                                          RHSMatType->getNumColumns());
12305   }
12306   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12307 }
12308 
12309 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12310                                            SourceLocation Loc,
12311                                            BinaryOperatorKind Opc) {
12312   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12313 
12314   bool IsCompAssign =
12315       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12316 
12317   if (LHS.get()->getType()->isVectorType() ||
12318       RHS.get()->getType()->isVectorType()) {
12319     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12320         RHS.get()->getType()->hasIntegerRepresentation())
12321       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12322                         /*AllowBothBool*/true,
12323                         /*AllowBoolConversions*/getLangOpts().ZVector);
12324     return InvalidOperands(Loc, LHS, RHS);
12325   }
12326 
12327   if (Opc == BO_And)
12328     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12329 
12330   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12331       RHS.get()->getType()->hasFloatingRepresentation())
12332     return InvalidOperands(Loc, LHS, RHS);
12333 
12334   ExprResult LHSResult = LHS, RHSResult = RHS;
12335   QualType compType = UsualArithmeticConversions(
12336       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12337   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12338     return QualType();
12339   LHS = LHSResult.get();
12340   RHS = RHSResult.get();
12341 
12342   if (Opc == BO_Xor)
12343     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12344 
12345   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12346     return compType;
12347   return InvalidOperands(Loc, LHS, RHS);
12348 }
12349 
12350 // C99 6.5.[13,14]
12351 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12352                                            SourceLocation Loc,
12353                                            BinaryOperatorKind Opc) {
12354   // Check vector operands differently.
12355   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12356     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12357 
12358   bool EnumConstantInBoolContext = false;
12359   for (const ExprResult &HS : {LHS, RHS}) {
12360     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12361       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12362       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12363         EnumConstantInBoolContext = true;
12364     }
12365   }
12366 
12367   if (EnumConstantInBoolContext)
12368     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12369 
12370   // Diagnose cases where the user write a logical and/or but probably meant a
12371   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12372   // is a constant.
12373   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12374       !LHS.get()->getType()->isBooleanType() &&
12375       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12376       // Don't warn in macros or template instantiations.
12377       !Loc.isMacroID() && !inTemplateInstantiation()) {
12378     // If the RHS can be constant folded, and if it constant folds to something
12379     // that isn't 0 or 1 (which indicate a potential logical operation that
12380     // happened to fold to true/false) then warn.
12381     // Parens on the RHS are ignored.
12382     Expr::EvalResult EVResult;
12383     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12384       llvm::APSInt Result = EVResult.Val.getInt();
12385       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12386            !RHS.get()->getExprLoc().isMacroID()) ||
12387           (Result != 0 && Result != 1)) {
12388         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12389           << RHS.get()->getSourceRange()
12390           << (Opc == BO_LAnd ? "&&" : "||");
12391         // Suggest replacing the logical operator with the bitwise version
12392         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12393             << (Opc == BO_LAnd ? "&" : "|")
12394             << FixItHint::CreateReplacement(SourceRange(
12395                                                  Loc, getLocForEndOfToken(Loc)),
12396                                             Opc == BO_LAnd ? "&" : "|");
12397         if (Opc == BO_LAnd)
12398           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12399           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12400               << FixItHint::CreateRemoval(
12401                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12402                                  RHS.get()->getEndLoc()));
12403       }
12404     }
12405   }
12406 
12407   if (!Context.getLangOpts().CPlusPlus) {
12408     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12409     // not operate on the built-in scalar and vector float types.
12410     if (Context.getLangOpts().OpenCL &&
12411         Context.getLangOpts().OpenCLVersion < 120) {
12412       if (LHS.get()->getType()->isFloatingType() ||
12413           RHS.get()->getType()->isFloatingType())
12414         return InvalidOperands(Loc, LHS, RHS);
12415     }
12416 
12417     LHS = UsualUnaryConversions(LHS.get());
12418     if (LHS.isInvalid())
12419       return QualType();
12420 
12421     RHS = UsualUnaryConversions(RHS.get());
12422     if (RHS.isInvalid())
12423       return QualType();
12424 
12425     if (!LHS.get()->getType()->isScalarType() ||
12426         !RHS.get()->getType()->isScalarType())
12427       return InvalidOperands(Loc, LHS, RHS);
12428 
12429     return Context.IntTy;
12430   }
12431 
12432   // The following is safe because we only use this method for
12433   // non-overloadable operands.
12434 
12435   // C++ [expr.log.and]p1
12436   // C++ [expr.log.or]p1
12437   // The operands are both contextually converted to type bool.
12438   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12439   if (LHSRes.isInvalid())
12440     return InvalidOperands(Loc, LHS, RHS);
12441   LHS = LHSRes;
12442 
12443   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12444   if (RHSRes.isInvalid())
12445     return InvalidOperands(Loc, LHS, RHS);
12446   RHS = RHSRes;
12447 
12448   // C++ [expr.log.and]p2
12449   // C++ [expr.log.or]p2
12450   // The result is a bool.
12451   return Context.BoolTy;
12452 }
12453 
12454 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12455   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12456   if (!ME) return false;
12457   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12458   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12459       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12460   if (!Base) return false;
12461   return Base->getMethodDecl() != nullptr;
12462 }
12463 
12464 /// Is the given expression (which must be 'const') a reference to a
12465 /// variable which was originally non-const, but which has become
12466 /// 'const' due to being captured within a block?
12467 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12468 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12469   assert(E->isLValue() && E->getType().isConstQualified());
12470   E = E->IgnoreParens();
12471 
12472   // Must be a reference to a declaration from an enclosing scope.
12473   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12474   if (!DRE) return NCCK_None;
12475   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12476 
12477   // The declaration must be a variable which is not declared 'const'.
12478   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12479   if (!var) return NCCK_None;
12480   if (var->getType().isConstQualified()) return NCCK_None;
12481   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12482 
12483   // Decide whether the first capture was for a block or a lambda.
12484   DeclContext *DC = S.CurContext, *Prev = nullptr;
12485   // Decide whether the first capture was for a block or a lambda.
12486   while (DC) {
12487     // For init-capture, it is possible that the variable belongs to the
12488     // template pattern of the current context.
12489     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12490       if (var->isInitCapture() &&
12491           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12492         break;
12493     if (DC == var->getDeclContext())
12494       break;
12495     Prev = DC;
12496     DC = DC->getParent();
12497   }
12498   // Unless we have an init-capture, we've gone one step too far.
12499   if (!var->isInitCapture())
12500     DC = Prev;
12501   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12502 }
12503 
12504 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12505   Ty = Ty.getNonReferenceType();
12506   if (IsDereference && Ty->isPointerType())
12507     Ty = Ty->getPointeeType();
12508   return !Ty.isConstQualified();
12509 }
12510 
12511 // Update err_typecheck_assign_const and note_typecheck_assign_const
12512 // when this enum is changed.
12513 enum {
12514   ConstFunction,
12515   ConstVariable,
12516   ConstMember,
12517   ConstMethod,
12518   NestedConstMember,
12519   ConstUnknown,  // Keep as last element
12520 };
12521 
12522 /// Emit the "read-only variable not assignable" error and print notes to give
12523 /// more information about why the variable is not assignable, such as pointing
12524 /// to the declaration of a const variable, showing that a method is const, or
12525 /// that the function is returning a const reference.
12526 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12527                                     SourceLocation Loc) {
12528   SourceRange ExprRange = E->getSourceRange();
12529 
12530   // Only emit one error on the first const found.  All other consts will emit
12531   // a note to the error.
12532   bool DiagnosticEmitted = false;
12533 
12534   // Track if the current expression is the result of a dereference, and if the
12535   // next checked expression is the result of a dereference.
12536   bool IsDereference = false;
12537   bool NextIsDereference = false;
12538 
12539   // Loop to process MemberExpr chains.
12540   while (true) {
12541     IsDereference = NextIsDereference;
12542 
12543     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12544     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12545       NextIsDereference = ME->isArrow();
12546       const ValueDecl *VD = ME->getMemberDecl();
12547       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12548         // Mutable fields can be modified even if the class is const.
12549         if (Field->isMutable()) {
12550           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12551           break;
12552         }
12553 
12554         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12555           if (!DiagnosticEmitted) {
12556             S.Diag(Loc, diag::err_typecheck_assign_const)
12557                 << ExprRange << ConstMember << false /*static*/ << Field
12558                 << Field->getType();
12559             DiagnosticEmitted = true;
12560           }
12561           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12562               << ConstMember << false /*static*/ << Field << Field->getType()
12563               << Field->getSourceRange();
12564         }
12565         E = ME->getBase();
12566         continue;
12567       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12568         if (VDecl->getType().isConstQualified()) {
12569           if (!DiagnosticEmitted) {
12570             S.Diag(Loc, diag::err_typecheck_assign_const)
12571                 << ExprRange << ConstMember << true /*static*/ << VDecl
12572                 << VDecl->getType();
12573             DiagnosticEmitted = true;
12574           }
12575           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12576               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12577               << VDecl->getSourceRange();
12578         }
12579         // Static fields do not inherit constness from parents.
12580         break;
12581       }
12582       break; // End MemberExpr
12583     } else if (const ArraySubscriptExpr *ASE =
12584                    dyn_cast<ArraySubscriptExpr>(E)) {
12585       E = ASE->getBase()->IgnoreParenImpCasts();
12586       continue;
12587     } else if (const ExtVectorElementExpr *EVE =
12588                    dyn_cast<ExtVectorElementExpr>(E)) {
12589       E = EVE->getBase()->IgnoreParenImpCasts();
12590       continue;
12591     }
12592     break;
12593   }
12594 
12595   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12596     // Function calls
12597     const FunctionDecl *FD = CE->getDirectCallee();
12598     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12599       if (!DiagnosticEmitted) {
12600         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12601                                                       << ConstFunction << FD;
12602         DiagnosticEmitted = true;
12603       }
12604       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12605              diag::note_typecheck_assign_const)
12606           << ConstFunction << FD << FD->getReturnType()
12607           << FD->getReturnTypeSourceRange();
12608     }
12609   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12610     // Point to variable declaration.
12611     if (const ValueDecl *VD = DRE->getDecl()) {
12612       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12613         if (!DiagnosticEmitted) {
12614           S.Diag(Loc, diag::err_typecheck_assign_const)
12615               << ExprRange << ConstVariable << VD << VD->getType();
12616           DiagnosticEmitted = true;
12617         }
12618         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12619             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12620       }
12621     }
12622   } else if (isa<CXXThisExpr>(E)) {
12623     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12624       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12625         if (MD->isConst()) {
12626           if (!DiagnosticEmitted) {
12627             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12628                                                           << ConstMethod << MD;
12629             DiagnosticEmitted = true;
12630           }
12631           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12632               << ConstMethod << MD << MD->getSourceRange();
12633         }
12634       }
12635     }
12636   }
12637 
12638   if (DiagnosticEmitted)
12639     return;
12640 
12641   // Can't determine a more specific message, so display the generic error.
12642   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12643 }
12644 
12645 enum OriginalExprKind {
12646   OEK_Variable,
12647   OEK_Member,
12648   OEK_LValue
12649 };
12650 
12651 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12652                                          const RecordType *Ty,
12653                                          SourceLocation Loc, SourceRange Range,
12654                                          OriginalExprKind OEK,
12655                                          bool &DiagnosticEmitted) {
12656   std::vector<const RecordType *> RecordTypeList;
12657   RecordTypeList.push_back(Ty);
12658   unsigned NextToCheckIndex = 0;
12659   // We walk the record hierarchy breadth-first to ensure that we print
12660   // diagnostics in field nesting order.
12661   while (RecordTypeList.size() > NextToCheckIndex) {
12662     bool IsNested = NextToCheckIndex > 0;
12663     for (const FieldDecl *Field :
12664          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12665       // First, check every field for constness.
12666       QualType FieldTy = Field->getType();
12667       if (FieldTy.isConstQualified()) {
12668         if (!DiagnosticEmitted) {
12669           S.Diag(Loc, diag::err_typecheck_assign_const)
12670               << Range << NestedConstMember << OEK << VD
12671               << IsNested << Field;
12672           DiagnosticEmitted = true;
12673         }
12674         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12675             << NestedConstMember << IsNested << Field
12676             << FieldTy << Field->getSourceRange();
12677       }
12678 
12679       // Then we append it to the list to check next in order.
12680       FieldTy = FieldTy.getCanonicalType();
12681       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12682         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12683           RecordTypeList.push_back(FieldRecTy);
12684       }
12685     }
12686     ++NextToCheckIndex;
12687   }
12688 }
12689 
12690 /// Emit an error for the case where a record we are trying to assign to has a
12691 /// const-qualified field somewhere in its hierarchy.
12692 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12693                                          SourceLocation Loc) {
12694   QualType Ty = E->getType();
12695   assert(Ty->isRecordType() && "lvalue was not record?");
12696   SourceRange Range = E->getSourceRange();
12697   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12698   bool DiagEmitted = false;
12699 
12700   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12701     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12702             Range, OEK_Member, DiagEmitted);
12703   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12704     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12705             Range, OEK_Variable, DiagEmitted);
12706   else
12707     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12708             Range, OEK_LValue, DiagEmitted);
12709   if (!DiagEmitted)
12710     DiagnoseConstAssignment(S, E, Loc);
12711 }
12712 
12713 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12714 /// emit an error and return true.  If so, return false.
12715 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12716   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12717 
12718   S.CheckShadowingDeclModification(E, Loc);
12719 
12720   SourceLocation OrigLoc = Loc;
12721   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12722                                                               &Loc);
12723   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12724     IsLV = Expr::MLV_InvalidMessageExpression;
12725   if (IsLV == Expr::MLV_Valid)
12726     return false;
12727 
12728   unsigned DiagID = 0;
12729   bool NeedType = false;
12730   switch (IsLV) { // C99 6.5.16p2
12731   case Expr::MLV_ConstQualified:
12732     // Use a specialized diagnostic when we're assigning to an object
12733     // from an enclosing function or block.
12734     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12735       if (NCCK == NCCK_Block)
12736         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12737       else
12738         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12739       break;
12740     }
12741 
12742     // In ARC, use some specialized diagnostics for occasions where we
12743     // infer 'const'.  These are always pseudo-strong variables.
12744     if (S.getLangOpts().ObjCAutoRefCount) {
12745       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12746       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12747         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12748 
12749         // Use the normal diagnostic if it's pseudo-__strong but the
12750         // user actually wrote 'const'.
12751         if (var->isARCPseudoStrong() &&
12752             (!var->getTypeSourceInfo() ||
12753              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12754           // There are three pseudo-strong cases:
12755           //  - self
12756           ObjCMethodDecl *method = S.getCurMethodDecl();
12757           if (method && var == method->getSelfDecl()) {
12758             DiagID = method->isClassMethod()
12759               ? diag::err_typecheck_arc_assign_self_class_method
12760               : diag::err_typecheck_arc_assign_self;
12761 
12762           //  - Objective-C externally_retained attribute.
12763           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12764                      isa<ParmVarDecl>(var)) {
12765             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12766 
12767           //  - fast enumeration variables
12768           } else {
12769             DiagID = diag::err_typecheck_arr_assign_enumeration;
12770           }
12771 
12772           SourceRange Assign;
12773           if (Loc != OrigLoc)
12774             Assign = SourceRange(OrigLoc, OrigLoc);
12775           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12776           // We need to preserve the AST regardless, so migration tool
12777           // can do its job.
12778           return false;
12779         }
12780       }
12781     }
12782 
12783     // If none of the special cases above are triggered, then this is a
12784     // simple const assignment.
12785     if (DiagID == 0) {
12786       DiagnoseConstAssignment(S, E, Loc);
12787       return true;
12788     }
12789 
12790     break;
12791   case Expr::MLV_ConstAddrSpace:
12792     DiagnoseConstAssignment(S, E, Loc);
12793     return true;
12794   case Expr::MLV_ConstQualifiedField:
12795     DiagnoseRecursiveConstFields(S, E, Loc);
12796     return true;
12797   case Expr::MLV_ArrayType:
12798   case Expr::MLV_ArrayTemporary:
12799     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12800     NeedType = true;
12801     break;
12802   case Expr::MLV_NotObjectType:
12803     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12804     NeedType = true;
12805     break;
12806   case Expr::MLV_LValueCast:
12807     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12808     break;
12809   case Expr::MLV_Valid:
12810     llvm_unreachable("did not take early return for MLV_Valid");
12811   case Expr::MLV_InvalidExpression:
12812   case Expr::MLV_MemberFunction:
12813   case Expr::MLV_ClassTemporary:
12814     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12815     break;
12816   case Expr::MLV_IncompleteType:
12817   case Expr::MLV_IncompleteVoidType:
12818     return S.RequireCompleteType(Loc, E->getType(),
12819              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12820   case Expr::MLV_DuplicateVectorComponents:
12821     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12822     break;
12823   case Expr::MLV_NoSetterProperty:
12824     llvm_unreachable("readonly properties should be processed differently");
12825   case Expr::MLV_InvalidMessageExpression:
12826     DiagID = diag::err_readonly_message_assignment;
12827     break;
12828   case Expr::MLV_SubObjCPropertySetting:
12829     DiagID = diag::err_no_subobject_property_setting;
12830     break;
12831   }
12832 
12833   SourceRange Assign;
12834   if (Loc != OrigLoc)
12835     Assign = SourceRange(OrigLoc, OrigLoc);
12836   if (NeedType)
12837     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12838   else
12839     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12840   return true;
12841 }
12842 
12843 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12844                                          SourceLocation Loc,
12845                                          Sema &Sema) {
12846   if (Sema.inTemplateInstantiation())
12847     return;
12848   if (Sema.isUnevaluatedContext())
12849     return;
12850   if (Loc.isInvalid() || Loc.isMacroID())
12851     return;
12852   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12853     return;
12854 
12855   // C / C++ fields
12856   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12857   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12858   if (ML && MR) {
12859     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12860       return;
12861     const ValueDecl *LHSDecl =
12862         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12863     const ValueDecl *RHSDecl =
12864         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12865     if (LHSDecl != RHSDecl)
12866       return;
12867     if (LHSDecl->getType().isVolatileQualified())
12868       return;
12869     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12870       if (RefTy->getPointeeType().isVolatileQualified())
12871         return;
12872 
12873     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12874   }
12875 
12876   // Objective-C instance variables
12877   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12878   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12879   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12880     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12881     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12882     if (RL && RR && RL->getDecl() == RR->getDecl())
12883       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12884   }
12885 }
12886 
12887 // C99 6.5.16.1
12888 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12889                                        SourceLocation Loc,
12890                                        QualType CompoundType) {
12891   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12892 
12893   // Verify that LHS is a modifiable lvalue, and emit error if not.
12894   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12895     return QualType();
12896 
12897   QualType LHSType = LHSExpr->getType();
12898   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12899                                              CompoundType;
12900   // OpenCL v1.2 s6.1.1.1 p2:
12901   // The half data type can only be used to declare a pointer to a buffer that
12902   // contains half values
12903   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12904     LHSType->isHalfType()) {
12905     Diag(Loc, diag::err_opencl_half_load_store) << 1
12906         << LHSType.getUnqualifiedType();
12907     return QualType();
12908   }
12909 
12910   AssignConvertType ConvTy;
12911   if (CompoundType.isNull()) {
12912     Expr *RHSCheck = RHS.get();
12913 
12914     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12915 
12916     QualType LHSTy(LHSType);
12917     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12918     if (RHS.isInvalid())
12919       return QualType();
12920     // Special case of NSObject attributes on c-style pointer types.
12921     if (ConvTy == IncompatiblePointer &&
12922         ((Context.isObjCNSObjectType(LHSType) &&
12923           RHSType->isObjCObjectPointerType()) ||
12924          (Context.isObjCNSObjectType(RHSType) &&
12925           LHSType->isObjCObjectPointerType())))
12926       ConvTy = Compatible;
12927 
12928     if (ConvTy == Compatible &&
12929         LHSType->isObjCObjectType())
12930         Diag(Loc, diag::err_objc_object_assignment)
12931           << LHSType;
12932 
12933     // If the RHS is a unary plus or minus, check to see if they = and + are
12934     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12935     // instead of "x += 4".
12936     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12937       RHSCheck = ICE->getSubExpr();
12938     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12939       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12940           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12941           // Only if the two operators are exactly adjacent.
12942           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12943           // And there is a space or other character before the subexpr of the
12944           // unary +/-.  We don't want to warn on "x=-1".
12945           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12946           UO->getSubExpr()->getBeginLoc().isFileID()) {
12947         Diag(Loc, diag::warn_not_compound_assign)
12948           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12949           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12950       }
12951     }
12952 
12953     if (ConvTy == Compatible) {
12954       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12955         // Warn about retain cycles where a block captures the LHS, but
12956         // not if the LHS is a simple variable into which the block is
12957         // being stored...unless that variable can be captured by reference!
12958         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12959         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12960         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12961           checkRetainCycles(LHSExpr, RHS.get());
12962       }
12963 
12964       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12965           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12966         // It is safe to assign a weak reference into a strong variable.
12967         // Although this code can still have problems:
12968         //   id x = self.weakProp;
12969         //   id y = self.weakProp;
12970         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12971         // paths through the function. This should be revisited if
12972         // -Wrepeated-use-of-weak is made flow-sensitive.
12973         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12974         // variable, which will be valid for the current autorelease scope.
12975         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12976                              RHS.get()->getBeginLoc()))
12977           getCurFunction()->markSafeWeakUse(RHS.get());
12978 
12979       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12980         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12981       }
12982     }
12983   } else {
12984     // Compound assignment "x += y"
12985     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12986   }
12987 
12988   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12989                                RHS.get(), AA_Assigning))
12990     return QualType();
12991 
12992   CheckForNullPointerDereference(*this, LHSExpr);
12993 
12994   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12995     if (CompoundType.isNull()) {
12996       // C++2a [expr.ass]p5:
12997       //   A simple-assignment whose left operand is of a volatile-qualified
12998       //   type is deprecated unless the assignment is either a discarded-value
12999       //   expression or an unevaluated operand
13000       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13001     } else {
13002       // C++2a [expr.ass]p6:
13003       //   [Compound-assignment] expressions are deprecated if E1 has
13004       //   volatile-qualified type
13005       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13006     }
13007   }
13008 
13009   // C99 6.5.16p3: The type of an assignment expression is the type of the
13010   // left operand unless the left operand has qualified type, in which case
13011   // it is the unqualified version of the type of the left operand.
13012   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13013   // is converted to the type of the assignment expression (above).
13014   // C++ 5.17p1: the type of the assignment expression is that of its left
13015   // operand.
13016   return (getLangOpts().CPlusPlus
13017           ? LHSType : LHSType.getUnqualifiedType());
13018 }
13019 
13020 // Only ignore explicit casts to void.
13021 static bool IgnoreCommaOperand(const Expr *E) {
13022   E = E->IgnoreParens();
13023 
13024   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13025     if (CE->getCastKind() == CK_ToVoid) {
13026       return true;
13027     }
13028 
13029     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13030     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13031         CE->getSubExpr()->getType()->isDependentType()) {
13032       return true;
13033     }
13034   }
13035 
13036   return false;
13037 }
13038 
13039 // Look for instances where it is likely the comma operator is confused with
13040 // another operator.  There is an explicit list of acceptable expressions for
13041 // the left hand side of the comma operator, otherwise emit a warning.
13042 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13043   // No warnings in macros
13044   if (Loc.isMacroID())
13045     return;
13046 
13047   // Don't warn in template instantiations.
13048   if (inTemplateInstantiation())
13049     return;
13050 
13051   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13052   // instead, skip more than needed, then call back into here with the
13053   // CommaVisitor in SemaStmt.cpp.
13054   // The listed locations are the initialization and increment portions
13055   // of a for loop.  The additional checks are on the condition of
13056   // if statements, do/while loops, and for loops.
13057   // Differences in scope flags for C89 mode requires the extra logic.
13058   const unsigned ForIncrementFlags =
13059       getLangOpts().C99 || getLangOpts().CPlusPlus
13060           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13061           : Scope::ContinueScope | Scope::BreakScope;
13062   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13063   const unsigned ScopeFlags = getCurScope()->getFlags();
13064   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13065       (ScopeFlags & ForInitFlags) == ForInitFlags)
13066     return;
13067 
13068   // If there are multiple comma operators used together, get the RHS of the
13069   // of the comma operator as the LHS.
13070   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13071     if (BO->getOpcode() != BO_Comma)
13072       break;
13073     LHS = BO->getRHS();
13074   }
13075 
13076   // Only allow some expressions on LHS to not warn.
13077   if (IgnoreCommaOperand(LHS))
13078     return;
13079 
13080   Diag(Loc, diag::warn_comma_operator);
13081   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13082       << LHS->getSourceRange()
13083       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13084                                     LangOpts.CPlusPlus ? "static_cast<void>("
13085                                                        : "(void)(")
13086       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13087                                     ")");
13088 }
13089 
13090 // C99 6.5.17
13091 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13092                                    SourceLocation Loc) {
13093   LHS = S.CheckPlaceholderExpr(LHS.get());
13094   RHS = S.CheckPlaceholderExpr(RHS.get());
13095   if (LHS.isInvalid() || RHS.isInvalid())
13096     return QualType();
13097 
13098   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13099   // operands, but not unary promotions.
13100   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13101 
13102   // So we treat the LHS as a ignored value, and in C++ we allow the
13103   // containing site to determine what should be done with the RHS.
13104   LHS = S.IgnoredValueConversions(LHS.get());
13105   if (LHS.isInvalid())
13106     return QualType();
13107 
13108   S.DiagnoseUnusedExprResult(LHS.get());
13109 
13110   if (!S.getLangOpts().CPlusPlus) {
13111     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13112     if (RHS.isInvalid())
13113       return QualType();
13114     if (!RHS.get()->getType()->isVoidType())
13115       S.RequireCompleteType(Loc, RHS.get()->getType(),
13116                             diag::err_incomplete_type);
13117   }
13118 
13119   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13120     S.DiagnoseCommaOperator(LHS.get(), Loc);
13121 
13122   return RHS.get()->getType();
13123 }
13124 
13125 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13126 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13127 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13128                                                ExprValueKind &VK,
13129                                                ExprObjectKind &OK,
13130                                                SourceLocation OpLoc,
13131                                                bool IsInc, bool IsPrefix) {
13132   if (Op->isTypeDependent())
13133     return S.Context.DependentTy;
13134 
13135   QualType ResType = Op->getType();
13136   // Atomic types can be used for increment / decrement where the non-atomic
13137   // versions can, so ignore the _Atomic() specifier for the purpose of
13138   // checking.
13139   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13140     ResType = ResAtomicType->getValueType();
13141 
13142   assert(!ResType.isNull() && "no type for increment/decrement expression");
13143 
13144   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13145     // Decrement of bool is not allowed.
13146     if (!IsInc) {
13147       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13148       return QualType();
13149     }
13150     // Increment of bool sets it to true, but is deprecated.
13151     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13152                                               : diag::warn_increment_bool)
13153       << Op->getSourceRange();
13154   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13155     // Error on enum increments and decrements in C++ mode
13156     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13157     return QualType();
13158   } else if (ResType->isRealType()) {
13159     // OK!
13160   } else if (ResType->isPointerType()) {
13161     // C99 6.5.2.4p2, 6.5.6p2
13162     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13163       return QualType();
13164   } else if (ResType->isObjCObjectPointerType()) {
13165     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13166     // Otherwise, we just need a complete type.
13167     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13168         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13169       return QualType();
13170   } else if (ResType->isAnyComplexType()) {
13171     // C99 does not support ++/-- on complex types, we allow as an extension.
13172     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13173       << ResType << Op->getSourceRange();
13174   } else if (ResType->isPlaceholderType()) {
13175     ExprResult PR = S.CheckPlaceholderExpr(Op);
13176     if (PR.isInvalid()) return QualType();
13177     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13178                                           IsInc, IsPrefix);
13179   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13180     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13181   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13182              (ResType->castAs<VectorType>()->getVectorKind() !=
13183               VectorType::AltiVecBool)) {
13184     // The z vector extensions allow ++ and -- for non-bool vectors.
13185   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13186             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13187     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13188   } else {
13189     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13190       << ResType << int(IsInc) << Op->getSourceRange();
13191     return QualType();
13192   }
13193   // At this point, we know we have a real, complex or pointer type.
13194   // Now make sure the operand is a modifiable lvalue.
13195   if (CheckForModifiableLvalue(Op, OpLoc, S))
13196     return QualType();
13197   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13198     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13199     //   An operand with volatile-qualified type is deprecated
13200     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13201         << IsInc << ResType;
13202   }
13203   // In C++, a prefix increment is the same type as the operand. Otherwise
13204   // (in C or with postfix), the increment is the unqualified type of the
13205   // operand.
13206   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13207     VK = VK_LValue;
13208     OK = Op->getObjectKind();
13209     return ResType;
13210   } else {
13211     VK = VK_RValue;
13212     return ResType.getUnqualifiedType();
13213   }
13214 }
13215 
13216 
13217 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13218 /// This routine allows us to typecheck complex/recursive expressions
13219 /// where the declaration is needed for type checking. We only need to
13220 /// handle cases when the expression references a function designator
13221 /// or is an lvalue. Here are some examples:
13222 ///  - &(x) => x
13223 ///  - &*****f => f for f a function designator.
13224 ///  - &s.xx => s
13225 ///  - &s.zz[1].yy -> s, if zz is an array
13226 ///  - *(x + 1) -> x, if x is an array
13227 ///  - &"123"[2] -> 0
13228 ///  - & __real__ x -> x
13229 ///
13230 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13231 /// members.
13232 static ValueDecl *getPrimaryDecl(Expr *E) {
13233   switch (E->getStmtClass()) {
13234   case Stmt::DeclRefExprClass:
13235     return cast<DeclRefExpr>(E)->getDecl();
13236   case Stmt::MemberExprClass:
13237     // If this is an arrow operator, the address is an offset from
13238     // the base's value, so the object the base refers to is
13239     // irrelevant.
13240     if (cast<MemberExpr>(E)->isArrow())
13241       return nullptr;
13242     // Otherwise, the expression refers to a part of the base
13243     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13244   case Stmt::ArraySubscriptExprClass: {
13245     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13246     // promotion of register arrays earlier.
13247     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13248     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13249       if (ICE->getSubExpr()->getType()->isArrayType())
13250         return getPrimaryDecl(ICE->getSubExpr());
13251     }
13252     return nullptr;
13253   }
13254   case Stmt::UnaryOperatorClass: {
13255     UnaryOperator *UO = cast<UnaryOperator>(E);
13256 
13257     switch(UO->getOpcode()) {
13258     case UO_Real:
13259     case UO_Imag:
13260     case UO_Extension:
13261       return getPrimaryDecl(UO->getSubExpr());
13262     default:
13263       return nullptr;
13264     }
13265   }
13266   case Stmt::ParenExprClass:
13267     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13268   case Stmt::ImplicitCastExprClass:
13269     // If the result of an implicit cast is an l-value, we care about
13270     // the sub-expression; otherwise, the result here doesn't matter.
13271     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13272   case Stmt::CXXUuidofExprClass:
13273     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13274   default:
13275     return nullptr;
13276   }
13277 }
13278 
13279 namespace {
13280 enum {
13281   AO_Bit_Field = 0,
13282   AO_Vector_Element = 1,
13283   AO_Property_Expansion = 2,
13284   AO_Register_Variable = 3,
13285   AO_Matrix_Element = 4,
13286   AO_No_Error = 5
13287 };
13288 }
13289 /// Diagnose invalid operand for address of operations.
13290 ///
13291 /// \param Type The type of operand which cannot have its address taken.
13292 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13293                                          Expr *E, unsigned Type) {
13294   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13295 }
13296 
13297 /// CheckAddressOfOperand - The operand of & must be either a function
13298 /// designator or an lvalue designating an object. If it is an lvalue, the
13299 /// object cannot be declared with storage class register or be a bit field.
13300 /// Note: The usual conversions are *not* applied to the operand of the &
13301 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13302 /// In C++, the operand might be an overloaded function name, in which case
13303 /// we allow the '&' but retain the overloaded-function type.
13304 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13305   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13306     if (PTy->getKind() == BuiltinType::Overload) {
13307       Expr *E = OrigOp.get()->IgnoreParens();
13308       if (!isa<OverloadExpr>(E)) {
13309         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13310         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13311           << OrigOp.get()->getSourceRange();
13312         return QualType();
13313       }
13314 
13315       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13316       if (isa<UnresolvedMemberExpr>(Ovl))
13317         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13318           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13319             << OrigOp.get()->getSourceRange();
13320           return QualType();
13321         }
13322 
13323       return Context.OverloadTy;
13324     }
13325 
13326     if (PTy->getKind() == BuiltinType::UnknownAny)
13327       return Context.UnknownAnyTy;
13328 
13329     if (PTy->getKind() == BuiltinType::BoundMember) {
13330       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13331         << OrigOp.get()->getSourceRange();
13332       return QualType();
13333     }
13334 
13335     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13336     if (OrigOp.isInvalid()) return QualType();
13337   }
13338 
13339   if (OrigOp.get()->isTypeDependent())
13340     return Context.DependentTy;
13341 
13342   assert(!OrigOp.get()->getType()->isPlaceholderType());
13343 
13344   // Make sure to ignore parentheses in subsequent checks
13345   Expr *op = OrigOp.get()->IgnoreParens();
13346 
13347   // In OpenCL captures for blocks called as lambda functions
13348   // are located in the private address space. Blocks used in
13349   // enqueue_kernel can be located in a different address space
13350   // depending on a vendor implementation. Thus preventing
13351   // taking an address of the capture to avoid invalid AS casts.
13352   if (LangOpts.OpenCL) {
13353     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13354     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13355       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13356       return QualType();
13357     }
13358   }
13359 
13360   if (getLangOpts().C99) {
13361     // Implement C99-only parts of addressof rules.
13362     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13363       if (uOp->getOpcode() == UO_Deref)
13364         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13365         // (assuming the deref expression is valid).
13366         return uOp->getSubExpr()->getType();
13367     }
13368     // Technically, there should be a check for array subscript
13369     // expressions here, but the result of one is always an lvalue anyway.
13370   }
13371   ValueDecl *dcl = getPrimaryDecl(op);
13372 
13373   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13374     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13375                                            op->getBeginLoc()))
13376       return QualType();
13377 
13378   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13379   unsigned AddressOfError = AO_No_Error;
13380 
13381   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13382     bool sfinae = (bool)isSFINAEContext();
13383     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13384                                   : diag::ext_typecheck_addrof_temporary)
13385       << op->getType() << op->getSourceRange();
13386     if (sfinae)
13387       return QualType();
13388     // Materialize the temporary as an lvalue so that we can take its address.
13389     OrigOp = op =
13390         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13391   } else if (isa<ObjCSelectorExpr>(op)) {
13392     return Context.getPointerType(op->getType());
13393   } else if (lval == Expr::LV_MemberFunction) {
13394     // If it's an instance method, make a member pointer.
13395     // The expression must have exactly the form &A::foo.
13396 
13397     // If the underlying expression isn't a decl ref, give up.
13398     if (!isa<DeclRefExpr>(op)) {
13399       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13400         << OrigOp.get()->getSourceRange();
13401       return QualType();
13402     }
13403     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13404     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13405 
13406     // The id-expression was parenthesized.
13407     if (OrigOp.get() != DRE) {
13408       Diag(OpLoc, diag::err_parens_pointer_member_function)
13409         << OrigOp.get()->getSourceRange();
13410 
13411     // The method was named without a qualifier.
13412     } else if (!DRE->getQualifier()) {
13413       if (MD->getParent()->getName().empty())
13414         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13415           << op->getSourceRange();
13416       else {
13417         SmallString<32> Str;
13418         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13419         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13420           << op->getSourceRange()
13421           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13422       }
13423     }
13424 
13425     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13426     if (isa<CXXDestructorDecl>(MD))
13427       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13428 
13429     QualType MPTy = Context.getMemberPointerType(
13430         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13431     // Under the MS ABI, lock down the inheritance model now.
13432     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13433       (void)isCompleteType(OpLoc, MPTy);
13434     return MPTy;
13435   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13436     // C99 6.5.3.2p1
13437     // The operand must be either an l-value or a function designator
13438     if (!op->getType()->isFunctionType()) {
13439       // Use a special diagnostic for loads from property references.
13440       if (isa<PseudoObjectExpr>(op)) {
13441         AddressOfError = AO_Property_Expansion;
13442       } else {
13443         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13444           << op->getType() << op->getSourceRange();
13445         return QualType();
13446       }
13447     }
13448   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13449     // The operand cannot be a bit-field
13450     AddressOfError = AO_Bit_Field;
13451   } else if (op->getObjectKind() == OK_VectorComponent) {
13452     // The operand cannot be an element of a vector
13453     AddressOfError = AO_Vector_Element;
13454   } else if (op->getObjectKind() == OK_MatrixComponent) {
13455     // The operand cannot be an element of a matrix.
13456     AddressOfError = AO_Matrix_Element;
13457   } else if (dcl) { // C99 6.5.3.2p1
13458     // We have an lvalue with a decl. Make sure the decl is not declared
13459     // with the register storage-class specifier.
13460     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13461       // in C++ it is not error to take address of a register
13462       // variable (c++03 7.1.1P3)
13463       if (vd->getStorageClass() == SC_Register &&
13464           !getLangOpts().CPlusPlus) {
13465         AddressOfError = AO_Register_Variable;
13466       }
13467     } else if (isa<MSPropertyDecl>(dcl)) {
13468       AddressOfError = AO_Property_Expansion;
13469     } else if (isa<FunctionTemplateDecl>(dcl)) {
13470       return Context.OverloadTy;
13471     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13472       // Okay: we can take the address of a field.
13473       // Could be a pointer to member, though, if there is an explicit
13474       // scope qualifier for the class.
13475       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13476         DeclContext *Ctx = dcl->getDeclContext();
13477         if (Ctx && Ctx->isRecord()) {
13478           if (dcl->getType()->isReferenceType()) {
13479             Diag(OpLoc,
13480                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13481               << dcl->getDeclName() << dcl->getType();
13482             return QualType();
13483           }
13484 
13485           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13486             Ctx = Ctx->getParent();
13487 
13488           QualType MPTy = Context.getMemberPointerType(
13489               op->getType(),
13490               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13491           // Under the MS ABI, lock down the inheritance model now.
13492           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13493             (void)isCompleteType(OpLoc, MPTy);
13494           return MPTy;
13495         }
13496       }
13497     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13498                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13499       llvm_unreachable("Unknown/unexpected decl type");
13500   }
13501 
13502   if (AddressOfError != AO_No_Error) {
13503     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13504     return QualType();
13505   }
13506 
13507   if (lval == Expr::LV_IncompleteVoidType) {
13508     // Taking the address of a void variable is technically illegal, but we
13509     // allow it in cases which are otherwise valid.
13510     // Example: "extern void x; void* y = &x;".
13511     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13512   }
13513 
13514   // If the operand has type "type", the result has type "pointer to type".
13515   if (op->getType()->isObjCObjectType())
13516     return Context.getObjCObjectPointerType(op->getType());
13517 
13518   CheckAddressOfPackedMember(op);
13519 
13520   return Context.getPointerType(op->getType());
13521 }
13522 
13523 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13524   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13525   if (!DRE)
13526     return;
13527   const Decl *D = DRE->getDecl();
13528   if (!D)
13529     return;
13530   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13531   if (!Param)
13532     return;
13533   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13534     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13535       return;
13536   if (FunctionScopeInfo *FD = S.getCurFunction())
13537     if (!FD->ModifiedNonNullParams.count(Param))
13538       FD->ModifiedNonNullParams.insert(Param);
13539 }
13540 
13541 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13542 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13543                                         SourceLocation OpLoc) {
13544   if (Op->isTypeDependent())
13545     return S.Context.DependentTy;
13546 
13547   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13548   if (ConvResult.isInvalid())
13549     return QualType();
13550   Op = ConvResult.get();
13551   QualType OpTy = Op->getType();
13552   QualType Result;
13553 
13554   if (isa<CXXReinterpretCastExpr>(Op)) {
13555     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13556     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13557                                      Op->getSourceRange());
13558   }
13559 
13560   if (const PointerType *PT = OpTy->getAs<PointerType>())
13561   {
13562     Result = PT->getPointeeType();
13563   }
13564   else if (const ObjCObjectPointerType *OPT =
13565              OpTy->getAs<ObjCObjectPointerType>())
13566     Result = OPT->getPointeeType();
13567   else {
13568     ExprResult PR = S.CheckPlaceholderExpr(Op);
13569     if (PR.isInvalid()) return QualType();
13570     if (PR.get() != Op)
13571       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13572   }
13573 
13574   if (Result.isNull()) {
13575     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13576       << OpTy << Op->getSourceRange();
13577     return QualType();
13578   }
13579 
13580   // Note that per both C89 and C99, indirection is always legal, even if Result
13581   // is an incomplete type or void.  It would be possible to warn about
13582   // dereferencing a void pointer, but it's completely well-defined, and such a
13583   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13584   // for pointers to 'void' but is fine for any other pointer type:
13585   //
13586   // C++ [expr.unary.op]p1:
13587   //   [...] the expression to which [the unary * operator] is applied shall
13588   //   be a pointer to an object type, or a pointer to a function type
13589   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13590     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13591       << OpTy << Op->getSourceRange();
13592 
13593   // Dereferences are usually l-values...
13594   VK = VK_LValue;
13595 
13596   // ...except that certain expressions are never l-values in C.
13597   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13598     VK = VK_RValue;
13599 
13600   return Result;
13601 }
13602 
13603 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13604   BinaryOperatorKind Opc;
13605   switch (Kind) {
13606   default: llvm_unreachable("Unknown binop!");
13607   case tok::periodstar:           Opc = BO_PtrMemD; break;
13608   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13609   case tok::star:                 Opc = BO_Mul; break;
13610   case tok::slash:                Opc = BO_Div; break;
13611   case tok::percent:              Opc = BO_Rem; break;
13612   case tok::plus:                 Opc = BO_Add; break;
13613   case tok::minus:                Opc = BO_Sub; break;
13614   case tok::lessless:             Opc = BO_Shl; break;
13615   case tok::greatergreater:       Opc = BO_Shr; break;
13616   case tok::lessequal:            Opc = BO_LE; break;
13617   case tok::less:                 Opc = BO_LT; break;
13618   case tok::greaterequal:         Opc = BO_GE; break;
13619   case tok::greater:              Opc = BO_GT; break;
13620   case tok::exclaimequal:         Opc = BO_NE; break;
13621   case tok::equalequal:           Opc = BO_EQ; break;
13622   case tok::spaceship:            Opc = BO_Cmp; break;
13623   case tok::amp:                  Opc = BO_And; break;
13624   case tok::caret:                Opc = BO_Xor; break;
13625   case tok::pipe:                 Opc = BO_Or; break;
13626   case tok::ampamp:               Opc = BO_LAnd; break;
13627   case tok::pipepipe:             Opc = BO_LOr; break;
13628   case tok::equal:                Opc = BO_Assign; break;
13629   case tok::starequal:            Opc = BO_MulAssign; break;
13630   case tok::slashequal:           Opc = BO_DivAssign; break;
13631   case tok::percentequal:         Opc = BO_RemAssign; break;
13632   case tok::plusequal:            Opc = BO_AddAssign; break;
13633   case tok::minusequal:           Opc = BO_SubAssign; break;
13634   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13635   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13636   case tok::ampequal:             Opc = BO_AndAssign; break;
13637   case tok::caretequal:           Opc = BO_XorAssign; break;
13638   case tok::pipeequal:            Opc = BO_OrAssign; break;
13639   case tok::comma:                Opc = BO_Comma; break;
13640   }
13641   return Opc;
13642 }
13643 
13644 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13645   tok::TokenKind Kind) {
13646   UnaryOperatorKind Opc;
13647   switch (Kind) {
13648   default: llvm_unreachable("Unknown unary op!");
13649   case tok::plusplus:     Opc = UO_PreInc; break;
13650   case tok::minusminus:   Opc = UO_PreDec; break;
13651   case tok::amp:          Opc = UO_AddrOf; break;
13652   case tok::star:         Opc = UO_Deref; break;
13653   case tok::plus:         Opc = UO_Plus; break;
13654   case tok::minus:        Opc = UO_Minus; break;
13655   case tok::tilde:        Opc = UO_Not; break;
13656   case tok::exclaim:      Opc = UO_LNot; break;
13657   case tok::kw___real:    Opc = UO_Real; break;
13658   case tok::kw___imag:    Opc = UO_Imag; break;
13659   case tok::kw___extension__: Opc = UO_Extension; break;
13660   }
13661   return Opc;
13662 }
13663 
13664 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13665 /// This warning suppressed in the event of macro expansions.
13666 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13667                                    SourceLocation OpLoc, bool IsBuiltin) {
13668   if (S.inTemplateInstantiation())
13669     return;
13670   if (S.isUnevaluatedContext())
13671     return;
13672   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13673     return;
13674   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13675   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13676   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13677   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13678   if (!LHSDeclRef || !RHSDeclRef ||
13679       LHSDeclRef->getLocation().isMacroID() ||
13680       RHSDeclRef->getLocation().isMacroID())
13681     return;
13682   const ValueDecl *LHSDecl =
13683     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13684   const ValueDecl *RHSDecl =
13685     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13686   if (LHSDecl != RHSDecl)
13687     return;
13688   if (LHSDecl->getType().isVolatileQualified())
13689     return;
13690   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13691     if (RefTy->getPointeeType().isVolatileQualified())
13692       return;
13693 
13694   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13695                           : diag::warn_self_assignment_overloaded)
13696       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13697       << RHSExpr->getSourceRange();
13698 }
13699 
13700 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13701 /// is usually indicative of introspection within the Objective-C pointer.
13702 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13703                                           SourceLocation OpLoc) {
13704   if (!S.getLangOpts().ObjC)
13705     return;
13706 
13707   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13708   const Expr *LHS = L.get();
13709   const Expr *RHS = R.get();
13710 
13711   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13712     ObjCPointerExpr = LHS;
13713     OtherExpr = RHS;
13714   }
13715   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13716     ObjCPointerExpr = RHS;
13717     OtherExpr = LHS;
13718   }
13719 
13720   // This warning is deliberately made very specific to reduce false
13721   // positives with logic that uses '&' for hashing.  This logic mainly
13722   // looks for code trying to introspect into tagged pointers, which
13723   // code should generally never do.
13724   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13725     unsigned Diag = diag::warn_objc_pointer_masking;
13726     // Determine if we are introspecting the result of performSelectorXXX.
13727     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13728     // Special case messages to -performSelector and friends, which
13729     // can return non-pointer values boxed in a pointer value.
13730     // Some clients may wish to silence warnings in this subcase.
13731     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13732       Selector S = ME->getSelector();
13733       StringRef SelArg0 = S.getNameForSlot(0);
13734       if (SelArg0.startswith("performSelector"))
13735         Diag = diag::warn_objc_pointer_masking_performSelector;
13736     }
13737 
13738     S.Diag(OpLoc, Diag)
13739       << ObjCPointerExpr->getSourceRange();
13740   }
13741 }
13742 
13743 static NamedDecl *getDeclFromExpr(Expr *E) {
13744   if (!E)
13745     return nullptr;
13746   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13747     return DRE->getDecl();
13748   if (auto *ME = dyn_cast<MemberExpr>(E))
13749     return ME->getMemberDecl();
13750   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13751     return IRE->getDecl();
13752   return nullptr;
13753 }
13754 
13755 // This helper function promotes a binary operator's operands (which are of a
13756 // half vector type) to a vector of floats and then truncates the result to
13757 // a vector of either half or short.
13758 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13759                                       BinaryOperatorKind Opc, QualType ResultTy,
13760                                       ExprValueKind VK, ExprObjectKind OK,
13761                                       bool IsCompAssign, SourceLocation OpLoc,
13762                                       FPOptionsOverride FPFeatures) {
13763   auto &Context = S.getASTContext();
13764   assert((isVector(ResultTy, Context.HalfTy) ||
13765           isVector(ResultTy, Context.ShortTy)) &&
13766          "Result must be a vector of half or short");
13767   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13768          isVector(RHS.get()->getType(), Context.HalfTy) &&
13769          "both operands expected to be a half vector");
13770 
13771   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13772   QualType BinOpResTy = RHS.get()->getType();
13773 
13774   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13775   // change BinOpResTy to a vector of ints.
13776   if (isVector(ResultTy, Context.ShortTy))
13777     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13778 
13779   if (IsCompAssign)
13780     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13781                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13782                                           BinOpResTy, BinOpResTy);
13783 
13784   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13785   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13786                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13787   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13788 }
13789 
13790 static std::pair<ExprResult, ExprResult>
13791 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13792                            Expr *RHSExpr) {
13793   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13794   if (!S.Context.isDependenceAllowed()) {
13795     // C cannot handle TypoExpr nodes on either side of a binop because it
13796     // doesn't handle dependent types properly, so make sure any TypoExprs have
13797     // been dealt with before checking the operands.
13798     LHS = S.CorrectDelayedTyposInExpr(LHS);
13799     RHS = S.CorrectDelayedTyposInExpr(
13800         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13801         [Opc, LHS](Expr *E) {
13802           if (Opc != BO_Assign)
13803             return ExprResult(E);
13804           // Avoid correcting the RHS to the same Expr as the LHS.
13805           Decl *D = getDeclFromExpr(E);
13806           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13807         });
13808   }
13809   return std::make_pair(LHS, RHS);
13810 }
13811 
13812 /// Returns true if conversion between vectors of halfs and vectors of floats
13813 /// is needed.
13814 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13815                                      Expr *E0, Expr *E1 = nullptr) {
13816   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13817       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13818     return false;
13819 
13820   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13821     QualType Ty = E->IgnoreImplicit()->getType();
13822 
13823     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13824     // to vectors of floats. Although the element type of the vectors is __fp16,
13825     // the vectors shouldn't be treated as storage-only types. See the
13826     // discussion here: https://reviews.llvm.org/rG825235c140e7
13827     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13828       if (VT->getVectorKind() == VectorType::NeonVector)
13829         return false;
13830       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13831     }
13832     return false;
13833   };
13834 
13835   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13836 }
13837 
13838 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13839 /// operator @p Opc at location @c TokLoc. This routine only supports
13840 /// built-in operations; ActOnBinOp handles overloaded operators.
13841 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13842                                     BinaryOperatorKind Opc,
13843                                     Expr *LHSExpr, Expr *RHSExpr) {
13844   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13845     // The syntax only allows initializer lists on the RHS of assignment,
13846     // so we don't need to worry about accepting invalid code for
13847     // non-assignment operators.
13848     // C++11 5.17p9:
13849     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13850     //   of x = {} is x = T().
13851     InitializationKind Kind = InitializationKind::CreateDirectList(
13852         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13853     InitializedEntity Entity =
13854         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13855     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13856     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13857     if (Init.isInvalid())
13858       return Init;
13859     RHSExpr = Init.get();
13860   }
13861 
13862   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13863   QualType ResultTy;     // Result type of the binary operator.
13864   // The following two variables are used for compound assignment operators
13865   QualType CompLHSTy;    // Type of LHS after promotions for computation
13866   QualType CompResultTy; // Type of computation result
13867   ExprValueKind VK = VK_RValue;
13868   ExprObjectKind OK = OK_Ordinary;
13869   bool ConvertHalfVec = false;
13870 
13871   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13872   if (!LHS.isUsable() || !RHS.isUsable())
13873     return ExprError();
13874 
13875   if (getLangOpts().OpenCL) {
13876     QualType LHSTy = LHSExpr->getType();
13877     QualType RHSTy = RHSExpr->getType();
13878     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13879     // the ATOMIC_VAR_INIT macro.
13880     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13881       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13882       if (BO_Assign == Opc)
13883         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13884       else
13885         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13886       return ExprError();
13887     }
13888 
13889     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13890     // only with a builtin functions and therefore should be disallowed here.
13891     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13892         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13893         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13894         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13895       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13896       return ExprError();
13897     }
13898   }
13899 
13900   switch (Opc) {
13901   case BO_Assign:
13902     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13903     if (getLangOpts().CPlusPlus &&
13904         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13905       VK = LHS.get()->getValueKind();
13906       OK = LHS.get()->getObjectKind();
13907     }
13908     if (!ResultTy.isNull()) {
13909       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13910       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13911 
13912       // Avoid copying a block to the heap if the block is assigned to a local
13913       // auto variable that is declared in the same scope as the block. This
13914       // optimization is unsafe if the local variable is declared in an outer
13915       // scope. For example:
13916       //
13917       // BlockTy b;
13918       // {
13919       //   b = ^{...};
13920       // }
13921       // // It is unsafe to invoke the block here if it wasn't copied to the
13922       // // heap.
13923       // b();
13924 
13925       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13926         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13927           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13928             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13929               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13930 
13931       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13932         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13933                               NTCUC_Assignment, NTCUK_Copy);
13934     }
13935     RecordModifiableNonNullParam(*this, LHS.get());
13936     break;
13937   case BO_PtrMemD:
13938   case BO_PtrMemI:
13939     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13940                                             Opc == BO_PtrMemI);
13941     break;
13942   case BO_Mul:
13943   case BO_Div:
13944     ConvertHalfVec = true;
13945     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13946                                            Opc == BO_Div);
13947     break;
13948   case BO_Rem:
13949     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13950     break;
13951   case BO_Add:
13952     ConvertHalfVec = true;
13953     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13954     break;
13955   case BO_Sub:
13956     ConvertHalfVec = true;
13957     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13958     break;
13959   case BO_Shl:
13960   case BO_Shr:
13961     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13962     break;
13963   case BO_LE:
13964   case BO_LT:
13965   case BO_GE:
13966   case BO_GT:
13967     ConvertHalfVec = true;
13968     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13969     break;
13970   case BO_EQ:
13971   case BO_NE:
13972     ConvertHalfVec = true;
13973     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13974     break;
13975   case BO_Cmp:
13976     ConvertHalfVec = true;
13977     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13978     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13979     break;
13980   case BO_And:
13981     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13982     LLVM_FALLTHROUGH;
13983   case BO_Xor:
13984   case BO_Or:
13985     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13986     break;
13987   case BO_LAnd:
13988   case BO_LOr:
13989     ConvertHalfVec = true;
13990     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13991     break;
13992   case BO_MulAssign:
13993   case BO_DivAssign:
13994     ConvertHalfVec = true;
13995     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13996                                                Opc == BO_DivAssign);
13997     CompLHSTy = CompResultTy;
13998     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13999       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14000     break;
14001   case BO_RemAssign:
14002     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14003     CompLHSTy = CompResultTy;
14004     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14005       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14006     break;
14007   case BO_AddAssign:
14008     ConvertHalfVec = true;
14009     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14010     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14011       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14012     break;
14013   case BO_SubAssign:
14014     ConvertHalfVec = true;
14015     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14016     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14017       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14018     break;
14019   case BO_ShlAssign:
14020   case BO_ShrAssign:
14021     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14022     CompLHSTy = CompResultTy;
14023     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14024       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14025     break;
14026   case BO_AndAssign:
14027   case BO_OrAssign: // fallthrough
14028     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14029     LLVM_FALLTHROUGH;
14030   case BO_XorAssign:
14031     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14032     CompLHSTy = CompResultTy;
14033     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14034       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14035     break;
14036   case BO_Comma:
14037     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14038     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14039       VK = RHS.get()->getValueKind();
14040       OK = RHS.get()->getObjectKind();
14041     }
14042     break;
14043   }
14044   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14045     return ExprError();
14046 
14047   // Some of the binary operations require promoting operands of half vector to
14048   // float vectors and truncating the result back to half vector. For now, we do
14049   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14050   // arm64).
14051   assert(
14052       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14053                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14054       "both sides are half vectors or neither sides are");
14055   ConvertHalfVec =
14056       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14057 
14058   // Check for array bounds violations for both sides of the BinaryOperator
14059   CheckArrayAccess(LHS.get());
14060   CheckArrayAccess(RHS.get());
14061 
14062   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14063     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14064                                                  &Context.Idents.get("object_setClass"),
14065                                                  SourceLocation(), LookupOrdinaryName);
14066     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14067       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14068       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14069           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14070                                         "object_setClass(")
14071           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14072                                           ",")
14073           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14074     }
14075     else
14076       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14077   }
14078   else if (const ObjCIvarRefExpr *OIRE =
14079            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14080     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14081 
14082   // Opc is not a compound assignment if CompResultTy is null.
14083   if (CompResultTy.isNull()) {
14084     if (ConvertHalfVec)
14085       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14086                                  OpLoc, CurFPFeatureOverrides());
14087     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14088                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14089   }
14090 
14091   // Handle compound assignments.
14092   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14093       OK_ObjCProperty) {
14094     VK = VK_LValue;
14095     OK = LHS.get()->getObjectKind();
14096   }
14097 
14098   // The LHS is not converted to the result type for fixed-point compound
14099   // assignment as the common type is computed on demand. Reset the CompLHSTy
14100   // to the LHS type we would have gotten after unary conversions.
14101   if (CompResultTy->isFixedPointType())
14102     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14103 
14104   if (ConvertHalfVec)
14105     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14106                                OpLoc, CurFPFeatureOverrides());
14107 
14108   return CompoundAssignOperator::Create(
14109       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14110       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14111 }
14112 
14113 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14114 /// operators are mixed in a way that suggests that the programmer forgot that
14115 /// comparison operators have higher precedence. The most typical example of
14116 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14117 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14118                                       SourceLocation OpLoc, Expr *LHSExpr,
14119                                       Expr *RHSExpr) {
14120   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14121   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14122 
14123   // Check that one of the sides is a comparison operator and the other isn't.
14124   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14125   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14126   if (isLeftComp == isRightComp)
14127     return;
14128 
14129   // Bitwise operations are sometimes used as eager logical ops.
14130   // Don't diagnose this.
14131   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14132   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14133   if (isLeftBitwise || isRightBitwise)
14134     return;
14135 
14136   SourceRange DiagRange = isLeftComp
14137                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14138                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14139   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14140   SourceRange ParensRange =
14141       isLeftComp
14142           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14143           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14144 
14145   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14146     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14147   SuggestParentheses(Self, OpLoc,
14148     Self.PDiag(diag::note_precedence_silence) << OpStr,
14149     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14150   SuggestParentheses(Self, OpLoc,
14151     Self.PDiag(diag::note_precedence_bitwise_first)
14152       << BinaryOperator::getOpcodeStr(Opc),
14153     ParensRange);
14154 }
14155 
14156 /// It accepts a '&&' expr that is inside a '||' one.
14157 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14158 /// in parentheses.
14159 static void
14160 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14161                                        BinaryOperator *Bop) {
14162   assert(Bop->getOpcode() == BO_LAnd);
14163   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14164       << Bop->getSourceRange() << OpLoc;
14165   SuggestParentheses(Self, Bop->getOperatorLoc(),
14166     Self.PDiag(diag::note_precedence_silence)
14167       << Bop->getOpcodeStr(),
14168     Bop->getSourceRange());
14169 }
14170 
14171 /// Returns true if the given expression can be evaluated as a constant
14172 /// 'true'.
14173 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14174   bool Res;
14175   return !E->isValueDependent() &&
14176          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14177 }
14178 
14179 /// Returns true if the given expression can be evaluated as a constant
14180 /// 'false'.
14181 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14182   bool Res;
14183   return !E->isValueDependent() &&
14184          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14185 }
14186 
14187 /// Look for '&&' in the left hand of a '||' expr.
14188 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14189                                              Expr *LHSExpr, Expr *RHSExpr) {
14190   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14191     if (Bop->getOpcode() == BO_LAnd) {
14192       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14193       if (EvaluatesAsFalse(S, RHSExpr))
14194         return;
14195       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14196       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14197         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14198     } else if (Bop->getOpcode() == BO_LOr) {
14199       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14200         // If it's "a || b && 1 || c" we didn't warn earlier for
14201         // "a || b && 1", but warn now.
14202         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14203           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14204       }
14205     }
14206   }
14207 }
14208 
14209 /// Look for '&&' in the right hand of a '||' expr.
14210 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14211                                              Expr *LHSExpr, Expr *RHSExpr) {
14212   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14213     if (Bop->getOpcode() == BO_LAnd) {
14214       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14215       if (EvaluatesAsFalse(S, LHSExpr))
14216         return;
14217       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14218       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14219         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14220     }
14221   }
14222 }
14223 
14224 /// Look for bitwise op in the left or right hand of a bitwise op with
14225 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14226 /// the '&' expression in parentheses.
14227 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14228                                          SourceLocation OpLoc, Expr *SubExpr) {
14229   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14230     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14231       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14232         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14233         << Bop->getSourceRange() << OpLoc;
14234       SuggestParentheses(S, Bop->getOperatorLoc(),
14235         S.PDiag(diag::note_precedence_silence)
14236           << Bop->getOpcodeStr(),
14237         Bop->getSourceRange());
14238     }
14239   }
14240 }
14241 
14242 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14243                                     Expr *SubExpr, StringRef Shift) {
14244   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14245     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14246       StringRef Op = Bop->getOpcodeStr();
14247       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14248           << Bop->getSourceRange() << OpLoc << Shift << Op;
14249       SuggestParentheses(S, Bop->getOperatorLoc(),
14250           S.PDiag(diag::note_precedence_silence) << Op,
14251           Bop->getSourceRange());
14252     }
14253   }
14254 }
14255 
14256 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14257                                  Expr *LHSExpr, Expr *RHSExpr) {
14258   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14259   if (!OCE)
14260     return;
14261 
14262   FunctionDecl *FD = OCE->getDirectCallee();
14263   if (!FD || !FD->isOverloadedOperator())
14264     return;
14265 
14266   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14267   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14268     return;
14269 
14270   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14271       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14272       << (Kind == OO_LessLess);
14273   SuggestParentheses(S, OCE->getOperatorLoc(),
14274                      S.PDiag(diag::note_precedence_silence)
14275                          << (Kind == OO_LessLess ? "<<" : ">>"),
14276                      OCE->getSourceRange());
14277   SuggestParentheses(
14278       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14279       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14280 }
14281 
14282 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14283 /// precedence.
14284 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14285                                     SourceLocation OpLoc, Expr *LHSExpr,
14286                                     Expr *RHSExpr){
14287   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14288   if (BinaryOperator::isBitwiseOp(Opc))
14289     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14290 
14291   // Diagnose "arg1 & arg2 | arg3"
14292   if ((Opc == BO_Or || Opc == BO_Xor) &&
14293       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14294     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14295     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14296   }
14297 
14298   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14299   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14300   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14301     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14302     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14303   }
14304 
14305   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14306       || Opc == BO_Shr) {
14307     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14308     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14309     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14310   }
14311 
14312   // Warn on overloaded shift operators and comparisons, such as:
14313   // cout << 5 == 4;
14314   if (BinaryOperator::isComparisonOp(Opc))
14315     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14316 }
14317 
14318 // Binary Operators.  'Tok' is the token for the operator.
14319 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14320                             tok::TokenKind Kind,
14321                             Expr *LHSExpr, Expr *RHSExpr) {
14322   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14323   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14324   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14325 
14326   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14327   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14328 
14329   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14330 }
14331 
14332 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14333                        UnresolvedSetImpl &Functions) {
14334   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14335   if (OverOp != OO_None && OverOp != OO_Equal)
14336     LookupOverloadedOperatorName(OverOp, S, Functions);
14337 
14338   // In C++20 onwards, we may have a second operator to look up.
14339   if (getLangOpts().CPlusPlus20) {
14340     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14341       LookupOverloadedOperatorName(ExtraOp, S, Functions);
14342   }
14343 }
14344 
14345 /// Build an overloaded binary operator expression in the given scope.
14346 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14347                                        BinaryOperatorKind Opc,
14348                                        Expr *LHS, Expr *RHS) {
14349   switch (Opc) {
14350   case BO_Assign:
14351   case BO_DivAssign:
14352   case BO_RemAssign:
14353   case BO_SubAssign:
14354   case BO_AndAssign:
14355   case BO_OrAssign:
14356   case BO_XorAssign:
14357     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14358     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14359     break;
14360   default:
14361     break;
14362   }
14363 
14364   // Find all of the overloaded operators visible from this point.
14365   UnresolvedSet<16> Functions;
14366   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14367 
14368   // Build the (potentially-overloaded, potentially-dependent)
14369   // binary operation.
14370   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14371 }
14372 
14373 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14374                             BinaryOperatorKind Opc,
14375                             Expr *LHSExpr, Expr *RHSExpr) {
14376   ExprResult LHS, RHS;
14377   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14378   if (!LHS.isUsable() || !RHS.isUsable())
14379     return ExprError();
14380   LHSExpr = LHS.get();
14381   RHSExpr = RHS.get();
14382 
14383   // We want to end up calling one of checkPseudoObjectAssignment
14384   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14385   // both expressions are overloadable or either is type-dependent),
14386   // or CreateBuiltinBinOp (in any other case).  We also want to get
14387   // any placeholder types out of the way.
14388 
14389   // Handle pseudo-objects in the LHS.
14390   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14391     // Assignments with a pseudo-object l-value need special analysis.
14392     if (pty->getKind() == BuiltinType::PseudoObject &&
14393         BinaryOperator::isAssignmentOp(Opc))
14394       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14395 
14396     // Don't resolve overloads if the other type is overloadable.
14397     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14398       // We can't actually test that if we still have a placeholder,
14399       // though.  Fortunately, none of the exceptions we see in that
14400       // code below are valid when the LHS is an overload set.  Note
14401       // that an overload set can be dependently-typed, but it never
14402       // instantiates to having an overloadable type.
14403       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14404       if (resolvedRHS.isInvalid()) return ExprError();
14405       RHSExpr = resolvedRHS.get();
14406 
14407       if (RHSExpr->isTypeDependent() ||
14408           RHSExpr->getType()->isOverloadableType())
14409         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14410     }
14411 
14412     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14413     // template, diagnose the missing 'template' keyword instead of diagnosing
14414     // an invalid use of a bound member function.
14415     //
14416     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14417     // to C++1z [over.over]/1.4, but we already checked for that case above.
14418     if (Opc == BO_LT && inTemplateInstantiation() &&
14419         (pty->getKind() == BuiltinType::BoundMember ||
14420          pty->getKind() == BuiltinType::Overload)) {
14421       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14422       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14423           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14424             return isa<FunctionTemplateDecl>(ND);
14425           })) {
14426         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14427                                 : OE->getNameLoc(),
14428              diag::err_template_kw_missing)
14429           << OE->getName().getAsString() << "";
14430         return ExprError();
14431       }
14432     }
14433 
14434     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14435     if (LHS.isInvalid()) return ExprError();
14436     LHSExpr = LHS.get();
14437   }
14438 
14439   // Handle pseudo-objects in the RHS.
14440   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14441     // An overload in the RHS can potentially be resolved by the type
14442     // being assigned to.
14443     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14444       if (getLangOpts().CPlusPlus &&
14445           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14446            LHSExpr->getType()->isOverloadableType()))
14447         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14448 
14449       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14450     }
14451 
14452     // Don't resolve overloads if the other type is overloadable.
14453     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14454         LHSExpr->getType()->isOverloadableType())
14455       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14456 
14457     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14458     if (!resolvedRHS.isUsable()) return ExprError();
14459     RHSExpr = resolvedRHS.get();
14460   }
14461 
14462   if (getLangOpts().CPlusPlus) {
14463     // If either expression is type-dependent, always build an
14464     // overloaded op.
14465     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14466       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14467 
14468     // Otherwise, build an overloaded op if either expression has an
14469     // overloadable type.
14470     if (LHSExpr->getType()->isOverloadableType() ||
14471         RHSExpr->getType()->isOverloadableType())
14472       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14473   }
14474 
14475   if (getLangOpts().RecoveryAST &&
14476       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14477     assert(!getLangOpts().CPlusPlus);
14478     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14479            "Should only occur in error-recovery path.");
14480     if (BinaryOperator::isCompoundAssignmentOp(Opc))
14481       // C [6.15.16] p3:
14482       // An assignment expression has the value of the left operand after the
14483       // assignment, but is not an lvalue.
14484       return CompoundAssignOperator::Create(
14485           Context, LHSExpr, RHSExpr, Opc,
14486           LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14487           OpLoc, CurFPFeatureOverrides());
14488     QualType ResultType;
14489     switch (Opc) {
14490     case BO_Assign:
14491       ResultType = LHSExpr->getType().getUnqualifiedType();
14492       break;
14493     case BO_LT:
14494     case BO_GT:
14495     case BO_LE:
14496     case BO_GE:
14497     case BO_EQ:
14498     case BO_NE:
14499     case BO_LAnd:
14500     case BO_LOr:
14501       // These operators have a fixed result type regardless of operands.
14502       ResultType = Context.IntTy;
14503       break;
14504     case BO_Comma:
14505       ResultType = RHSExpr->getType();
14506       break;
14507     default:
14508       ResultType = Context.DependentTy;
14509       break;
14510     }
14511     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14512                                   VK_RValue, OK_Ordinary, OpLoc,
14513                                   CurFPFeatureOverrides());
14514   }
14515 
14516   // Build a built-in binary operation.
14517   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14518 }
14519 
14520 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14521   if (T.isNull() || T->isDependentType())
14522     return false;
14523 
14524   if (!T->isPromotableIntegerType())
14525     return true;
14526 
14527   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14528 }
14529 
14530 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14531                                       UnaryOperatorKind Opc,
14532                                       Expr *InputExpr) {
14533   ExprResult Input = InputExpr;
14534   ExprValueKind VK = VK_RValue;
14535   ExprObjectKind OK = OK_Ordinary;
14536   QualType resultType;
14537   bool CanOverflow = false;
14538 
14539   bool ConvertHalfVec = false;
14540   if (getLangOpts().OpenCL) {
14541     QualType Ty = InputExpr->getType();
14542     // The only legal unary operation for atomics is '&'.
14543     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14544     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14545     // only with a builtin functions and therefore should be disallowed here.
14546         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14547         || Ty->isBlockPointerType())) {
14548       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14549                        << InputExpr->getType()
14550                        << Input.get()->getSourceRange());
14551     }
14552   }
14553 
14554   switch (Opc) {
14555   case UO_PreInc:
14556   case UO_PreDec:
14557   case UO_PostInc:
14558   case UO_PostDec:
14559     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14560                                                 OpLoc,
14561                                                 Opc == UO_PreInc ||
14562                                                 Opc == UO_PostInc,
14563                                                 Opc == UO_PreInc ||
14564                                                 Opc == UO_PreDec);
14565     CanOverflow = isOverflowingIntegerType(Context, resultType);
14566     break;
14567   case UO_AddrOf:
14568     resultType = CheckAddressOfOperand(Input, OpLoc);
14569     CheckAddressOfNoDeref(InputExpr);
14570     RecordModifiableNonNullParam(*this, InputExpr);
14571     break;
14572   case UO_Deref: {
14573     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14574     if (Input.isInvalid()) return ExprError();
14575     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14576     break;
14577   }
14578   case UO_Plus:
14579   case UO_Minus:
14580     CanOverflow = Opc == UO_Minus &&
14581                   isOverflowingIntegerType(Context, Input.get()->getType());
14582     Input = UsualUnaryConversions(Input.get());
14583     if (Input.isInvalid()) return ExprError();
14584     // Unary plus and minus require promoting an operand of half vector to a
14585     // float vector and truncating the result back to a half vector. For now, we
14586     // do this only when HalfArgsAndReturns is set (that is, when the target is
14587     // arm or arm64).
14588     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14589 
14590     // If the operand is a half vector, promote it to a float vector.
14591     if (ConvertHalfVec)
14592       Input = convertVector(Input.get(), Context.FloatTy, *this);
14593     resultType = Input.get()->getType();
14594     if (resultType->isDependentType())
14595       break;
14596     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14597       break;
14598     else if (resultType->isVectorType() &&
14599              // The z vector extensions don't allow + or - with bool vectors.
14600              (!Context.getLangOpts().ZVector ||
14601               resultType->castAs<VectorType>()->getVectorKind() !=
14602               VectorType::AltiVecBool))
14603       break;
14604     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14605              Opc == UO_Plus &&
14606              resultType->isPointerType())
14607       break;
14608 
14609     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14610       << resultType << Input.get()->getSourceRange());
14611 
14612   case UO_Not: // bitwise complement
14613     Input = UsualUnaryConversions(Input.get());
14614     if (Input.isInvalid())
14615       return ExprError();
14616     resultType = Input.get()->getType();
14617     if (resultType->isDependentType())
14618       break;
14619     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14620     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14621       // C99 does not support '~' for complex conjugation.
14622       Diag(OpLoc, diag::ext_integer_complement_complex)
14623           << resultType << Input.get()->getSourceRange();
14624     else if (resultType->hasIntegerRepresentation())
14625       break;
14626     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14627       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14628       // on vector float types.
14629       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14630       if (!T->isIntegerType())
14631         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14632                           << resultType << Input.get()->getSourceRange());
14633     } else {
14634       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14635                        << resultType << Input.get()->getSourceRange());
14636     }
14637     break;
14638 
14639   case UO_LNot: // logical negation
14640     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14641     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14642     if (Input.isInvalid()) return ExprError();
14643     resultType = Input.get()->getType();
14644 
14645     // Though we still have to promote half FP to float...
14646     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14647       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14648       resultType = Context.FloatTy;
14649     }
14650 
14651     if (resultType->isDependentType())
14652       break;
14653     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14654       // C99 6.5.3.3p1: ok, fallthrough;
14655       if (Context.getLangOpts().CPlusPlus) {
14656         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14657         // operand contextually converted to bool.
14658         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14659                                   ScalarTypeToBooleanCastKind(resultType));
14660       } else if (Context.getLangOpts().OpenCL &&
14661                  Context.getLangOpts().OpenCLVersion < 120) {
14662         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14663         // operate on scalar float types.
14664         if (!resultType->isIntegerType() && !resultType->isPointerType())
14665           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14666                            << resultType << Input.get()->getSourceRange());
14667       }
14668     } else if (resultType->isExtVectorType()) {
14669       if (Context.getLangOpts().OpenCL &&
14670           Context.getLangOpts().OpenCLVersion < 120 &&
14671           !Context.getLangOpts().OpenCLCPlusPlus) {
14672         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14673         // operate on vector float types.
14674         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14675         if (!T->isIntegerType())
14676           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14677                            << resultType << Input.get()->getSourceRange());
14678       }
14679       // Vector logical not returns the signed variant of the operand type.
14680       resultType = GetSignedVectorType(resultType);
14681       break;
14682     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14683       const VectorType *VTy = resultType->castAs<VectorType>();
14684       if (VTy->getVectorKind() != VectorType::GenericVector)
14685         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14686                          << resultType << Input.get()->getSourceRange());
14687 
14688       // Vector logical not returns the signed variant of the operand type.
14689       resultType = GetSignedVectorType(resultType);
14690       break;
14691     } else {
14692       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14693         << resultType << Input.get()->getSourceRange());
14694     }
14695 
14696     // LNot always has type int. C99 6.5.3.3p5.
14697     // In C++, it's bool. C++ 5.3.1p8
14698     resultType = Context.getLogicalOperationType();
14699     break;
14700   case UO_Real:
14701   case UO_Imag:
14702     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14703     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14704     // complex l-values to ordinary l-values and all other values to r-values.
14705     if (Input.isInvalid()) return ExprError();
14706     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14707       if (Input.get()->getValueKind() != VK_RValue &&
14708           Input.get()->getObjectKind() == OK_Ordinary)
14709         VK = Input.get()->getValueKind();
14710     } else if (!getLangOpts().CPlusPlus) {
14711       // In C, a volatile scalar is read by __imag. In C++, it is not.
14712       Input = DefaultLvalueConversion(Input.get());
14713     }
14714     break;
14715   case UO_Extension:
14716     resultType = Input.get()->getType();
14717     VK = Input.get()->getValueKind();
14718     OK = Input.get()->getObjectKind();
14719     break;
14720   case UO_Coawait:
14721     // It's unnecessary to represent the pass-through operator co_await in the
14722     // AST; just return the input expression instead.
14723     assert(!Input.get()->getType()->isDependentType() &&
14724                    "the co_await expression must be non-dependant before "
14725                    "building operator co_await");
14726     return Input;
14727   }
14728   if (resultType.isNull() || Input.isInvalid())
14729     return ExprError();
14730 
14731   // Check for array bounds violations in the operand of the UnaryOperator,
14732   // except for the '*' and '&' operators that have to be handled specially
14733   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14734   // that are explicitly defined as valid by the standard).
14735   if (Opc != UO_AddrOf && Opc != UO_Deref)
14736     CheckArrayAccess(Input.get());
14737 
14738   auto *UO =
14739       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14740                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14741 
14742   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14743       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14744       !isUnevaluatedContext())
14745     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14746 
14747   // Convert the result back to a half vector.
14748   if (ConvertHalfVec)
14749     return convertVector(UO, Context.HalfTy, *this);
14750   return UO;
14751 }
14752 
14753 /// Determine whether the given expression is a qualified member
14754 /// access expression, of a form that could be turned into a pointer to member
14755 /// with the address-of operator.
14756 bool Sema::isQualifiedMemberAccess(Expr *E) {
14757   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14758     if (!DRE->getQualifier())
14759       return false;
14760 
14761     ValueDecl *VD = DRE->getDecl();
14762     if (!VD->isCXXClassMember())
14763       return false;
14764 
14765     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14766       return true;
14767     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14768       return Method->isInstance();
14769 
14770     return false;
14771   }
14772 
14773   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14774     if (!ULE->getQualifier())
14775       return false;
14776 
14777     for (NamedDecl *D : ULE->decls()) {
14778       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14779         if (Method->isInstance())
14780           return true;
14781       } else {
14782         // Overload set does not contain methods.
14783         break;
14784       }
14785     }
14786 
14787     return false;
14788   }
14789 
14790   return false;
14791 }
14792 
14793 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14794                               UnaryOperatorKind Opc, Expr *Input) {
14795   // First things first: handle placeholders so that the
14796   // overloaded-operator check considers the right type.
14797   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14798     // Increment and decrement of pseudo-object references.
14799     if (pty->getKind() == BuiltinType::PseudoObject &&
14800         UnaryOperator::isIncrementDecrementOp(Opc))
14801       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14802 
14803     // extension is always a builtin operator.
14804     if (Opc == UO_Extension)
14805       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14806 
14807     // & gets special logic for several kinds of placeholder.
14808     // The builtin code knows what to do.
14809     if (Opc == UO_AddrOf &&
14810         (pty->getKind() == BuiltinType::Overload ||
14811          pty->getKind() == BuiltinType::UnknownAny ||
14812          pty->getKind() == BuiltinType::BoundMember))
14813       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14814 
14815     // Anything else needs to be handled now.
14816     ExprResult Result = CheckPlaceholderExpr(Input);
14817     if (Result.isInvalid()) return ExprError();
14818     Input = Result.get();
14819   }
14820 
14821   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14822       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14823       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14824     // Find all of the overloaded operators visible from this point.
14825     UnresolvedSet<16> Functions;
14826     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14827     if (S && OverOp != OO_None)
14828       LookupOverloadedOperatorName(OverOp, S, Functions);
14829 
14830     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14831   }
14832 
14833   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14834 }
14835 
14836 // Unary Operators.  'Tok' is the token for the operator.
14837 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14838                               tok::TokenKind Op, Expr *Input) {
14839   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14840 }
14841 
14842 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14843 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14844                                 LabelDecl *TheDecl) {
14845   TheDecl->markUsed(Context);
14846   // Create the AST node.  The address of a label always has type 'void*'.
14847   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14848                                      Context.getPointerType(Context.VoidTy));
14849 }
14850 
14851 void Sema::ActOnStartStmtExpr() {
14852   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14853 }
14854 
14855 void Sema::ActOnStmtExprError() {
14856   // Note that function is also called by TreeTransform when leaving a
14857   // StmtExpr scope without rebuilding anything.
14858 
14859   DiscardCleanupsInEvaluationContext();
14860   PopExpressionEvaluationContext();
14861 }
14862 
14863 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14864                                SourceLocation RPLoc) {
14865   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14866 }
14867 
14868 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14869                                SourceLocation RPLoc, unsigned TemplateDepth) {
14870   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14871   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14872 
14873   if (hasAnyUnrecoverableErrorsInThisFunction())
14874     DiscardCleanupsInEvaluationContext();
14875   assert(!Cleanup.exprNeedsCleanups() &&
14876          "cleanups within StmtExpr not correctly bound!");
14877   PopExpressionEvaluationContext();
14878 
14879   // FIXME: there are a variety of strange constraints to enforce here, for
14880   // example, it is not possible to goto into a stmt expression apparently.
14881   // More semantic analysis is needed.
14882 
14883   // If there are sub-stmts in the compound stmt, take the type of the last one
14884   // as the type of the stmtexpr.
14885   QualType Ty = Context.VoidTy;
14886   bool StmtExprMayBindToTemp = false;
14887   if (!Compound->body_empty()) {
14888     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14889     if (const auto *LastStmt =
14890             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14891       if (const Expr *Value = LastStmt->getExprStmt()) {
14892         StmtExprMayBindToTemp = true;
14893         Ty = Value->getType();
14894       }
14895     }
14896   }
14897 
14898   // FIXME: Check that expression type is complete/non-abstract; statement
14899   // expressions are not lvalues.
14900   Expr *ResStmtExpr =
14901       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14902   if (StmtExprMayBindToTemp)
14903     return MaybeBindToTemporary(ResStmtExpr);
14904   return ResStmtExpr;
14905 }
14906 
14907 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14908   if (ER.isInvalid())
14909     return ExprError();
14910 
14911   // Do function/array conversion on the last expression, but not
14912   // lvalue-to-rvalue.  However, initialize an unqualified type.
14913   ER = DefaultFunctionArrayConversion(ER.get());
14914   if (ER.isInvalid())
14915     return ExprError();
14916   Expr *E = ER.get();
14917 
14918   if (E->isTypeDependent())
14919     return E;
14920 
14921   // In ARC, if the final expression ends in a consume, splice
14922   // the consume out and bind it later.  In the alternate case
14923   // (when dealing with a retainable type), the result
14924   // initialization will create a produce.  In both cases the
14925   // result will be +1, and we'll need to balance that out with
14926   // a bind.
14927   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14928   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14929     return Cast->getSubExpr();
14930 
14931   // FIXME: Provide a better location for the initialization.
14932   return PerformCopyInitialization(
14933       InitializedEntity::InitializeStmtExprResult(
14934           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14935       SourceLocation(), E);
14936 }
14937 
14938 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14939                                       TypeSourceInfo *TInfo,
14940                                       ArrayRef<OffsetOfComponent> Components,
14941                                       SourceLocation RParenLoc) {
14942   QualType ArgTy = TInfo->getType();
14943   bool Dependent = ArgTy->isDependentType();
14944   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14945 
14946   // We must have at least one component that refers to the type, and the first
14947   // one is known to be a field designator.  Verify that the ArgTy represents
14948   // a struct/union/class.
14949   if (!Dependent && !ArgTy->isRecordType())
14950     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14951                        << ArgTy << TypeRange);
14952 
14953   // Type must be complete per C99 7.17p3 because a declaring a variable
14954   // with an incomplete type would be ill-formed.
14955   if (!Dependent
14956       && RequireCompleteType(BuiltinLoc, ArgTy,
14957                              diag::err_offsetof_incomplete_type, TypeRange))
14958     return ExprError();
14959 
14960   bool DidWarnAboutNonPOD = false;
14961   QualType CurrentType = ArgTy;
14962   SmallVector<OffsetOfNode, 4> Comps;
14963   SmallVector<Expr*, 4> Exprs;
14964   for (const OffsetOfComponent &OC : Components) {
14965     if (OC.isBrackets) {
14966       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14967       if (!CurrentType->isDependentType()) {
14968         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14969         if(!AT)
14970           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14971                            << CurrentType);
14972         CurrentType = AT->getElementType();
14973       } else
14974         CurrentType = Context.DependentTy;
14975 
14976       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14977       if (IdxRval.isInvalid())
14978         return ExprError();
14979       Expr *Idx = IdxRval.get();
14980 
14981       // The expression must be an integral expression.
14982       // FIXME: An integral constant expression?
14983       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14984           !Idx->getType()->isIntegerType())
14985         return ExprError(
14986             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14987             << Idx->getSourceRange());
14988 
14989       // Record this array index.
14990       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14991       Exprs.push_back(Idx);
14992       continue;
14993     }
14994 
14995     // Offset of a field.
14996     if (CurrentType->isDependentType()) {
14997       // We have the offset of a field, but we can't look into the dependent
14998       // type. Just record the identifier of the field.
14999       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15000       CurrentType = Context.DependentTy;
15001       continue;
15002     }
15003 
15004     // We need to have a complete type to look into.
15005     if (RequireCompleteType(OC.LocStart, CurrentType,
15006                             diag::err_offsetof_incomplete_type))
15007       return ExprError();
15008 
15009     // Look for the designated field.
15010     const RecordType *RC = CurrentType->getAs<RecordType>();
15011     if (!RC)
15012       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15013                        << CurrentType);
15014     RecordDecl *RD = RC->getDecl();
15015 
15016     // C++ [lib.support.types]p5:
15017     //   The macro offsetof accepts a restricted set of type arguments in this
15018     //   International Standard. type shall be a POD structure or a POD union
15019     //   (clause 9).
15020     // C++11 [support.types]p4:
15021     //   If type is not a standard-layout class (Clause 9), the results are
15022     //   undefined.
15023     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15024       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15025       unsigned DiagID =
15026         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15027                             : diag::ext_offsetof_non_pod_type;
15028 
15029       if (!IsSafe && !DidWarnAboutNonPOD &&
15030           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15031                               PDiag(DiagID)
15032                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15033                               << CurrentType))
15034         DidWarnAboutNonPOD = true;
15035     }
15036 
15037     // Look for the field.
15038     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15039     LookupQualifiedName(R, RD);
15040     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15041     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15042     if (!MemberDecl) {
15043       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15044         MemberDecl = IndirectMemberDecl->getAnonField();
15045     }
15046 
15047     if (!MemberDecl)
15048       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15049                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15050                                                               OC.LocEnd));
15051 
15052     // C99 7.17p3:
15053     //   (If the specified member is a bit-field, the behavior is undefined.)
15054     //
15055     // We diagnose this as an error.
15056     if (MemberDecl->isBitField()) {
15057       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15058         << MemberDecl->getDeclName()
15059         << SourceRange(BuiltinLoc, RParenLoc);
15060       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15061       return ExprError();
15062     }
15063 
15064     RecordDecl *Parent = MemberDecl->getParent();
15065     if (IndirectMemberDecl)
15066       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15067 
15068     // If the member was found in a base class, introduce OffsetOfNodes for
15069     // the base class indirections.
15070     CXXBasePaths Paths;
15071     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15072                       Paths)) {
15073       if (Paths.getDetectedVirtual()) {
15074         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15075           << MemberDecl->getDeclName()
15076           << SourceRange(BuiltinLoc, RParenLoc);
15077         return ExprError();
15078       }
15079 
15080       CXXBasePath &Path = Paths.front();
15081       for (const CXXBasePathElement &B : Path)
15082         Comps.push_back(OffsetOfNode(B.Base));
15083     }
15084 
15085     if (IndirectMemberDecl) {
15086       for (auto *FI : IndirectMemberDecl->chain()) {
15087         assert(isa<FieldDecl>(FI));
15088         Comps.push_back(OffsetOfNode(OC.LocStart,
15089                                      cast<FieldDecl>(FI), OC.LocEnd));
15090       }
15091     } else
15092       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15093 
15094     CurrentType = MemberDecl->getType().getNonReferenceType();
15095   }
15096 
15097   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15098                               Comps, Exprs, RParenLoc);
15099 }
15100 
15101 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15102                                       SourceLocation BuiltinLoc,
15103                                       SourceLocation TypeLoc,
15104                                       ParsedType ParsedArgTy,
15105                                       ArrayRef<OffsetOfComponent> Components,
15106                                       SourceLocation RParenLoc) {
15107 
15108   TypeSourceInfo *ArgTInfo;
15109   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15110   if (ArgTy.isNull())
15111     return ExprError();
15112 
15113   if (!ArgTInfo)
15114     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15115 
15116   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15117 }
15118 
15119 
15120 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15121                                  Expr *CondExpr,
15122                                  Expr *LHSExpr, Expr *RHSExpr,
15123                                  SourceLocation RPLoc) {
15124   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15125 
15126   ExprValueKind VK = VK_RValue;
15127   ExprObjectKind OK = OK_Ordinary;
15128   QualType resType;
15129   bool CondIsTrue = false;
15130   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15131     resType = Context.DependentTy;
15132   } else {
15133     // The conditional expression is required to be a constant expression.
15134     llvm::APSInt condEval(32);
15135     ExprResult CondICE = VerifyIntegerConstantExpression(
15136         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15137     if (CondICE.isInvalid())
15138       return ExprError();
15139     CondExpr = CondICE.get();
15140     CondIsTrue = condEval.getZExtValue();
15141 
15142     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15143     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15144 
15145     resType = ActiveExpr->getType();
15146     VK = ActiveExpr->getValueKind();
15147     OK = ActiveExpr->getObjectKind();
15148   }
15149 
15150   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15151                                   resType, VK, OK, RPLoc, CondIsTrue);
15152 }
15153 
15154 //===----------------------------------------------------------------------===//
15155 // Clang Extensions.
15156 //===----------------------------------------------------------------------===//
15157 
15158 /// ActOnBlockStart - This callback is invoked when a block literal is started.
15159 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15160   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15161 
15162   if (LangOpts.CPlusPlus) {
15163     MangleNumberingContext *MCtx;
15164     Decl *ManglingContextDecl;
15165     std::tie(MCtx, ManglingContextDecl) =
15166         getCurrentMangleNumberContext(Block->getDeclContext());
15167     if (MCtx) {
15168       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15169       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15170     }
15171   }
15172 
15173   PushBlockScope(CurScope, Block);
15174   CurContext->addDecl(Block);
15175   if (CurScope)
15176     PushDeclContext(CurScope, Block);
15177   else
15178     CurContext = Block;
15179 
15180   getCurBlock()->HasImplicitReturnType = true;
15181 
15182   // Enter a new evaluation context to insulate the block from any
15183   // cleanups from the enclosing full-expression.
15184   PushExpressionEvaluationContext(
15185       ExpressionEvaluationContext::PotentiallyEvaluated);
15186 }
15187 
15188 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15189                                Scope *CurScope) {
15190   assert(ParamInfo.getIdentifier() == nullptr &&
15191          "block-id should have no identifier!");
15192   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15193   BlockScopeInfo *CurBlock = getCurBlock();
15194 
15195   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15196   QualType T = Sig->getType();
15197 
15198   // FIXME: We should allow unexpanded parameter packs here, but that would,
15199   // in turn, make the block expression contain unexpanded parameter packs.
15200   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15201     // Drop the parameters.
15202     FunctionProtoType::ExtProtoInfo EPI;
15203     EPI.HasTrailingReturn = false;
15204     EPI.TypeQuals.addConst();
15205     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15206     Sig = Context.getTrivialTypeSourceInfo(T);
15207   }
15208 
15209   // GetTypeForDeclarator always produces a function type for a block
15210   // literal signature.  Furthermore, it is always a FunctionProtoType
15211   // unless the function was written with a typedef.
15212   assert(T->isFunctionType() &&
15213          "GetTypeForDeclarator made a non-function block signature");
15214 
15215   // Look for an explicit signature in that function type.
15216   FunctionProtoTypeLoc ExplicitSignature;
15217 
15218   if ((ExplicitSignature = Sig->getTypeLoc()
15219                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15220 
15221     // Check whether that explicit signature was synthesized by
15222     // GetTypeForDeclarator.  If so, don't save that as part of the
15223     // written signature.
15224     if (ExplicitSignature.getLocalRangeBegin() ==
15225         ExplicitSignature.getLocalRangeEnd()) {
15226       // This would be much cheaper if we stored TypeLocs instead of
15227       // TypeSourceInfos.
15228       TypeLoc Result = ExplicitSignature.getReturnLoc();
15229       unsigned Size = Result.getFullDataSize();
15230       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15231       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15232 
15233       ExplicitSignature = FunctionProtoTypeLoc();
15234     }
15235   }
15236 
15237   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15238   CurBlock->FunctionType = T;
15239 
15240   const auto *Fn = T->castAs<FunctionType>();
15241   QualType RetTy = Fn->getReturnType();
15242   bool isVariadic =
15243       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15244 
15245   CurBlock->TheDecl->setIsVariadic(isVariadic);
15246 
15247   // Context.DependentTy is used as a placeholder for a missing block
15248   // return type.  TODO:  what should we do with declarators like:
15249   //   ^ * { ... }
15250   // If the answer is "apply template argument deduction"....
15251   if (RetTy != Context.DependentTy) {
15252     CurBlock->ReturnType = RetTy;
15253     CurBlock->TheDecl->setBlockMissingReturnType(false);
15254     CurBlock->HasImplicitReturnType = false;
15255   }
15256 
15257   // Push block parameters from the declarator if we had them.
15258   SmallVector<ParmVarDecl*, 8> Params;
15259   if (ExplicitSignature) {
15260     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15261       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15262       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15263           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15264         // Diagnose this as an extension in C17 and earlier.
15265         if (!getLangOpts().C2x)
15266           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15267       }
15268       Params.push_back(Param);
15269     }
15270 
15271   // Fake up parameter variables if we have a typedef, like
15272   //   ^ fntype { ... }
15273   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15274     for (const auto &I : Fn->param_types()) {
15275       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15276           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15277       Params.push_back(Param);
15278     }
15279   }
15280 
15281   // Set the parameters on the block decl.
15282   if (!Params.empty()) {
15283     CurBlock->TheDecl->setParams(Params);
15284     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15285                              /*CheckParameterNames=*/false);
15286   }
15287 
15288   // Finally we can process decl attributes.
15289   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15290 
15291   // Put the parameter variables in scope.
15292   for (auto AI : CurBlock->TheDecl->parameters()) {
15293     AI->setOwningFunction(CurBlock->TheDecl);
15294 
15295     // If this has an identifier, add it to the scope stack.
15296     if (AI->getIdentifier()) {
15297       CheckShadow(CurBlock->TheScope, AI);
15298 
15299       PushOnScopeChains(AI, CurBlock->TheScope);
15300     }
15301   }
15302 }
15303 
15304 /// ActOnBlockError - If there is an error parsing a block, this callback
15305 /// is invoked to pop the information about the block from the action impl.
15306 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15307   // Leave the expression-evaluation context.
15308   DiscardCleanupsInEvaluationContext();
15309   PopExpressionEvaluationContext();
15310 
15311   // Pop off CurBlock, handle nested blocks.
15312   PopDeclContext();
15313   PopFunctionScopeInfo();
15314 }
15315 
15316 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15317 /// literal was successfully completed.  ^(int x){...}
15318 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15319                                     Stmt *Body, Scope *CurScope) {
15320   // If blocks are disabled, emit an error.
15321   if (!LangOpts.Blocks)
15322     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15323 
15324   // Leave the expression-evaluation context.
15325   if (hasAnyUnrecoverableErrorsInThisFunction())
15326     DiscardCleanupsInEvaluationContext();
15327   assert(!Cleanup.exprNeedsCleanups() &&
15328          "cleanups within block not correctly bound!");
15329   PopExpressionEvaluationContext();
15330 
15331   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15332   BlockDecl *BD = BSI->TheDecl;
15333 
15334   if (BSI->HasImplicitReturnType)
15335     deduceClosureReturnType(*BSI);
15336 
15337   QualType RetTy = Context.VoidTy;
15338   if (!BSI->ReturnType.isNull())
15339     RetTy = BSI->ReturnType;
15340 
15341   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15342   QualType BlockTy;
15343 
15344   // If the user wrote a function type in some form, try to use that.
15345   if (!BSI->FunctionType.isNull()) {
15346     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15347 
15348     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15349     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15350 
15351     // Turn protoless block types into nullary block types.
15352     if (isa<FunctionNoProtoType>(FTy)) {
15353       FunctionProtoType::ExtProtoInfo EPI;
15354       EPI.ExtInfo = Ext;
15355       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15356 
15357     // Otherwise, if we don't need to change anything about the function type,
15358     // preserve its sugar structure.
15359     } else if (FTy->getReturnType() == RetTy &&
15360                (!NoReturn || FTy->getNoReturnAttr())) {
15361       BlockTy = BSI->FunctionType;
15362 
15363     // Otherwise, make the minimal modifications to the function type.
15364     } else {
15365       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15366       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15367       EPI.TypeQuals = Qualifiers();
15368       EPI.ExtInfo = Ext;
15369       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15370     }
15371 
15372   // If we don't have a function type, just build one from nothing.
15373   } else {
15374     FunctionProtoType::ExtProtoInfo EPI;
15375     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15376     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15377   }
15378 
15379   DiagnoseUnusedParameters(BD->parameters());
15380   BlockTy = Context.getBlockPointerType(BlockTy);
15381 
15382   // If needed, diagnose invalid gotos and switches in the block.
15383   if (getCurFunction()->NeedsScopeChecking() &&
15384       !PP.isCodeCompletionEnabled())
15385     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15386 
15387   BD->setBody(cast<CompoundStmt>(Body));
15388 
15389   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15390     DiagnoseUnguardedAvailabilityViolations(BD);
15391 
15392   // Try to apply the named return value optimization. We have to check again
15393   // if we can do this, though, because blocks keep return statements around
15394   // to deduce an implicit return type.
15395   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15396       !BD->isDependentContext())
15397     computeNRVO(Body, BSI);
15398 
15399   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15400       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15401     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15402                           NTCUK_Destruct|NTCUK_Copy);
15403 
15404   PopDeclContext();
15405 
15406   // Set the captured variables on the block.
15407   SmallVector<BlockDecl::Capture, 4> Captures;
15408   for (Capture &Cap : BSI->Captures) {
15409     if (Cap.isInvalid() || Cap.isThisCapture())
15410       continue;
15411 
15412     VarDecl *Var = Cap.getVariable();
15413     Expr *CopyExpr = nullptr;
15414     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15415       if (const RecordType *Record =
15416               Cap.getCaptureType()->getAs<RecordType>()) {
15417         // The capture logic needs the destructor, so make sure we mark it.
15418         // Usually this is unnecessary because most local variables have
15419         // their destructors marked at declaration time, but parameters are
15420         // an exception because it's technically only the call site that
15421         // actually requires the destructor.
15422         if (isa<ParmVarDecl>(Var))
15423           FinalizeVarWithDestructor(Var, Record);
15424 
15425         // Enter a separate potentially-evaluated context while building block
15426         // initializers to isolate their cleanups from those of the block
15427         // itself.
15428         // FIXME: Is this appropriate even when the block itself occurs in an
15429         // unevaluated operand?
15430         EnterExpressionEvaluationContext EvalContext(
15431             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15432 
15433         SourceLocation Loc = Cap.getLocation();
15434 
15435         ExprResult Result = BuildDeclarationNameExpr(
15436             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15437 
15438         // According to the blocks spec, the capture of a variable from
15439         // the stack requires a const copy constructor.  This is not true
15440         // of the copy/move done to move a __block variable to the heap.
15441         if (!Result.isInvalid() &&
15442             !Result.get()->getType().isConstQualified()) {
15443           Result = ImpCastExprToType(Result.get(),
15444                                      Result.get()->getType().withConst(),
15445                                      CK_NoOp, VK_LValue);
15446         }
15447 
15448         if (!Result.isInvalid()) {
15449           Result = PerformCopyInitialization(
15450               InitializedEntity::InitializeBlock(Var->getLocation(),
15451                                                  Cap.getCaptureType(), false),
15452               Loc, Result.get());
15453         }
15454 
15455         // Build a full-expression copy expression if initialization
15456         // succeeded and used a non-trivial constructor.  Recover from
15457         // errors by pretending that the copy isn't necessary.
15458         if (!Result.isInvalid() &&
15459             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15460                 ->isTrivial()) {
15461           Result = MaybeCreateExprWithCleanups(Result);
15462           CopyExpr = Result.get();
15463         }
15464       }
15465     }
15466 
15467     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15468                               CopyExpr);
15469     Captures.push_back(NewCap);
15470   }
15471   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15472 
15473   // Pop the block scope now but keep it alive to the end of this function.
15474   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15475   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15476 
15477   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15478 
15479   // If the block isn't obviously global, i.e. it captures anything at
15480   // all, then we need to do a few things in the surrounding context:
15481   if (Result->getBlockDecl()->hasCaptures()) {
15482     // First, this expression has a new cleanup object.
15483     ExprCleanupObjects.push_back(Result->getBlockDecl());
15484     Cleanup.setExprNeedsCleanups(true);
15485 
15486     // It also gets a branch-protected scope if any of the captured
15487     // variables needs destruction.
15488     for (const auto &CI : Result->getBlockDecl()->captures()) {
15489       const VarDecl *var = CI.getVariable();
15490       if (var->getType().isDestructedType() != QualType::DK_none) {
15491         setFunctionHasBranchProtectedScope();
15492         break;
15493       }
15494     }
15495   }
15496 
15497   if (getCurFunction())
15498     getCurFunction()->addBlock(BD);
15499 
15500   return Result;
15501 }
15502 
15503 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15504                             SourceLocation RPLoc) {
15505   TypeSourceInfo *TInfo;
15506   GetTypeFromParser(Ty, &TInfo);
15507   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15508 }
15509 
15510 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15511                                 Expr *E, TypeSourceInfo *TInfo,
15512                                 SourceLocation RPLoc) {
15513   Expr *OrigExpr = E;
15514   bool IsMS = false;
15515 
15516   // CUDA device code does not support varargs.
15517   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15518     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15519       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15520       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15521         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15522     }
15523   }
15524 
15525   // NVPTX does not support va_arg expression.
15526   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15527       Context.getTargetInfo().getTriple().isNVPTX())
15528     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15529 
15530   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15531   // as Microsoft ABI on an actual Microsoft platform, where
15532   // __builtin_ms_va_list and __builtin_va_list are the same.)
15533   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15534       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15535     QualType MSVaListType = Context.getBuiltinMSVaListType();
15536     if (Context.hasSameType(MSVaListType, E->getType())) {
15537       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15538         return ExprError();
15539       IsMS = true;
15540     }
15541   }
15542 
15543   // Get the va_list type
15544   QualType VaListType = Context.getBuiltinVaListType();
15545   if (!IsMS) {
15546     if (VaListType->isArrayType()) {
15547       // Deal with implicit array decay; for example, on x86-64,
15548       // va_list is an array, but it's supposed to decay to
15549       // a pointer for va_arg.
15550       VaListType = Context.getArrayDecayedType(VaListType);
15551       // Make sure the input expression also decays appropriately.
15552       ExprResult Result = UsualUnaryConversions(E);
15553       if (Result.isInvalid())
15554         return ExprError();
15555       E = Result.get();
15556     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15557       // If va_list is a record type and we are compiling in C++ mode,
15558       // check the argument using reference binding.
15559       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15560           Context, Context.getLValueReferenceType(VaListType), false);
15561       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15562       if (Init.isInvalid())
15563         return ExprError();
15564       E = Init.getAs<Expr>();
15565     } else {
15566       // Otherwise, the va_list argument must be an l-value because
15567       // it is modified by va_arg.
15568       if (!E->isTypeDependent() &&
15569           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15570         return ExprError();
15571     }
15572   }
15573 
15574   if (!IsMS && !E->isTypeDependent() &&
15575       !Context.hasSameType(VaListType, E->getType()))
15576     return ExprError(
15577         Diag(E->getBeginLoc(),
15578              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15579         << OrigExpr->getType() << E->getSourceRange());
15580 
15581   if (!TInfo->getType()->isDependentType()) {
15582     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15583                             diag::err_second_parameter_to_va_arg_incomplete,
15584                             TInfo->getTypeLoc()))
15585       return ExprError();
15586 
15587     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15588                                TInfo->getType(),
15589                                diag::err_second_parameter_to_va_arg_abstract,
15590                                TInfo->getTypeLoc()))
15591       return ExprError();
15592 
15593     if (!TInfo->getType().isPODType(Context)) {
15594       Diag(TInfo->getTypeLoc().getBeginLoc(),
15595            TInfo->getType()->isObjCLifetimeType()
15596              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15597              : diag::warn_second_parameter_to_va_arg_not_pod)
15598         << TInfo->getType()
15599         << TInfo->getTypeLoc().getSourceRange();
15600     }
15601 
15602     // Check for va_arg where arguments of the given type will be promoted
15603     // (i.e. this va_arg is guaranteed to have undefined behavior).
15604     QualType PromoteType;
15605     if (TInfo->getType()->isPromotableIntegerType()) {
15606       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15607       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15608         PromoteType = QualType();
15609     }
15610     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15611       PromoteType = Context.DoubleTy;
15612     if (!PromoteType.isNull())
15613       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15614                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15615                           << TInfo->getType()
15616                           << PromoteType
15617                           << TInfo->getTypeLoc().getSourceRange());
15618   }
15619 
15620   QualType T = TInfo->getType().getNonLValueExprType(Context);
15621   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15622 }
15623 
15624 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15625   // The type of __null will be int or long, depending on the size of
15626   // pointers on the target.
15627   QualType Ty;
15628   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15629   if (pw == Context.getTargetInfo().getIntWidth())
15630     Ty = Context.IntTy;
15631   else if (pw == Context.getTargetInfo().getLongWidth())
15632     Ty = Context.LongTy;
15633   else if (pw == Context.getTargetInfo().getLongLongWidth())
15634     Ty = Context.LongLongTy;
15635   else {
15636     llvm_unreachable("I don't know size of pointer!");
15637   }
15638 
15639   return new (Context) GNUNullExpr(Ty, TokenLoc);
15640 }
15641 
15642 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15643                                     SourceLocation BuiltinLoc,
15644                                     SourceLocation RPLoc) {
15645   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15646 }
15647 
15648 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15649                                     SourceLocation BuiltinLoc,
15650                                     SourceLocation RPLoc,
15651                                     DeclContext *ParentContext) {
15652   return new (Context)
15653       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15654 }
15655 
15656 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15657                                         bool Diagnose) {
15658   if (!getLangOpts().ObjC)
15659     return false;
15660 
15661   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15662   if (!PT)
15663     return false;
15664   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15665 
15666   // Ignore any parens, implicit casts (should only be
15667   // array-to-pointer decays), and not-so-opaque values.  The last is
15668   // important for making this trigger for property assignments.
15669   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15670   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15671     if (OV->getSourceExpr())
15672       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15673 
15674   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15675     if (!PT->isObjCIdType() &&
15676         !(ID && ID->getIdentifier()->isStr("NSString")))
15677       return false;
15678     if (!SL->isAscii())
15679       return false;
15680 
15681     if (Diagnose) {
15682       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15683           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15684       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15685     }
15686     return true;
15687   }
15688 
15689   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15690       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15691       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15692       !SrcExpr->isNullPointerConstant(
15693           getASTContext(), Expr::NPC_NeverValueDependent)) {
15694     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15695       return false;
15696     if (Diagnose) {
15697       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15698           << /*number*/1
15699           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15700       Expr *NumLit =
15701           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15702       if (NumLit)
15703         Exp = NumLit;
15704     }
15705     return true;
15706   }
15707 
15708   return false;
15709 }
15710 
15711 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15712                                               const Expr *SrcExpr) {
15713   if (!DstType->isFunctionPointerType() ||
15714       !SrcExpr->getType()->isFunctionType())
15715     return false;
15716 
15717   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15718   if (!DRE)
15719     return false;
15720 
15721   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15722   if (!FD)
15723     return false;
15724 
15725   return !S.checkAddressOfFunctionIsAvailable(FD,
15726                                               /*Complain=*/true,
15727                                               SrcExpr->getBeginLoc());
15728 }
15729 
15730 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15731                                     SourceLocation Loc,
15732                                     QualType DstType, QualType SrcType,
15733                                     Expr *SrcExpr, AssignmentAction Action,
15734                                     bool *Complained) {
15735   if (Complained)
15736     *Complained = false;
15737 
15738   // Decode the result (notice that AST's are still created for extensions).
15739   bool CheckInferredResultType = false;
15740   bool isInvalid = false;
15741   unsigned DiagKind = 0;
15742   ConversionFixItGenerator ConvHints;
15743   bool MayHaveConvFixit = false;
15744   bool MayHaveFunctionDiff = false;
15745   const ObjCInterfaceDecl *IFace = nullptr;
15746   const ObjCProtocolDecl *PDecl = nullptr;
15747 
15748   switch (ConvTy) {
15749   case Compatible:
15750       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15751       return false;
15752 
15753   case PointerToInt:
15754     if (getLangOpts().CPlusPlus) {
15755       DiagKind = diag::err_typecheck_convert_pointer_int;
15756       isInvalid = true;
15757     } else {
15758       DiagKind = diag::ext_typecheck_convert_pointer_int;
15759     }
15760     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15761     MayHaveConvFixit = true;
15762     break;
15763   case IntToPointer:
15764     if (getLangOpts().CPlusPlus) {
15765       DiagKind = diag::err_typecheck_convert_int_pointer;
15766       isInvalid = true;
15767     } else {
15768       DiagKind = diag::ext_typecheck_convert_int_pointer;
15769     }
15770     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15771     MayHaveConvFixit = true;
15772     break;
15773   case IncompatibleFunctionPointer:
15774     if (getLangOpts().CPlusPlus) {
15775       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15776       isInvalid = true;
15777     } else {
15778       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15779     }
15780     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15781     MayHaveConvFixit = true;
15782     break;
15783   case IncompatiblePointer:
15784     if (Action == AA_Passing_CFAudited) {
15785       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15786     } else if (getLangOpts().CPlusPlus) {
15787       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15788       isInvalid = true;
15789     } else {
15790       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15791     }
15792     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15793       SrcType->isObjCObjectPointerType();
15794     if (!CheckInferredResultType) {
15795       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15796     } else if (CheckInferredResultType) {
15797       SrcType = SrcType.getUnqualifiedType();
15798       DstType = DstType.getUnqualifiedType();
15799     }
15800     MayHaveConvFixit = true;
15801     break;
15802   case IncompatiblePointerSign:
15803     if (getLangOpts().CPlusPlus) {
15804       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15805       isInvalid = true;
15806     } else {
15807       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15808     }
15809     break;
15810   case FunctionVoidPointer:
15811     if (getLangOpts().CPlusPlus) {
15812       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15813       isInvalid = true;
15814     } else {
15815       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15816     }
15817     break;
15818   case IncompatiblePointerDiscardsQualifiers: {
15819     // Perform array-to-pointer decay if necessary.
15820     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15821 
15822     isInvalid = true;
15823 
15824     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15825     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15826     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15827       DiagKind = diag::err_typecheck_incompatible_address_space;
15828       break;
15829 
15830     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15831       DiagKind = diag::err_typecheck_incompatible_ownership;
15832       break;
15833     }
15834 
15835     llvm_unreachable("unknown error case for discarding qualifiers!");
15836     // fallthrough
15837   }
15838   case CompatiblePointerDiscardsQualifiers:
15839     // If the qualifiers lost were because we were applying the
15840     // (deprecated) C++ conversion from a string literal to a char*
15841     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15842     // Ideally, this check would be performed in
15843     // checkPointerTypesForAssignment. However, that would require a
15844     // bit of refactoring (so that the second argument is an
15845     // expression, rather than a type), which should be done as part
15846     // of a larger effort to fix checkPointerTypesForAssignment for
15847     // C++ semantics.
15848     if (getLangOpts().CPlusPlus &&
15849         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15850       return false;
15851     if (getLangOpts().CPlusPlus) {
15852       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15853       isInvalid = true;
15854     } else {
15855       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15856     }
15857 
15858     break;
15859   case IncompatibleNestedPointerQualifiers:
15860     if (getLangOpts().CPlusPlus) {
15861       isInvalid = true;
15862       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15863     } else {
15864       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15865     }
15866     break;
15867   case IncompatibleNestedPointerAddressSpaceMismatch:
15868     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15869     isInvalid = true;
15870     break;
15871   case IntToBlockPointer:
15872     DiagKind = diag::err_int_to_block_pointer;
15873     isInvalid = true;
15874     break;
15875   case IncompatibleBlockPointer:
15876     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15877     isInvalid = true;
15878     break;
15879   case IncompatibleObjCQualifiedId: {
15880     if (SrcType->isObjCQualifiedIdType()) {
15881       const ObjCObjectPointerType *srcOPT =
15882                 SrcType->castAs<ObjCObjectPointerType>();
15883       for (auto *srcProto : srcOPT->quals()) {
15884         PDecl = srcProto;
15885         break;
15886       }
15887       if (const ObjCInterfaceType *IFaceT =
15888             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15889         IFace = IFaceT->getDecl();
15890     }
15891     else if (DstType->isObjCQualifiedIdType()) {
15892       const ObjCObjectPointerType *dstOPT =
15893         DstType->castAs<ObjCObjectPointerType>();
15894       for (auto *dstProto : dstOPT->quals()) {
15895         PDecl = dstProto;
15896         break;
15897       }
15898       if (const ObjCInterfaceType *IFaceT =
15899             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15900         IFace = IFaceT->getDecl();
15901     }
15902     if (getLangOpts().CPlusPlus) {
15903       DiagKind = diag::err_incompatible_qualified_id;
15904       isInvalid = true;
15905     } else {
15906       DiagKind = diag::warn_incompatible_qualified_id;
15907     }
15908     break;
15909   }
15910   case IncompatibleVectors:
15911     if (getLangOpts().CPlusPlus) {
15912       DiagKind = diag::err_incompatible_vectors;
15913       isInvalid = true;
15914     } else {
15915       DiagKind = diag::warn_incompatible_vectors;
15916     }
15917     break;
15918   case IncompatibleObjCWeakRef:
15919     DiagKind = diag::err_arc_weak_unavailable_assign;
15920     isInvalid = true;
15921     break;
15922   case Incompatible:
15923     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15924       if (Complained)
15925         *Complained = true;
15926       return true;
15927     }
15928 
15929     DiagKind = diag::err_typecheck_convert_incompatible;
15930     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15931     MayHaveConvFixit = true;
15932     isInvalid = true;
15933     MayHaveFunctionDiff = true;
15934     break;
15935   }
15936 
15937   QualType FirstType, SecondType;
15938   switch (Action) {
15939   case AA_Assigning:
15940   case AA_Initializing:
15941     // The destination type comes first.
15942     FirstType = DstType;
15943     SecondType = SrcType;
15944     break;
15945 
15946   case AA_Returning:
15947   case AA_Passing:
15948   case AA_Passing_CFAudited:
15949   case AA_Converting:
15950   case AA_Sending:
15951   case AA_Casting:
15952     // The source type comes first.
15953     FirstType = SrcType;
15954     SecondType = DstType;
15955     break;
15956   }
15957 
15958   PartialDiagnostic FDiag = PDiag(DiagKind);
15959   if (Action == AA_Passing_CFAudited)
15960     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15961   else
15962     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15963 
15964   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
15965       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
15966     auto isPlainChar = [](const clang::Type *Type) {
15967       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
15968              Type->isSpecificBuiltinType(BuiltinType::Char_U);
15969     };
15970     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
15971               isPlainChar(SecondType->getPointeeOrArrayElementType()));
15972   }
15973 
15974   // If we can fix the conversion, suggest the FixIts.
15975   if (!ConvHints.isNull()) {
15976     for (FixItHint &H : ConvHints.Hints)
15977       FDiag << H;
15978   }
15979 
15980   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15981 
15982   if (MayHaveFunctionDiff)
15983     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15984 
15985   Diag(Loc, FDiag);
15986   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15987        DiagKind == diag::err_incompatible_qualified_id) &&
15988       PDecl && IFace && !IFace->hasDefinition())
15989     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15990         << IFace << PDecl;
15991 
15992   if (SecondType == Context.OverloadTy)
15993     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15994                               FirstType, /*TakingAddress=*/true);
15995 
15996   if (CheckInferredResultType)
15997     EmitRelatedResultTypeNote(SrcExpr);
15998 
15999   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16000     EmitRelatedResultTypeNoteForReturn(DstType);
16001 
16002   if (Complained)
16003     *Complained = true;
16004   return isInvalid;
16005 }
16006 
16007 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16008                                                  llvm::APSInt *Result,
16009                                                  AllowFoldKind CanFold) {
16010   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16011   public:
16012     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16013                                              QualType T) override {
16014       return S.Diag(Loc, diag::err_ice_not_integral)
16015              << T << S.LangOpts.CPlusPlus;
16016     }
16017     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16018       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16019     }
16020   } Diagnoser;
16021 
16022   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16023 }
16024 
16025 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16026                                                  llvm::APSInt *Result,
16027                                                  unsigned DiagID,
16028                                                  AllowFoldKind CanFold) {
16029   class IDDiagnoser : public VerifyICEDiagnoser {
16030     unsigned DiagID;
16031 
16032   public:
16033     IDDiagnoser(unsigned DiagID)
16034       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16035 
16036     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16037       return S.Diag(Loc, DiagID);
16038     }
16039   } Diagnoser(DiagID);
16040 
16041   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16042 }
16043 
16044 Sema::SemaDiagnosticBuilder
16045 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16046                                              QualType T) {
16047   return diagnoseNotICE(S, Loc);
16048 }
16049 
16050 Sema::SemaDiagnosticBuilder
16051 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16052   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16053 }
16054 
16055 ExprResult
16056 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16057                                       VerifyICEDiagnoser &Diagnoser,
16058                                       AllowFoldKind CanFold) {
16059   SourceLocation DiagLoc = E->getBeginLoc();
16060 
16061   if (getLangOpts().CPlusPlus11) {
16062     // C++11 [expr.const]p5:
16063     //   If an expression of literal class type is used in a context where an
16064     //   integral constant expression is required, then that class type shall
16065     //   have a single non-explicit conversion function to an integral or
16066     //   unscoped enumeration type
16067     ExprResult Converted;
16068     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16069       VerifyICEDiagnoser &BaseDiagnoser;
16070     public:
16071       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16072           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16073                                 BaseDiagnoser.Suppress, true),
16074             BaseDiagnoser(BaseDiagnoser) {}
16075 
16076       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16077                                            QualType T) override {
16078         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16079       }
16080 
16081       SemaDiagnosticBuilder diagnoseIncomplete(
16082           Sema &S, SourceLocation Loc, QualType T) override {
16083         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16084       }
16085 
16086       SemaDiagnosticBuilder diagnoseExplicitConv(
16087           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16088         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16089       }
16090 
16091       SemaDiagnosticBuilder noteExplicitConv(
16092           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16093         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16094                  << ConvTy->isEnumeralType() << ConvTy;
16095       }
16096 
16097       SemaDiagnosticBuilder diagnoseAmbiguous(
16098           Sema &S, SourceLocation Loc, QualType T) override {
16099         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16100       }
16101 
16102       SemaDiagnosticBuilder noteAmbiguous(
16103           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16104         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16105                  << ConvTy->isEnumeralType() << ConvTy;
16106       }
16107 
16108       SemaDiagnosticBuilder diagnoseConversion(
16109           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16110         llvm_unreachable("conversion functions are permitted");
16111       }
16112     } ConvertDiagnoser(Diagnoser);
16113 
16114     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16115                                                     ConvertDiagnoser);
16116     if (Converted.isInvalid())
16117       return Converted;
16118     E = Converted.get();
16119     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16120       return ExprError();
16121   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16122     // An ICE must be of integral or unscoped enumeration type.
16123     if (!Diagnoser.Suppress)
16124       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16125           << E->getSourceRange();
16126     return ExprError();
16127   }
16128 
16129   ExprResult RValueExpr = DefaultLvalueConversion(E);
16130   if (RValueExpr.isInvalid())
16131     return ExprError();
16132 
16133   E = RValueExpr.get();
16134 
16135   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16136   // in the non-ICE case.
16137   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16138     if (Result)
16139       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16140     if (!isa<ConstantExpr>(E))
16141       E = ConstantExpr::Create(Context, E);
16142     return E;
16143   }
16144 
16145   Expr::EvalResult EvalResult;
16146   SmallVector<PartialDiagnosticAt, 8> Notes;
16147   EvalResult.Diag = &Notes;
16148 
16149   // Try to evaluate the expression, and produce diagnostics explaining why it's
16150   // not a constant expression as a side-effect.
16151   bool Folded =
16152       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16153       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16154 
16155   if (!isa<ConstantExpr>(E))
16156     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16157 
16158   // In C++11, we can rely on diagnostics being produced for any expression
16159   // which is not a constant expression. If no diagnostics were produced, then
16160   // this is a constant expression.
16161   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16162     if (Result)
16163       *Result = EvalResult.Val.getInt();
16164     return E;
16165   }
16166 
16167   // If our only note is the usual "invalid subexpression" note, just point
16168   // the caret at its location rather than producing an essentially
16169   // redundant note.
16170   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16171         diag::note_invalid_subexpr_in_const_expr) {
16172     DiagLoc = Notes[0].first;
16173     Notes.clear();
16174   }
16175 
16176   if (!Folded || !CanFold) {
16177     if (!Diagnoser.Suppress) {
16178       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16179       for (const PartialDiagnosticAt &Note : Notes)
16180         Diag(Note.first, Note.second);
16181     }
16182 
16183     return ExprError();
16184   }
16185 
16186   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16187   for (const PartialDiagnosticAt &Note : Notes)
16188     Diag(Note.first, Note.second);
16189 
16190   if (Result)
16191     *Result = EvalResult.Val.getInt();
16192   return E;
16193 }
16194 
16195 namespace {
16196   // Handle the case where we conclude a expression which we speculatively
16197   // considered to be unevaluated is actually evaluated.
16198   class TransformToPE : public TreeTransform<TransformToPE> {
16199     typedef TreeTransform<TransformToPE> BaseTransform;
16200 
16201   public:
16202     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16203 
16204     // Make sure we redo semantic analysis
16205     bool AlwaysRebuild() { return true; }
16206     bool ReplacingOriginal() { return true; }
16207 
16208     // We need to special-case DeclRefExprs referring to FieldDecls which
16209     // are not part of a member pointer formation; normal TreeTransforming
16210     // doesn't catch this case because of the way we represent them in the AST.
16211     // FIXME: This is a bit ugly; is it really the best way to handle this
16212     // case?
16213     //
16214     // Error on DeclRefExprs referring to FieldDecls.
16215     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16216       if (isa<FieldDecl>(E->getDecl()) &&
16217           !SemaRef.isUnevaluatedContext())
16218         return SemaRef.Diag(E->getLocation(),
16219                             diag::err_invalid_non_static_member_use)
16220             << E->getDecl() << E->getSourceRange();
16221 
16222       return BaseTransform::TransformDeclRefExpr(E);
16223     }
16224 
16225     // Exception: filter out member pointer formation
16226     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16227       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16228         return E;
16229 
16230       return BaseTransform::TransformUnaryOperator(E);
16231     }
16232 
16233     // The body of a lambda-expression is in a separate expression evaluation
16234     // context so never needs to be transformed.
16235     // FIXME: Ideally we wouldn't transform the closure type either, and would
16236     // just recreate the capture expressions and lambda expression.
16237     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16238       return SkipLambdaBody(E, Body);
16239     }
16240   };
16241 }
16242 
16243 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16244   assert(isUnevaluatedContext() &&
16245          "Should only transform unevaluated expressions");
16246   ExprEvalContexts.back().Context =
16247       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16248   if (isUnevaluatedContext())
16249     return E;
16250   return TransformToPE(*this).TransformExpr(E);
16251 }
16252 
16253 void
16254 Sema::PushExpressionEvaluationContext(
16255     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16256     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16257   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16258                                 LambdaContextDecl, ExprContext);
16259   Cleanup.reset();
16260   if (!MaybeODRUseExprs.empty())
16261     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16262 }
16263 
16264 void
16265 Sema::PushExpressionEvaluationContext(
16266     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16267     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16268   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16269   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16270 }
16271 
16272 namespace {
16273 
16274 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16275   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16276   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16277     if (E->getOpcode() == UO_Deref)
16278       return CheckPossibleDeref(S, E->getSubExpr());
16279   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16280     return CheckPossibleDeref(S, E->getBase());
16281   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16282     return CheckPossibleDeref(S, E->getBase());
16283   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16284     QualType Inner;
16285     QualType Ty = E->getType();
16286     if (const auto *Ptr = Ty->getAs<PointerType>())
16287       Inner = Ptr->getPointeeType();
16288     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16289       Inner = Arr->getElementType();
16290     else
16291       return nullptr;
16292 
16293     if (Inner->hasAttr(attr::NoDeref))
16294       return E;
16295   }
16296   return nullptr;
16297 }
16298 
16299 } // namespace
16300 
16301 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16302   for (const Expr *E : Rec.PossibleDerefs) {
16303     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16304     if (DeclRef) {
16305       const ValueDecl *Decl = DeclRef->getDecl();
16306       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16307           << Decl->getName() << E->getSourceRange();
16308       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16309     } else {
16310       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16311           << E->getSourceRange();
16312     }
16313   }
16314   Rec.PossibleDerefs.clear();
16315 }
16316 
16317 /// Check whether E, which is either a discarded-value expression or an
16318 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16319 /// and if so, remove it from the list of volatile-qualified assignments that
16320 /// we are going to warn are deprecated.
16321 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16322   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16323     return;
16324 
16325   // Note: ignoring parens here is not justified by the standard rules, but
16326   // ignoring parentheses seems like a more reasonable approach, and this only
16327   // drives a deprecation warning so doesn't affect conformance.
16328   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16329     if (BO->getOpcode() == BO_Assign) {
16330       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16331       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16332                  LHSs.end());
16333     }
16334   }
16335 }
16336 
16337 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16338   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16339       RebuildingImmediateInvocation)
16340     return E;
16341 
16342   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16343   /// It's OK if this fails; we'll also remove this in
16344   /// HandleImmediateInvocations, but catching it here allows us to avoid
16345   /// walking the AST looking for it in simple cases.
16346   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16347     if (auto *DeclRef =
16348             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16349       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16350 
16351   E = MaybeCreateExprWithCleanups(E);
16352 
16353   ConstantExpr *Res = ConstantExpr::Create(
16354       getASTContext(), E.get(),
16355       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16356                                    getASTContext()),
16357       /*IsImmediateInvocation*/ true);
16358   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16359   return Res;
16360 }
16361 
16362 static void EvaluateAndDiagnoseImmediateInvocation(
16363     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16364   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16365   Expr::EvalResult Eval;
16366   Eval.Diag = &Notes;
16367   ConstantExpr *CE = Candidate.getPointer();
16368   bool Result = CE->EvaluateAsConstantExpr(
16369       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16370   if (!Result || !Notes.empty()) {
16371     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16372     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16373       InnerExpr = FunctionalCast->getSubExpr();
16374     FunctionDecl *FD = nullptr;
16375     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16376       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16377     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16378       FD = Call->getConstructor();
16379     else
16380       llvm_unreachable("unhandled decl kind");
16381     assert(FD->isConsteval());
16382     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16383     for (auto &Note : Notes)
16384       SemaRef.Diag(Note.first, Note.second);
16385     return;
16386   }
16387   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16388 }
16389 
16390 static void RemoveNestedImmediateInvocation(
16391     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16392     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16393   struct ComplexRemove : TreeTransform<ComplexRemove> {
16394     using Base = TreeTransform<ComplexRemove>;
16395     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16396     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16397     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16398         CurrentII;
16399     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16400                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16401                   SmallVector<Sema::ImmediateInvocationCandidate,
16402                               4>::reverse_iterator Current)
16403         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16404     void RemoveImmediateInvocation(ConstantExpr* E) {
16405       auto It = std::find_if(CurrentII, IISet.rend(),
16406                              [E](Sema::ImmediateInvocationCandidate Elem) {
16407                                return Elem.getPointer() == E;
16408                              });
16409       assert(It != IISet.rend() &&
16410              "ConstantExpr marked IsImmediateInvocation should "
16411              "be present");
16412       It->setInt(1); // Mark as deleted
16413     }
16414     ExprResult TransformConstantExpr(ConstantExpr *E) {
16415       if (!E->isImmediateInvocation())
16416         return Base::TransformConstantExpr(E);
16417       RemoveImmediateInvocation(E);
16418       return Base::TransformExpr(E->getSubExpr());
16419     }
16420     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16421     /// we need to remove its DeclRefExpr from the DRSet.
16422     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16423       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16424       return Base::TransformCXXOperatorCallExpr(E);
16425     }
16426     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16427     /// here.
16428     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16429       if (!Init)
16430         return Init;
16431       /// ConstantExpr are the first layer of implicit node to be removed so if
16432       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16433       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16434         if (CE->isImmediateInvocation())
16435           RemoveImmediateInvocation(CE);
16436       return Base::TransformInitializer(Init, NotCopyInit);
16437     }
16438     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16439       DRSet.erase(E);
16440       return E;
16441     }
16442     bool AlwaysRebuild() { return false; }
16443     bool ReplacingOriginal() { return true; }
16444     bool AllowSkippingCXXConstructExpr() {
16445       bool Res = AllowSkippingFirstCXXConstructExpr;
16446       AllowSkippingFirstCXXConstructExpr = true;
16447       return Res;
16448     }
16449     bool AllowSkippingFirstCXXConstructExpr = true;
16450   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16451                 Rec.ImmediateInvocationCandidates, It);
16452 
16453   /// CXXConstructExpr with a single argument are getting skipped by
16454   /// TreeTransform in some situtation because they could be implicit. This
16455   /// can only occur for the top-level CXXConstructExpr because it is used
16456   /// nowhere in the expression being transformed therefore will not be rebuilt.
16457   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16458   /// skipping the first CXXConstructExpr.
16459   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16460     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16461 
16462   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16463   assert(Res.isUsable());
16464   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16465   It->getPointer()->setSubExpr(Res.get());
16466 }
16467 
16468 static void
16469 HandleImmediateInvocations(Sema &SemaRef,
16470                            Sema::ExpressionEvaluationContextRecord &Rec) {
16471   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16472        Rec.ReferenceToConsteval.size() == 0) ||
16473       SemaRef.RebuildingImmediateInvocation)
16474     return;
16475 
16476   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16477   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16478   /// need to remove ReferenceToConsteval in the immediate invocation.
16479   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16480 
16481     /// Prevent sema calls during the tree transform from adding pointers that
16482     /// are already in the sets.
16483     llvm::SaveAndRestore<bool> DisableIITracking(
16484         SemaRef.RebuildingImmediateInvocation, true);
16485 
16486     /// Prevent diagnostic during tree transfrom as they are duplicates
16487     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16488 
16489     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16490          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16491       if (!It->getInt())
16492         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16493   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16494              Rec.ReferenceToConsteval.size()) {
16495     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16496       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16497       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16498       bool VisitDeclRefExpr(DeclRefExpr *E) {
16499         DRSet.erase(E);
16500         return DRSet.size();
16501       }
16502     } Visitor(Rec.ReferenceToConsteval);
16503     Visitor.TraverseStmt(
16504         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16505   }
16506   for (auto CE : Rec.ImmediateInvocationCandidates)
16507     if (!CE.getInt())
16508       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16509   for (auto DR : Rec.ReferenceToConsteval) {
16510     auto *FD = cast<FunctionDecl>(DR->getDecl());
16511     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16512         << FD;
16513     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16514   }
16515 }
16516 
16517 void Sema::PopExpressionEvaluationContext() {
16518   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16519   unsigned NumTypos = Rec.NumTypos;
16520 
16521   if (!Rec.Lambdas.empty()) {
16522     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16523     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16524         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16525       unsigned D;
16526       if (Rec.isUnevaluated()) {
16527         // C++11 [expr.prim.lambda]p2:
16528         //   A lambda-expression shall not appear in an unevaluated operand
16529         //   (Clause 5).
16530         D = diag::err_lambda_unevaluated_operand;
16531       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16532         // C++1y [expr.const]p2:
16533         //   A conditional-expression e is a core constant expression unless the
16534         //   evaluation of e, following the rules of the abstract machine, would
16535         //   evaluate [...] a lambda-expression.
16536         D = diag::err_lambda_in_constant_expression;
16537       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16538         // C++17 [expr.prim.lamda]p2:
16539         // A lambda-expression shall not appear [...] in a template-argument.
16540         D = diag::err_lambda_in_invalid_context;
16541       } else
16542         llvm_unreachable("Couldn't infer lambda error message.");
16543 
16544       for (const auto *L : Rec.Lambdas)
16545         Diag(L->getBeginLoc(), D);
16546     }
16547   }
16548 
16549   WarnOnPendingNoDerefs(Rec);
16550   HandleImmediateInvocations(*this, Rec);
16551 
16552   // Warn on any volatile-qualified simple-assignments that are not discarded-
16553   // value expressions nor unevaluated operands (those cases get removed from
16554   // this list by CheckUnusedVolatileAssignment).
16555   for (auto *BO : Rec.VolatileAssignmentLHSs)
16556     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16557         << BO->getType();
16558 
16559   // When are coming out of an unevaluated context, clear out any
16560   // temporaries that we may have created as part of the evaluation of
16561   // the expression in that context: they aren't relevant because they
16562   // will never be constructed.
16563   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16564     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16565                              ExprCleanupObjects.end());
16566     Cleanup = Rec.ParentCleanup;
16567     CleanupVarDeclMarking();
16568     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16569   // Otherwise, merge the contexts together.
16570   } else {
16571     Cleanup.mergeFrom(Rec.ParentCleanup);
16572     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16573                             Rec.SavedMaybeODRUseExprs.end());
16574   }
16575 
16576   // Pop the current expression evaluation context off the stack.
16577   ExprEvalContexts.pop_back();
16578 
16579   // The global expression evaluation context record is never popped.
16580   ExprEvalContexts.back().NumTypos += NumTypos;
16581 }
16582 
16583 void Sema::DiscardCleanupsInEvaluationContext() {
16584   ExprCleanupObjects.erase(
16585          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16586          ExprCleanupObjects.end());
16587   Cleanup.reset();
16588   MaybeODRUseExprs.clear();
16589 }
16590 
16591 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16592   ExprResult Result = CheckPlaceholderExpr(E);
16593   if (Result.isInvalid())
16594     return ExprError();
16595   E = Result.get();
16596   if (!E->getType()->isVariablyModifiedType())
16597     return E;
16598   return TransformToPotentiallyEvaluated(E);
16599 }
16600 
16601 /// Are we in a context that is potentially constant evaluated per C++20
16602 /// [expr.const]p12?
16603 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16604   /// C++2a [expr.const]p12:
16605   //   An expression or conversion is potentially constant evaluated if it is
16606   switch (SemaRef.ExprEvalContexts.back().Context) {
16607     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16608       // -- a manifestly constant-evaluated expression,
16609     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16610     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16611     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16612       // -- a potentially-evaluated expression,
16613     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16614       // -- an immediate subexpression of a braced-init-list,
16615 
16616       // -- [FIXME] an expression of the form & cast-expression that occurs
16617       //    within a templated entity
16618       // -- a subexpression of one of the above that is not a subexpression of
16619       // a nested unevaluated operand.
16620       return true;
16621 
16622     case Sema::ExpressionEvaluationContext::Unevaluated:
16623     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16624       // Expressions in this context are never evaluated.
16625       return false;
16626   }
16627   llvm_unreachable("Invalid context");
16628 }
16629 
16630 /// Return true if this function has a calling convention that requires mangling
16631 /// in the size of the parameter pack.
16632 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16633   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16634   // we don't need parameter type sizes.
16635   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16636   if (!TT.isOSWindows() || !TT.isX86())
16637     return false;
16638 
16639   // If this is C++ and this isn't an extern "C" function, parameters do not
16640   // need to be complete. In this case, C++ mangling will apply, which doesn't
16641   // use the size of the parameters.
16642   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16643     return false;
16644 
16645   // Stdcall, fastcall, and vectorcall need this special treatment.
16646   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16647   switch (CC) {
16648   case CC_X86StdCall:
16649   case CC_X86FastCall:
16650   case CC_X86VectorCall:
16651     return true;
16652   default:
16653     break;
16654   }
16655   return false;
16656 }
16657 
16658 /// Require that all of the parameter types of function be complete. Normally,
16659 /// parameter types are only required to be complete when a function is called
16660 /// or defined, but to mangle functions with certain calling conventions, the
16661 /// mangler needs to know the size of the parameter list. In this situation,
16662 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16663 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16664 /// result in a linker error. Clang doesn't implement this behavior, and instead
16665 /// attempts to error at compile time.
16666 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16667                                                   SourceLocation Loc) {
16668   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16669     FunctionDecl *FD;
16670     ParmVarDecl *Param;
16671 
16672   public:
16673     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16674         : FD(FD), Param(Param) {}
16675 
16676     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16677       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16678       StringRef CCName;
16679       switch (CC) {
16680       case CC_X86StdCall:
16681         CCName = "stdcall";
16682         break;
16683       case CC_X86FastCall:
16684         CCName = "fastcall";
16685         break;
16686       case CC_X86VectorCall:
16687         CCName = "vectorcall";
16688         break;
16689       default:
16690         llvm_unreachable("CC does not need mangling");
16691       }
16692 
16693       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16694           << Param->getDeclName() << FD->getDeclName() << CCName;
16695     }
16696   };
16697 
16698   for (ParmVarDecl *Param : FD->parameters()) {
16699     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16700     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16701   }
16702 }
16703 
16704 namespace {
16705 enum class OdrUseContext {
16706   /// Declarations in this context are not odr-used.
16707   None,
16708   /// Declarations in this context are formally odr-used, but this is a
16709   /// dependent context.
16710   Dependent,
16711   /// Declarations in this context are odr-used but not actually used (yet).
16712   FormallyOdrUsed,
16713   /// Declarations in this context are used.
16714   Used
16715 };
16716 }
16717 
16718 /// Are we within a context in which references to resolved functions or to
16719 /// variables result in odr-use?
16720 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16721   OdrUseContext Result;
16722 
16723   switch (SemaRef.ExprEvalContexts.back().Context) {
16724     case Sema::ExpressionEvaluationContext::Unevaluated:
16725     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16726     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16727       return OdrUseContext::None;
16728 
16729     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16730     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16731       Result = OdrUseContext::Used;
16732       break;
16733 
16734     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16735       Result = OdrUseContext::FormallyOdrUsed;
16736       break;
16737 
16738     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16739       // A default argument formally results in odr-use, but doesn't actually
16740       // result in a use in any real sense until it itself is used.
16741       Result = OdrUseContext::FormallyOdrUsed;
16742       break;
16743   }
16744 
16745   if (SemaRef.CurContext->isDependentContext())
16746     return OdrUseContext::Dependent;
16747 
16748   return Result;
16749 }
16750 
16751 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16752   if (!Func->isConstexpr())
16753     return false;
16754 
16755   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16756     return true;
16757   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16758   return CCD && CCD->getInheritedConstructor();
16759 }
16760 
16761 /// Mark a function referenced, and check whether it is odr-used
16762 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16763 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16764                                   bool MightBeOdrUse) {
16765   assert(Func && "No function?");
16766 
16767   Func->setReferenced();
16768 
16769   // Recursive functions aren't really used until they're used from some other
16770   // context.
16771   bool IsRecursiveCall = CurContext == Func;
16772 
16773   // C++11 [basic.def.odr]p3:
16774   //   A function whose name appears as a potentially-evaluated expression is
16775   //   odr-used if it is the unique lookup result or the selected member of a
16776   //   set of overloaded functions [...].
16777   //
16778   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16779   // can just check that here.
16780   OdrUseContext OdrUse =
16781       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16782   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16783     OdrUse = OdrUseContext::FormallyOdrUsed;
16784 
16785   // Trivial default constructors and destructors are never actually used.
16786   // FIXME: What about other special members?
16787   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16788       OdrUse == OdrUseContext::Used) {
16789     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16790       if (Constructor->isDefaultConstructor())
16791         OdrUse = OdrUseContext::FormallyOdrUsed;
16792     if (isa<CXXDestructorDecl>(Func))
16793       OdrUse = OdrUseContext::FormallyOdrUsed;
16794   }
16795 
16796   // C++20 [expr.const]p12:
16797   //   A function [...] is needed for constant evaluation if it is [...] a
16798   //   constexpr function that is named by an expression that is potentially
16799   //   constant evaluated
16800   bool NeededForConstantEvaluation =
16801       isPotentiallyConstantEvaluatedContext(*this) &&
16802       isImplicitlyDefinableConstexprFunction(Func);
16803 
16804   // Determine whether we require a function definition to exist, per
16805   // C++11 [temp.inst]p3:
16806   //   Unless a function template specialization has been explicitly
16807   //   instantiated or explicitly specialized, the function template
16808   //   specialization is implicitly instantiated when the specialization is
16809   //   referenced in a context that requires a function definition to exist.
16810   // C++20 [temp.inst]p7:
16811   //   The existence of a definition of a [...] function is considered to
16812   //   affect the semantics of the program if the [...] function is needed for
16813   //   constant evaluation by an expression
16814   // C++20 [basic.def.odr]p10:
16815   //   Every program shall contain exactly one definition of every non-inline
16816   //   function or variable that is odr-used in that program outside of a
16817   //   discarded statement
16818   // C++20 [special]p1:
16819   //   The implementation will implicitly define [defaulted special members]
16820   //   if they are odr-used or needed for constant evaluation.
16821   //
16822   // Note that we skip the implicit instantiation of templates that are only
16823   // used in unused default arguments or by recursive calls to themselves.
16824   // This is formally non-conforming, but seems reasonable in practice.
16825   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16826                                              NeededForConstantEvaluation);
16827 
16828   // C++14 [temp.expl.spec]p6:
16829   //   If a template [...] is explicitly specialized then that specialization
16830   //   shall be declared before the first use of that specialization that would
16831   //   cause an implicit instantiation to take place, in every translation unit
16832   //   in which such a use occurs
16833   if (NeedDefinition &&
16834       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16835        Func->getMemberSpecializationInfo()))
16836     checkSpecializationVisibility(Loc, Func);
16837 
16838   if (getLangOpts().CUDA)
16839     CheckCUDACall(Loc, Func);
16840 
16841   if (getLangOpts().SYCLIsDevice)
16842     checkSYCLDeviceFunction(Loc, Func);
16843 
16844   // If we need a definition, try to create one.
16845   if (NeedDefinition && !Func->getBody()) {
16846     runWithSufficientStackSpace(Loc, [&] {
16847       if (CXXConstructorDecl *Constructor =
16848               dyn_cast<CXXConstructorDecl>(Func)) {
16849         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16850         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16851           if (Constructor->isDefaultConstructor()) {
16852             if (Constructor->isTrivial() &&
16853                 !Constructor->hasAttr<DLLExportAttr>())
16854               return;
16855             DefineImplicitDefaultConstructor(Loc, Constructor);
16856           } else if (Constructor->isCopyConstructor()) {
16857             DefineImplicitCopyConstructor(Loc, Constructor);
16858           } else if (Constructor->isMoveConstructor()) {
16859             DefineImplicitMoveConstructor(Loc, Constructor);
16860           }
16861         } else if (Constructor->getInheritedConstructor()) {
16862           DefineInheritingConstructor(Loc, Constructor);
16863         }
16864       } else if (CXXDestructorDecl *Destructor =
16865                      dyn_cast<CXXDestructorDecl>(Func)) {
16866         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16867         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16868           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16869             return;
16870           DefineImplicitDestructor(Loc, Destructor);
16871         }
16872         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16873           MarkVTableUsed(Loc, Destructor->getParent());
16874       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16875         if (MethodDecl->isOverloadedOperator() &&
16876             MethodDecl->getOverloadedOperator() == OO_Equal) {
16877           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16878           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16879             if (MethodDecl->isCopyAssignmentOperator())
16880               DefineImplicitCopyAssignment(Loc, MethodDecl);
16881             else if (MethodDecl->isMoveAssignmentOperator())
16882               DefineImplicitMoveAssignment(Loc, MethodDecl);
16883           }
16884         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16885                    MethodDecl->getParent()->isLambda()) {
16886           CXXConversionDecl *Conversion =
16887               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16888           if (Conversion->isLambdaToBlockPointerConversion())
16889             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16890           else
16891             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16892         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16893           MarkVTableUsed(Loc, MethodDecl->getParent());
16894       }
16895 
16896       if (Func->isDefaulted() && !Func->isDeleted()) {
16897         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16898         if (DCK != DefaultedComparisonKind::None)
16899           DefineDefaultedComparison(Loc, Func, DCK);
16900       }
16901 
16902       // Implicit instantiation of function templates and member functions of
16903       // class templates.
16904       if (Func->isImplicitlyInstantiable()) {
16905         TemplateSpecializationKind TSK =
16906             Func->getTemplateSpecializationKindForInstantiation();
16907         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16908         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16909         if (FirstInstantiation) {
16910           PointOfInstantiation = Loc;
16911           if (auto *MSI = Func->getMemberSpecializationInfo())
16912             MSI->setPointOfInstantiation(Loc);
16913             // FIXME: Notify listener.
16914           else
16915             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16916         } else if (TSK != TSK_ImplicitInstantiation) {
16917           // Use the point of use as the point of instantiation, instead of the
16918           // point of explicit instantiation (which we track as the actual point
16919           // of instantiation). This gives better backtraces in diagnostics.
16920           PointOfInstantiation = Loc;
16921         }
16922 
16923         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16924             Func->isConstexpr()) {
16925           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16926               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16927               CodeSynthesisContexts.size())
16928             PendingLocalImplicitInstantiations.push_back(
16929                 std::make_pair(Func, PointOfInstantiation));
16930           else if (Func->isConstexpr())
16931             // Do not defer instantiations of constexpr functions, to avoid the
16932             // expression evaluator needing to call back into Sema if it sees a
16933             // call to such a function.
16934             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16935           else {
16936             Func->setInstantiationIsPending(true);
16937             PendingInstantiations.push_back(
16938                 std::make_pair(Func, PointOfInstantiation));
16939             // Notify the consumer that a function was implicitly instantiated.
16940             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16941           }
16942         }
16943       } else {
16944         // Walk redefinitions, as some of them may be instantiable.
16945         for (auto i : Func->redecls()) {
16946           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16947             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16948         }
16949       }
16950     });
16951   }
16952 
16953   // C++14 [except.spec]p17:
16954   //   An exception-specification is considered to be needed when:
16955   //   - the function is odr-used or, if it appears in an unevaluated operand,
16956   //     would be odr-used if the expression were potentially-evaluated;
16957   //
16958   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16959   // function is a pure virtual function we're calling, and in that case the
16960   // function was selected by overload resolution and we need to resolve its
16961   // exception specification for a different reason.
16962   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16963   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16964     ResolveExceptionSpec(Loc, FPT);
16965 
16966   // If this is the first "real" use, act on that.
16967   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16968     // Keep track of used but undefined functions.
16969     if (!Func->isDefined()) {
16970       if (mightHaveNonExternalLinkage(Func))
16971         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16972       else if (Func->getMostRecentDecl()->isInlined() &&
16973                !LangOpts.GNUInline &&
16974                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16975         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16976       else if (isExternalWithNoLinkageType(Func))
16977         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16978     }
16979 
16980     // Some x86 Windows calling conventions mangle the size of the parameter
16981     // pack into the name. Computing the size of the parameters requires the
16982     // parameter types to be complete. Check that now.
16983     if (funcHasParameterSizeMangling(*this, Func))
16984       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16985 
16986     // In the MS C++ ABI, the compiler emits destructor variants where they are
16987     // used. If the destructor is used here but defined elsewhere, mark the
16988     // virtual base destructors referenced. If those virtual base destructors
16989     // are inline, this will ensure they are defined when emitting the complete
16990     // destructor variant. This checking may be redundant if the destructor is
16991     // provided later in this TU.
16992     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16993       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16994         CXXRecordDecl *Parent = Dtor->getParent();
16995         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16996           CheckCompleteDestructorVariant(Loc, Dtor);
16997       }
16998     }
16999 
17000     Func->markUsed(Context);
17001   }
17002 }
17003 
17004 /// Directly mark a variable odr-used. Given a choice, prefer to use
17005 /// MarkVariableReferenced since it does additional checks and then
17006 /// calls MarkVarDeclODRUsed.
17007 /// If the variable must be captured:
17008 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17009 ///  - else capture it in the DeclContext that maps to the
17010 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17011 static void
17012 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17013                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17014   // Keep track of used but undefined variables.
17015   // FIXME: We shouldn't suppress this warning for static data members.
17016   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17017       (!Var->isExternallyVisible() || Var->isInline() ||
17018        SemaRef.isExternalWithNoLinkageType(Var)) &&
17019       !(Var->isStaticDataMember() && Var->hasInit())) {
17020     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17021     if (old.isInvalid())
17022       old = Loc;
17023   }
17024   QualType CaptureType, DeclRefType;
17025   if (SemaRef.LangOpts.OpenMP)
17026     SemaRef.tryCaptureOpenMPLambdas(Var);
17027   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17028     /*EllipsisLoc*/ SourceLocation(),
17029     /*BuildAndDiagnose*/ true,
17030     CaptureType, DeclRefType,
17031     FunctionScopeIndexToStopAt);
17032 
17033   Var->markUsed(SemaRef.Context);
17034 }
17035 
17036 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17037                                              SourceLocation Loc,
17038                                              unsigned CapturingScopeIndex) {
17039   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17040 }
17041 
17042 static void
17043 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17044                                    ValueDecl *var, DeclContext *DC) {
17045   DeclContext *VarDC = var->getDeclContext();
17046 
17047   //  If the parameter still belongs to the translation unit, then
17048   //  we're actually just using one parameter in the declaration of
17049   //  the next.
17050   if (isa<ParmVarDecl>(var) &&
17051       isa<TranslationUnitDecl>(VarDC))
17052     return;
17053 
17054   // For C code, don't diagnose about capture if we're not actually in code
17055   // right now; it's impossible to write a non-constant expression outside of
17056   // function context, so we'll get other (more useful) diagnostics later.
17057   //
17058   // For C++, things get a bit more nasty... it would be nice to suppress this
17059   // diagnostic for certain cases like using a local variable in an array bound
17060   // for a member of a local class, but the correct predicate is not obvious.
17061   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17062     return;
17063 
17064   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17065   unsigned ContextKind = 3; // unknown
17066   if (isa<CXXMethodDecl>(VarDC) &&
17067       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17068     ContextKind = 2;
17069   } else if (isa<FunctionDecl>(VarDC)) {
17070     ContextKind = 0;
17071   } else if (isa<BlockDecl>(VarDC)) {
17072     ContextKind = 1;
17073   }
17074 
17075   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17076     << var << ValueKind << ContextKind << VarDC;
17077   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17078       << var;
17079 
17080   // FIXME: Add additional diagnostic info about class etc. which prevents
17081   // capture.
17082 }
17083 
17084 
17085 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17086                                       bool &SubCapturesAreNested,
17087                                       QualType &CaptureType,
17088                                       QualType &DeclRefType) {
17089    // Check whether we've already captured it.
17090   if (CSI->CaptureMap.count(Var)) {
17091     // If we found a capture, any subcaptures are nested.
17092     SubCapturesAreNested = true;
17093 
17094     // Retrieve the capture type for this variable.
17095     CaptureType = CSI->getCapture(Var).getCaptureType();
17096 
17097     // Compute the type of an expression that refers to this variable.
17098     DeclRefType = CaptureType.getNonReferenceType();
17099 
17100     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17101     // are mutable in the sense that user can change their value - they are
17102     // private instances of the captured declarations.
17103     const Capture &Cap = CSI->getCapture(Var);
17104     if (Cap.isCopyCapture() &&
17105         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17106         !(isa<CapturedRegionScopeInfo>(CSI) &&
17107           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17108       DeclRefType.addConst();
17109     return true;
17110   }
17111   return false;
17112 }
17113 
17114 // Only block literals, captured statements, and lambda expressions can
17115 // capture; other scopes don't work.
17116 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17117                                  SourceLocation Loc,
17118                                  const bool Diagnose, Sema &S) {
17119   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17120     return getLambdaAwareParentOfDeclContext(DC);
17121   else if (Var->hasLocalStorage()) {
17122     if (Diagnose)
17123        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17124   }
17125   return nullptr;
17126 }
17127 
17128 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17129 // certain types of variables (unnamed, variably modified types etc.)
17130 // so check for eligibility.
17131 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17132                                  SourceLocation Loc,
17133                                  const bool Diagnose, Sema &S) {
17134 
17135   bool IsBlock = isa<BlockScopeInfo>(CSI);
17136   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17137 
17138   // Lambdas are not allowed to capture unnamed variables
17139   // (e.g. anonymous unions).
17140   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17141   // assuming that's the intent.
17142   if (IsLambda && !Var->getDeclName()) {
17143     if (Diagnose) {
17144       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17145       S.Diag(Var->getLocation(), diag::note_declared_at);
17146     }
17147     return false;
17148   }
17149 
17150   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17151   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17152     if (Diagnose) {
17153       S.Diag(Loc, diag::err_ref_vm_type);
17154       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17155     }
17156     return false;
17157   }
17158   // Prohibit structs with flexible array members too.
17159   // We cannot capture what is in the tail end of the struct.
17160   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17161     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17162       if (Diagnose) {
17163         if (IsBlock)
17164           S.Diag(Loc, diag::err_ref_flexarray_type);
17165         else
17166           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17167         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17168       }
17169       return false;
17170     }
17171   }
17172   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17173   // Lambdas and captured statements are not allowed to capture __block
17174   // variables; they don't support the expected semantics.
17175   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17176     if (Diagnose) {
17177       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17178       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17179     }
17180     return false;
17181   }
17182   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17183   if (S.getLangOpts().OpenCL && IsBlock &&
17184       Var->getType()->isBlockPointerType()) {
17185     if (Diagnose)
17186       S.Diag(Loc, diag::err_opencl_block_ref_block);
17187     return false;
17188   }
17189 
17190   return true;
17191 }
17192 
17193 // Returns true if the capture by block was successful.
17194 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17195                                  SourceLocation Loc,
17196                                  const bool BuildAndDiagnose,
17197                                  QualType &CaptureType,
17198                                  QualType &DeclRefType,
17199                                  const bool Nested,
17200                                  Sema &S, bool Invalid) {
17201   bool ByRef = false;
17202 
17203   // Blocks are not allowed to capture arrays, excepting OpenCL.
17204   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17205   // (decayed to pointers).
17206   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17207     if (BuildAndDiagnose) {
17208       S.Diag(Loc, diag::err_ref_array_type);
17209       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17210       Invalid = true;
17211     } else {
17212       return false;
17213     }
17214   }
17215 
17216   // Forbid the block-capture of autoreleasing variables.
17217   if (!Invalid &&
17218       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17219     if (BuildAndDiagnose) {
17220       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17221         << /*block*/ 0;
17222       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17223       Invalid = true;
17224     } else {
17225       return false;
17226     }
17227   }
17228 
17229   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17230   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17231     QualType PointeeTy = PT->getPointeeType();
17232 
17233     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17234         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17235         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17236       if (BuildAndDiagnose) {
17237         SourceLocation VarLoc = Var->getLocation();
17238         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17239         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17240       }
17241     }
17242   }
17243 
17244   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17245   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17246       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17247     // Block capture by reference does not change the capture or
17248     // declaration reference types.
17249     ByRef = true;
17250   } else {
17251     // Block capture by copy introduces 'const'.
17252     CaptureType = CaptureType.getNonReferenceType().withConst();
17253     DeclRefType = CaptureType;
17254   }
17255 
17256   // Actually capture the variable.
17257   if (BuildAndDiagnose)
17258     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17259                     CaptureType, Invalid);
17260 
17261   return !Invalid;
17262 }
17263 
17264 
17265 /// Capture the given variable in the captured region.
17266 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17267                                     VarDecl *Var,
17268                                     SourceLocation Loc,
17269                                     const bool BuildAndDiagnose,
17270                                     QualType &CaptureType,
17271                                     QualType &DeclRefType,
17272                                     const bool RefersToCapturedVariable,
17273                                     Sema &S, bool Invalid) {
17274   // By default, capture variables by reference.
17275   bool ByRef = true;
17276   // Using an LValue reference type is consistent with Lambdas (see below).
17277   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17278     if (S.isOpenMPCapturedDecl(Var)) {
17279       bool HasConst = DeclRefType.isConstQualified();
17280       DeclRefType = DeclRefType.getUnqualifiedType();
17281       // Don't lose diagnostics about assignments to const.
17282       if (HasConst)
17283         DeclRefType.addConst();
17284     }
17285     // Do not capture firstprivates in tasks.
17286     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17287         OMPC_unknown)
17288       return true;
17289     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17290                                     RSI->OpenMPCaptureLevel);
17291   }
17292 
17293   if (ByRef)
17294     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17295   else
17296     CaptureType = DeclRefType;
17297 
17298   // Actually capture the variable.
17299   if (BuildAndDiagnose)
17300     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17301                     Loc, SourceLocation(), CaptureType, Invalid);
17302 
17303   return !Invalid;
17304 }
17305 
17306 /// Capture the given variable in the lambda.
17307 static bool captureInLambda(LambdaScopeInfo *LSI,
17308                             VarDecl *Var,
17309                             SourceLocation Loc,
17310                             const bool BuildAndDiagnose,
17311                             QualType &CaptureType,
17312                             QualType &DeclRefType,
17313                             const bool RefersToCapturedVariable,
17314                             const Sema::TryCaptureKind Kind,
17315                             SourceLocation EllipsisLoc,
17316                             const bool IsTopScope,
17317                             Sema &S, bool Invalid) {
17318   // Determine whether we are capturing by reference or by value.
17319   bool ByRef = false;
17320   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17321     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17322   } else {
17323     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17324   }
17325 
17326   // Compute the type of the field that will capture this variable.
17327   if (ByRef) {
17328     // C++11 [expr.prim.lambda]p15:
17329     //   An entity is captured by reference if it is implicitly or
17330     //   explicitly captured but not captured by copy. It is
17331     //   unspecified whether additional unnamed non-static data
17332     //   members are declared in the closure type for entities
17333     //   captured by reference.
17334     //
17335     // FIXME: It is not clear whether we want to build an lvalue reference
17336     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17337     // to do the former, while EDG does the latter. Core issue 1249 will
17338     // clarify, but for now we follow GCC because it's a more permissive and
17339     // easily defensible position.
17340     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17341   } else {
17342     // C++11 [expr.prim.lambda]p14:
17343     //   For each entity captured by copy, an unnamed non-static
17344     //   data member is declared in the closure type. The
17345     //   declaration order of these members is unspecified. The type
17346     //   of such a data member is the type of the corresponding
17347     //   captured entity if the entity is not a reference to an
17348     //   object, or the referenced type otherwise. [Note: If the
17349     //   captured entity is a reference to a function, the
17350     //   corresponding data member is also a reference to a
17351     //   function. - end note ]
17352     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17353       if (!RefType->getPointeeType()->isFunctionType())
17354         CaptureType = RefType->getPointeeType();
17355     }
17356 
17357     // Forbid the lambda copy-capture of autoreleasing variables.
17358     if (!Invalid &&
17359         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17360       if (BuildAndDiagnose) {
17361         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17362         S.Diag(Var->getLocation(), diag::note_previous_decl)
17363           << Var->getDeclName();
17364         Invalid = true;
17365       } else {
17366         return false;
17367       }
17368     }
17369 
17370     // Make sure that by-copy captures are of a complete and non-abstract type.
17371     if (!Invalid && BuildAndDiagnose) {
17372       if (!CaptureType->isDependentType() &&
17373           S.RequireCompleteSizedType(
17374               Loc, CaptureType,
17375               diag::err_capture_of_incomplete_or_sizeless_type,
17376               Var->getDeclName()))
17377         Invalid = true;
17378       else if (S.RequireNonAbstractType(Loc, CaptureType,
17379                                         diag::err_capture_of_abstract_type))
17380         Invalid = true;
17381     }
17382   }
17383 
17384   // Compute the type of a reference to this captured variable.
17385   if (ByRef)
17386     DeclRefType = CaptureType.getNonReferenceType();
17387   else {
17388     // C++ [expr.prim.lambda]p5:
17389     //   The closure type for a lambda-expression has a public inline
17390     //   function call operator [...]. This function call operator is
17391     //   declared const (9.3.1) if and only if the lambda-expression's
17392     //   parameter-declaration-clause is not followed by mutable.
17393     DeclRefType = CaptureType.getNonReferenceType();
17394     if (!LSI->Mutable && !CaptureType->isReferenceType())
17395       DeclRefType.addConst();
17396   }
17397 
17398   // Add the capture.
17399   if (BuildAndDiagnose)
17400     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17401                     Loc, EllipsisLoc, CaptureType, Invalid);
17402 
17403   return !Invalid;
17404 }
17405 
17406 bool Sema::tryCaptureVariable(
17407     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17408     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17409     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17410   // An init-capture is notionally from the context surrounding its
17411   // declaration, but its parent DC is the lambda class.
17412   DeclContext *VarDC = Var->getDeclContext();
17413   if (Var->isInitCapture())
17414     VarDC = VarDC->getParent();
17415 
17416   DeclContext *DC = CurContext;
17417   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17418       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17419   // We need to sync up the Declaration Context with the
17420   // FunctionScopeIndexToStopAt
17421   if (FunctionScopeIndexToStopAt) {
17422     unsigned FSIndex = FunctionScopes.size() - 1;
17423     while (FSIndex != MaxFunctionScopesIndex) {
17424       DC = getLambdaAwareParentOfDeclContext(DC);
17425       --FSIndex;
17426     }
17427   }
17428 
17429 
17430   // If the variable is declared in the current context, there is no need to
17431   // capture it.
17432   if (VarDC == DC) return true;
17433 
17434   // Capture global variables if it is required to use private copy of this
17435   // variable.
17436   bool IsGlobal = !Var->hasLocalStorage();
17437   if (IsGlobal &&
17438       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17439                                                 MaxFunctionScopesIndex)))
17440     return true;
17441   Var = Var->getCanonicalDecl();
17442 
17443   // Walk up the stack to determine whether we can capture the variable,
17444   // performing the "simple" checks that don't depend on type. We stop when
17445   // we've either hit the declared scope of the variable or find an existing
17446   // capture of that variable.  We start from the innermost capturing-entity
17447   // (the DC) and ensure that all intervening capturing-entities
17448   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17449   // declcontext can either capture the variable or have already captured
17450   // the variable.
17451   CaptureType = Var->getType();
17452   DeclRefType = CaptureType.getNonReferenceType();
17453   bool Nested = false;
17454   bool Explicit = (Kind != TryCapture_Implicit);
17455   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17456   do {
17457     // Only block literals, captured statements, and lambda expressions can
17458     // capture; other scopes don't work.
17459     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17460                                                               ExprLoc,
17461                                                               BuildAndDiagnose,
17462                                                               *this);
17463     // We need to check for the parent *first* because, if we *have*
17464     // private-captured a global variable, we need to recursively capture it in
17465     // intermediate blocks, lambdas, etc.
17466     if (!ParentDC) {
17467       if (IsGlobal) {
17468         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17469         break;
17470       }
17471       return true;
17472     }
17473 
17474     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17475     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17476 
17477 
17478     // Check whether we've already captured it.
17479     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17480                                              DeclRefType)) {
17481       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17482       break;
17483     }
17484     // If we are instantiating a generic lambda call operator body,
17485     // we do not want to capture new variables.  What was captured
17486     // during either a lambdas transformation or initial parsing
17487     // should be used.
17488     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17489       if (BuildAndDiagnose) {
17490         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17491         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17492           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17493           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17494           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17495         } else
17496           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17497       }
17498       return true;
17499     }
17500 
17501     // Try to capture variable-length arrays types.
17502     if (Var->getType()->isVariablyModifiedType()) {
17503       // We're going to walk down into the type and look for VLA
17504       // expressions.
17505       QualType QTy = Var->getType();
17506       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17507         QTy = PVD->getOriginalType();
17508       captureVariablyModifiedType(Context, QTy, CSI);
17509     }
17510 
17511     if (getLangOpts().OpenMP) {
17512       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17513         // OpenMP private variables should not be captured in outer scope, so
17514         // just break here. Similarly, global variables that are captured in a
17515         // target region should not be captured outside the scope of the region.
17516         if (RSI->CapRegionKind == CR_OpenMP) {
17517           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17518               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17519           // If the variable is private (i.e. not captured) and has variably
17520           // modified type, we still need to capture the type for correct
17521           // codegen in all regions, associated with the construct. Currently,
17522           // it is captured in the innermost captured region only.
17523           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17524               Var->getType()->isVariablyModifiedType()) {
17525             QualType QTy = Var->getType();
17526             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17527               QTy = PVD->getOriginalType();
17528             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17529                  I < E; ++I) {
17530               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17531                   FunctionScopes[FunctionScopesIndex - I]);
17532               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17533                      "Wrong number of captured regions associated with the "
17534                      "OpenMP construct.");
17535               captureVariablyModifiedType(Context, QTy, OuterRSI);
17536             }
17537           }
17538           bool IsTargetCap =
17539               IsOpenMPPrivateDecl != OMPC_private &&
17540               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17541                                          RSI->OpenMPCaptureLevel);
17542           // Do not capture global if it is not privatized in outer regions.
17543           bool IsGlobalCap =
17544               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17545                                                      RSI->OpenMPCaptureLevel);
17546 
17547           // When we detect target captures we are looking from inside the
17548           // target region, therefore we need to propagate the capture from the
17549           // enclosing region. Therefore, the capture is not initially nested.
17550           if (IsTargetCap)
17551             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17552 
17553           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17554               (IsGlobal && !IsGlobalCap)) {
17555             Nested = !IsTargetCap;
17556             bool HasConst = DeclRefType.isConstQualified();
17557             DeclRefType = DeclRefType.getUnqualifiedType();
17558             // Don't lose diagnostics about assignments to const.
17559             if (HasConst)
17560               DeclRefType.addConst();
17561             CaptureType = Context.getLValueReferenceType(DeclRefType);
17562             break;
17563           }
17564         }
17565       }
17566     }
17567     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17568       // No capture-default, and this is not an explicit capture
17569       // so cannot capture this variable.
17570       if (BuildAndDiagnose) {
17571         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17572         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17573         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17574           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17575                diag::note_lambda_decl);
17576         // FIXME: If we error out because an outer lambda can not implicitly
17577         // capture a variable that an inner lambda explicitly captures, we
17578         // should have the inner lambda do the explicit capture - because
17579         // it makes for cleaner diagnostics later.  This would purely be done
17580         // so that the diagnostic does not misleadingly claim that a variable
17581         // can not be captured by a lambda implicitly even though it is captured
17582         // explicitly.  Suggestion:
17583         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17584         //    at the function head
17585         //  - cache the StartingDeclContext - this must be a lambda
17586         //  - captureInLambda in the innermost lambda the variable.
17587       }
17588       return true;
17589     }
17590 
17591     FunctionScopesIndex--;
17592     DC = ParentDC;
17593     Explicit = false;
17594   } while (!VarDC->Equals(DC));
17595 
17596   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17597   // computing the type of the capture at each step, checking type-specific
17598   // requirements, and adding captures if requested.
17599   // If the variable had already been captured previously, we start capturing
17600   // at the lambda nested within that one.
17601   bool Invalid = false;
17602   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17603        ++I) {
17604     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17605 
17606     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17607     // certain types of variables (unnamed, variably modified types etc.)
17608     // so check for eligibility.
17609     if (!Invalid)
17610       Invalid =
17611           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17612 
17613     // After encountering an error, if we're actually supposed to capture, keep
17614     // capturing in nested contexts to suppress any follow-on diagnostics.
17615     if (Invalid && !BuildAndDiagnose)
17616       return true;
17617 
17618     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17619       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17620                                DeclRefType, Nested, *this, Invalid);
17621       Nested = true;
17622     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17623       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17624                                          CaptureType, DeclRefType, Nested,
17625                                          *this, Invalid);
17626       Nested = true;
17627     } else {
17628       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17629       Invalid =
17630           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17631                            DeclRefType, Nested, Kind, EllipsisLoc,
17632                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17633       Nested = true;
17634     }
17635 
17636     if (Invalid && !BuildAndDiagnose)
17637       return true;
17638   }
17639   return Invalid;
17640 }
17641 
17642 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17643                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17644   QualType CaptureType;
17645   QualType DeclRefType;
17646   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17647                             /*BuildAndDiagnose=*/true, CaptureType,
17648                             DeclRefType, nullptr);
17649 }
17650 
17651 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17652   QualType CaptureType;
17653   QualType DeclRefType;
17654   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17655                              /*BuildAndDiagnose=*/false, CaptureType,
17656                              DeclRefType, nullptr);
17657 }
17658 
17659 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17660   QualType CaptureType;
17661   QualType DeclRefType;
17662 
17663   // Determine whether we can capture this variable.
17664   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17665                          /*BuildAndDiagnose=*/false, CaptureType,
17666                          DeclRefType, nullptr))
17667     return QualType();
17668 
17669   return DeclRefType;
17670 }
17671 
17672 namespace {
17673 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17674 // The produced TemplateArgumentListInfo* points to data stored within this
17675 // object, so should only be used in contexts where the pointer will not be
17676 // used after the CopiedTemplateArgs object is destroyed.
17677 class CopiedTemplateArgs {
17678   bool HasArgs;
17679   TemplateArgumentListInfo TemplateArgStorage;
17680 public:
17681   template<typename RefExpr>
17682   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17683     if (HasArgs)
17684       E->copyTemplateArgumentsInto(TemplateArgStorage);
17685   }
17686   operator TemplateArgumentListInfo*()
17687 #ifdef __has_cpp_attribute
17688 #if __has_cpp_attribute(clang::lifetimebound)
17689   [[clang::lifetimebound]]
17690 #endif
17691 #endif
17692   {
17693     return HasArgs ? &TemplateArgStorage : nullptr;
17694   }
17695 };
17696 }
17697 
17698 /// Walk the set of potential results of an expression and mark them all as
17699 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17700 ///
17701 /// \return A new expression if we found any potential results, ExprEmpty() if
17702 ///         not, and ExprError() if we diagnosed an error.
17703 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17704                                                       NonOdrUseReason NOUR) {
17705   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17706   // an object that satisfies the requirements for appearing in a
17707   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17708   // is immediately applied."  This function handles the lvalue-to-rvalue
17709   // conversion part.
17710   //
17711   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17712   // transform it into the relevant kind of non-odr-use node and rebuild the
17713   // tree of nodes leading to it.
17714   //
17715   // This is a mini-TreeTransform that only transforms a restricted subset of
17716   // nodes (and only certain operands of them).
17717 
17718   // Rebuild a subexpression.
17719   auto Rebuild = [&](Expr *Sub) {
17720     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17721   };
17722 
17723   // Check whether a potential result satisfies the requirements of NOUR.
17724   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17725     // Any entity other than a VarDecl is always odr-used whenever it's named
17726     // in a potentially-evaluated expression.
17727     auto *VD = dyn_cast<VarDecl>(D);
17728     if (!VD)
17729       return true;
17730 
17731     // C++2a [basic.def.odr]p4:
17732     //   A variable x whose name appears as a potentially-evalauted expression
17733     //   e is odr-used by e unless
17734     //   -- x is a reference that is usable in constant expressions, or
17735     //   -- x is a variable of non-reference type that is usable in constant
17736     //      expressions and has no mutable subobjects, and e is an element of
17737     //      the set of potential results of an expression of
17738     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17739     //      conversion is applied, or
17740     //   -- x is a variable of non-reference type, and e is an element of the
17741     //      set of potential results of a discarded-value expression to which
17742     //      the lvalue-to-rvalue conversion is not applied
17743     //
17744     // We check the first bullet and the "potentially-evaluated" condition in
17745     // BuildDeclRefExpr. We check the type requirements in the second bullet
17746     // in CheckLValueToRValueConversionOperand below.
17747     switch (NOUR) {
17748     case NOUR_None:
17749     case NOUR_Unevaluated:
17750       llvm_unreachable("unexpected non-odr-use-reason");
17751 
17752     case NOUR_Constant:
17753       // Constant references were handled when they were built.
17754       if (VD->getType()->isReferenceType())
17755         return true;
17756       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17757         if (RD->hasMutableFields())
17758           return true;
17759       if (!VD->isUsableInConstantExpressions(S.Context))
17760         return true;
17761       break;
17762 
17763     case NOUR_Discarded:
17764       if (VD->getType()->isReferenceType())
17765         return true;
17766       break;
17767     }
17768     return false;
17769   };
17770 
17771   // Mark that this expression does not constitute an odr-use.
17772   auto MarkNotOdrUsed = [&] {
17773     S.MaybeODRUseExprs.remove(E);
17774     if (LambdaScopeInfo *LSI = S.getCurLambda())
17775       LSI->markVariableExprAsNonODRUsed(E);
17776   };
17777 
17778   // C++2a [basic.def.odr]p2:
17779   //   The set of potential results of an expression e is defined as follows:
17780   switch (E->getStmtClass()) {
17781   //   -- If e is an id-expression, ...
17782   case Expr::DeclRefExprClass: {
17783     auto *DRE = cast<DeclRefExpr>(E);
17784     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17785       break;
17786 
17787     // Rebuild as a non-odr-use DeclRefExpr.
17788     MarkNotOdrUsed();
17789     return DeclRefExpr::Create(
17790         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17791         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17792         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17793         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17794   }
17795 
17796   case Expr::FunctionParmPackExprClass: {
17797     auto *FPPE = cast<FunctionParmPackExpr>(E);
17798     // If any of the declarations in the pack is odr-used, then the expression
17799     // as a whole constitutes an odr-use.
17800     for (VarDecl *D : *FPPE)
17801       if (IsPotentialResultOdrUsed(D))
17802         return ExprEmpty();
17803 
17804     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17805     // nothing cares about whether we marked this as an odr-use, but it might
17806     // be useful for non-compiler tools.
17807     MarkNotOdrUsed();
17808     break;
17809   }
17810 
17811   //   -- If e is a subscripting operation with an array operand...
17812   case Expr::ArraySubscriptExprClass: {
17813     auto *ASE = cast<ArraySubscriptExpr>(E);
17814     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17815     if (!OldBase->getType()->isArrayType())
17816       break;
17817     ExprResult Base = Rebuild(OldBase);
17818     if (!Base.isUsable())
17819       return Base;
17820     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17821     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17822     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17823     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17824                                      ASE->getRBracketLoc());
17825   }
17826 
17827   case Expr::MemberExprClass: {
17828     auto *ME = cast<MemberExpr>(E);
17829     // -- If e is a class member access expression [...] naming a non-static
17830     //    data member...
17831     if (isa<FieldDecl>(ME->getMemberDecl())) {
17832       ExprResult Base = Rebuild(ME->getBase());
17833       if (!Base.isUsable())
17834         return Base;
17835       return MemberExpr::Create(
17836           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17837           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17838           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17839           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17840           ME->getObjectKind(), ME->isNonOdrUse());
17841     }
17842 
17843     if (ME->getMemberDecl()->isCXXInstanceMember())
17844       break;
17845 
17846     // -- If e is a class member access expression naming a static data member,
17847     //    ...
17848     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17849       break;
17850 
17851     // Rebuild as a non-odr-use MemberExpr.
17852     MarkNotOdrUsed();
17853     return MemberExpr::Create(
17854         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17855         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17856         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17857         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17858     return ExprEmpty();
17859   }
17860 
17861   case Expr::BinaryOperatorClass: {
17862     auto *BO = cast<BinaryOperator>(E);
17863     Expr *LHS = BO->getLHS();
17864     Expr *RHS = BO->getRHS();
17865     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17866     if (BO->getOpcode() == BO_PtrMemD) {
17867       ExprResult Sub = Rebuild(LHS);
17868       if (!Sub.isUsable())
17869         return Sub;
17870       LHS = Sub.get();
17871     //   -- If e is a comma expression, ...
17872     } else if (BO->getOpcode() == BO_Comma) {
17873       ExprResult Sub = Rebuild(RHS);
17874       if (!Sub.isUsable())
17875         return Sub;
17876       RHS = Sub.get();
17877     } else {
17878       break;
17879     }
17880     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17881                         LHS, RHS);
17882   }
17883 
17884   //   -- If e has the form (e1)...
17885   case Expr::ParenExprClass: {
17886     auto *PE = cast<ParenExpr>(E);
17887     ExprResult Sub = Rebuild(PE->getSubExpr());
17888     if (!Sub.isUsable())
17889       return Sub;
17890     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17891   }
17892 
17893   //   -- If e is a glvalue conditional expression, ...
17894   // We don't apply this to a binary conditional operator. FIXME: Should we?
17895   case Expr::ConditionalOperatorClass: {
17896     auto *CO = cast<ConditionalOperator>(E);
17897     ExprResult LHS = Rebuild(CO->getLHS());
17898     if (LHS.isInvalid())
17899       return ExprError();
17900     ExprResult RHS = Rebuild(CO->getRHS());
17901     if (RHS.isInvalid())
17902       return ExprError();
17903     if (!LHS.isUsable() && !RHS.isUsable())
17904       return ExprEmpty();
17905     if (!LHS.isUsable())
17906       LHS = CO->getLHS();
17907     if (!RHS.isUsable())
17908       RHS = CO->getRHS();
17909     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17910                                 CO->getCond(), LHS.get(), RHS.get());
17911   }
17912 
17913   // [Clang extension]
17914   //   -- If e has the form __extension__ e1...
17915   case Expr::UnaryOperatorClass: {
17916     auto *UO = cast<UnaryOperator>(E);
17917     if (UO->getOpcode() != UO_Extension)
17918       break;
17919     ExprResult Sub = Rebuild(UO->getSubExpr());
17920     if (!Sub.isUsable())
17921       return Sub;
17922     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17923                           Sub.get());
17924   }
17925 
17926   // [Clang extension]
17927   //   -- If e has the form _Generic(...), the set of potential results is the
17928   //      union of the sets of potential results of the associated expressions.
17929   case Expr::GenericSelectionExprClass: {
17930     auto *GSE = cast<GenericSelectionExpr>(E);
17931 
17932     SmallVector<Expr *, 4> AssocExprs;
17933     bool AnyChanged = false;
17934     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17935       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17936       if (AssocExpr.isInvalid())
17937         return ExprError();
17938       if (AssocExpr.isUsable()) {
17939         AssocExprs.push_back(AssocExpr.get());
17940         AnyChanged = true;
17941       } else {
17942         AssocExprs.push_back(OrigAssocExpr);
17943       }
17944     }
17945 
17946     return AnyChanged ? S.CreateGenericSelectionExpr(
17947                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17948                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17949                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17950                       : ExprEmpty();
17951   }
17952 
17953   // [Clang extension]
17954   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17955   //      results is the union of the sets of potential results of the
17956   //      second and third subexpressions.
17957   case Expr::ChooseExprClass: {
17958     auto *CE = cast<ChooseExpr>(E);
17959 
17960     ExprResult LHS = Rebuild(CE->getLHS());
17961     if (LHS.isInvalid())
17962       return ExprError();
17963 
17964     ExprResult RHS = Rebuild(CE->getLHS());
17965     if (RHS.isInvalid())
17966       return ExprError();
17967 
17968     if (!LHS.get() && !RHS.get())
17969       return ExprEmpty();
17970     if (!LHS.isUsable())
17971       LHS = CE->getLHS();
17972     if (!RHS.isUsable())
17973       RHS = CE->getRHS();
17974 
17975     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17976                              RHS.get(), CE->getRParenLoc());
17977   }
17978 
17979   // Step through non-syntactic nodes.
17980   case Expr::ConstantExprClass: {
17981     auto *CE = cast<ConstantExpr>(E);
17982     ExprResult Sub = Rebuild(CE->getSubExpr());
17983     if (!Sub.isUsable())
17984       return Sub;
17985     return ConstantExpr::Create(S.Context, Sub.get());
17986   }
17987 
17988   // We could mostly rely on the recursive rebuilding to rebuild implicit
17989   // casts, but not at the top level, so rebuild them here.
17990   case Expr::ImplicitCastExprClass: {
17991     auto *ICE = cast<ImplicitCastExpr>(E);
17992     // Only step through the narrow set of cast kinds we expect to encounter.
17993     // Anything else suggests we've left the region in which potential results
17994     // can be found.
17995     switch (ICE->getCastKind()) {
17996     case CK_NoOp:
17997     case CK_DerivedToBase:
17998     case CK_UncheckedDerivedToBase: {
17999       ExprResult Sub = Rebuild(ICE->getSubExpr());
18000       if (!Sub.isUsable())
18001         return Sub;
18002       CXXCastPath Path(ICE->path());
18003       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18004                                  ICE->getValueKind(), &Path);
18005     }
18006 
18007     default:
18008       break;
18009     }
18010     break;
18011   }
18012 
18013   default:
18014     break;
18015   }
18016 
18017   // Can't traverse through this node. Nothing to do.
18018   return ExprEmpty();
18019 }
18020 
18021 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18022   // Check whether the operand is or contains an object of non-trivial C union
18023   // type.
18024   if (E->getType().isVolatileQualified() &&
18025       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18026        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18027     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18028                           Sema::NTCUC_LValueToRValueVolatile,
18029                           NTCUK_Destruct|NTCUK_Copy);
18030 
18031   // C++2a [basic.def.odr]p4:
18032   //   [...] an expression of non-volatile-qualified non-class type to which
18033   //   the lvalue-to-rvalue conversion is applied [...]
18034   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18035     return E;
18036 
18037   ExprResult Result =
18038       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18039   if (Result.isInvalid())
18040     return ExprError();
18041   return Result.get() ? Result : E;
18042 }
18043 
18044 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18045   Res = CorrectDelayedTyposInExpr(Res);
18046 
18047   if (!Res.isUsable())
18048     return Res;
18049 
18050   // If a constant-expression is a reference to a variable where we delay
18051   // deciding whether it is an odr-use, just assume we will apply the
18052   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18053   // (a non-type template argument), we have special handling anyway.
18054   return CheckLValueToRValueConversionOperand(Res.get());
18055 }
18056 
18057 void Sema::CleanupVarDeclMarking() {
18058   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18059   // call.
18060   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18061   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18062 
18063   for (Expr *E : LocalMaybeODRUseExprs) {
18064     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18065       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18066                          DRE->getLocation(), *this);
18067     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18068       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18069                          *this);
18070     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18071       for (VarDecl *VD : *FP)
18072         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18073     } else {
18074       llvm_unreachable("Unexpected expression");
18075     }
18076   }
18077 
18078   assert(MaybeODRUseExprs.empty() &&
18079          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18080 }
18081 
18082 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18083                                     VarDecl *Var, Expr *E) {
18084   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18085           isa<FunctionParmPackExpr>(E)) &&
18086          "Invalid Expr argument to DoMarkVarDeclReferenced");
18087   Var->setReferenced();
18088 
18089   if (Var->isInvalidDecl())
18090     return;
18091 
18092   // Record a CUDA/HIP static device/constant variable if it is referenced
18093   // by host code. This is done conservatively, when the variable is referenced
18094   // in any of the following contexts:
18095   //   - a non-function context
18096   //   - a host function
18097   //   - a host device function
18098   // This also requires the reference of the static device/constant variable by
18099   // host code to be visible in the device compilation for the compiler to be
18100   // able to externalize the static device/constant variable.
18101   if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18102     auto *CurContext = SemaRef.CurContext;
18103     if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18104         cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18105         (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18106          !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18107       SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18108   }
18109 
18110   auto *MSI = Var->getMemberSpecializationInfo();
18111   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18112                                        : Var->getTemplateSpecializationKind();
18113 
18114   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18115   bool UsableInConstantExpr =
18116       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18117 
18118   // C++20 [expr.const]p12:
18119   //   A variable [...] is needed for constant evaluation if it is [...] a
18120   //   variable whose name appears as a potentially constant evaluated
18121   //   expression that is either a contexpr variable or is of non-volatile
18122   //   const-qualified integral type or of reference type
18123   bool NeededForConstantEvaluation =
18124       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18125 
18126   bool NeedDefinition =
18127       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18128 
18129   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18130          "Can't instantiate a partial template specialization.");
18131 
18132   // If this might be a member specialization of a static data member, check
18133   // the specialization is visible. We already did the checks for variable
18134   // template specializations when we created them.
18135   if (NeedDefinition && TSK != TSK_Undeclared &&
18136       !isa<VarTemplateSpecializationDecl>(Var))
18137     SemaRef.checkSpecializationVisibility(Loc, Var);
18138 
18139   // Perform implicit instantiation of static data members, static data member
18140   // templates of class templates, and variable template specializations. Delay
18141   // instantiations of variable templates, except for those that could be used
18142   // in a constant expression.
18143   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18144     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18145     // instantiation declaration if a variable is usable in a constant
18146     // expression (among other cases).
18147     bool TryInstantiating =
18148         TSK == TSK_ImplicitInstantiation ||
18149         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18150 
18151     if (TryInstantiating) {
18152       SourceLocation PointOfInstantiation =
18153           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18154       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18155       if (FirstInstantiation) {
18156         PointOfInstantiation = Loc;
18157         if (MSI)
18158           MSI->setPointOfInstantiation(PointOfInstantiation);
18159           // FIXME: Notify listener.
18160         else
18161           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18162       }
18163 
18164       if (UsableInConstantExpr) {
18165         // Do not defer instantiations of variables that could be used in a
18166         // constant expression.
18167         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18168           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18169         });
18170 
18171         // Re-set the member to trigger a recomputation of the dependence bits
18172         // for the expression.
18173         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18174           DRE->setDecl(DRE->getDecl());
18175         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18176           ME->setMemberDecl(ME->getMemberDecl());
18177       } else if (FirstInstantiation ||
18178                  isa<VarTemplateSpecializationDecl>(Var)) {
18179         // FIXME: For a specialization of a variable template, we don't
18180         // distinguish between "declaration and type implicitly instantiated"
18181         // and "implicit instantiation of definition requested", so we have
18182         // no direct way to avoid enqueueing the pending instantiation
18183         // multiple times.
18184         SemaRef.PendingInstantiations
18185             .push_back(std::make_pair(Var, PointOfInstantiation));
18186       }
18187     }
18188   }
18189 
18190   // C++2a [basic.def.odr]p4:
18191   //   A variable x whose name appears as a potentially-evaluated expression e
18192   //   is odr-used by e unless
18193   //   -- x is a reference that is usable in constant expressions
18194   //   -- x is a variable of non-reference type that is usable in constant
18195   //      expressions and has no mutable subobjects [FIXME], and e is an
18196   //      element of the set of potential results of an expression of
18197   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18198   //      conversion is applied
18199   //   -- x is a variable of non-reference type, and e is an element of the set
18200   //      of potential results of a discarded-value expression to which the
18201   //      lvalue-to-rvalue conversion is not applied [FIXME]
18202   //
18203   // We check the first part of the second bullet here, and
18204   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18205   // FIXME: To get the third bullet right, we need to delay this even for
18206   // variables that are not usable in constant expressions.
18207 
18208   // If we already know this isn't an odr-use, there's nothing more to do.
18209   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18210     if (DRE->isNonOdrUse())
18211       return;
18212   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18213     if (ME->isNonOdrUse())
18214       return;
18215 
18216   switch (OdrUse) {
18217   case OdrUseContext::None:
18218     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18219            "missing non-odr-use marking for unevaluated decl ref");
18220     break;
18221 
18222   case OdrUseContext::FormallyOdrUsed:
18223     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18224     // behavior.
18225     break;
18226 
18227   case OdrUseContext::Used:
18228     // If we might later find that this expression isn't actually an odr-use,
18229     // delay the marking.
18230     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18231       SemaRef.MaybeODRUseExprs.insert(E);
18232     else
18233       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18234     break;
18235 
18236   case OdrUseContext::Dependent:
18237     // If this is a dependent context, we don't need to mark variables as
18238     // odr-used, but we may still need to track them for lambda capture.
18239     // FIXME: Do we also need to do this inside dependent typeid expressions
18240     // (which are modeled as unevaluated at this point)?
18241     const bool RefersToEnclosingScope =
18242         (SemaRef.CurContext != Var->getDeclContext() &&
18243          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18244     if (RefersToEnclosingScope) {
18245       LambdaScopeInfo *const LSI =
18246           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18247       if (LSI && (!LSI->CallOperator ||
18248                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18249         // If a variable could potentially be odr-used, defer marking it so
18250         // until we finish analyzing the full expression for any
18251         // lvalue-to-rvalue
18252         // or discarded value conversions that would obviate odr-use.
18253         // Add it to the list of potential captures that will be analyzed
18254         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18255         // unless the variable is a reference that was initialized by a constant
18256         // expression (this will never need to be captured or odr-used).
18257         //
18258         // FIXME: We can simplify this a lot after implementing P0588R1.
18259         assert(E && "Capture variable should be used in an expression.");
18260         if (!Var->getType()->isReferenceType() ||
18261             !Var->isUsableInConstantExpressions(SemaRef.Context))
18262           LSI->addPotentialCapture(E->IgnoreParens());
18263       }
18264     }
18265     break;
18266   }
18267 }
18268 
18269 /// Mark a variable referenced, and check whether it is odr-used
18270 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18271 /// used directly for normal expressions referring to VarDecl.
18272 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18273   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18274 }
18275 
18276 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18277                                Decl *D, Expr *E, bool MightBeOdrUse) {
18278   if (SemaRef.isInOpenMPDeclareTargetContext())
18279     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18280 
18281   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18282     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18283     return;
18284   }
18285 
18286   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18287 
18288   // If this is a call to a method via a cast, also mark the method in the
18289   // derived class used in case codegen can devirtualize the call.
18290   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18291   if (!ME)
18292     return;
18293   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18294   if (!MD)
18295     return;
18296   // Only attempt to devirtualize if this is truly a virtual call.
18297   bool IsVirtualCall = MD->isVirtual() &&
18298                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18299   if (!IsVirtualCall)
18300     return;
18301 
18302   // If it's possible to devirtualize the call, mark the called function
18303   // referenced.
18304   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18305       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18306   if (DM)
18307     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18308 }
18309 
18310 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18311 ///
18312 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18313 /// handled with care if the DeclRefExpr is not newly-created.
18314 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18315   // TODO: update this with DR# once a defect report is filed.
18316   // C++11 defect. The address of a pure member should not be an ODR use, even
18317   // if it's a qualified reference.
18318   bool OdrUse = true;
18319   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18320     if (Method->isVirtual() &&
18321         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18322       OdrUse = false;
18323 
18324   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18325     if (!isConstantEvaluated() && FD->isConsteval() &&
18326         !RebuildingImmediateInvocation)
18327       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18328   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18329 }
18330 
18331 /// Perform reference-marking and odr-use handling for a MemberExpr.
18332 void Sema::MarkMemberReferenced(MemberExpr *E) {
18333   // C++11 [basic.def.odr]p2:
18334   //   A non-overloaded function whose name appears as a potentially-evaluated
18335   //   expression or a member of a set of candidate functions, if selected by
18336   //   overload resolution when referred to from a potentially-evaluated
18337   //   expression, is odr-used, unless it is a pure virtual function and its
18338   //   name is not explicitly qualified.
18339   bool MightBeOdrUse = true;
18340   if (E->performsVirtualDispatch(getLangOpts())) {
18341     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18342       if (Method->isPure())
18343         MightBeOdrUse = false;
18344   }
18345   SourceLocation Loc =
18346       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18347   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18348 }
18349 
18350 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18351 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18352   for (VarDecl *VD : *E)
18353     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18354 }
18355 
18356 /// Perform marking for a reference to an arbitrary declaration.  It
18357 /// marks the declaration referenced, and performs odr-use checking for
18358 /// functions and variables. This method should not be used when building a
18359 /// normal expression which refers to a variable.
18360 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18361                                  bool MightBeOdrUse) {
18362   if (MightBeOdrUse) {
18363     if (auto *VD = dyn_cast<VarDecl>(D)) {
18364       MarkVariableReferenced(Loc, VD);
18365       return;
18366     }
18367   }
18368   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18369     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18370     return;
18371   }
18372   D->setReferenced();
18373 }
18374 
18375 namespace {
18376   // Mark all of the declarations used by a type as referenced.
18377   // FIXME: Not fully implemented yet! We need to have a better understanding
18378   // of when we're entering a context we should not recurse into.
18379   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18380   // TreeTransforms rebuilding the type in a new context. Rather than
18381   // duplicating the TreeTransform logic, we should consider reusing it here.
18382   // Currently that causes problems when rebuilding LambdaExprs.
18383   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18384     Sema &S;
18385     SourceLocation Loc;
18386 
18387   public:
18388     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18389 
18390     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18391 
18392     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18393   };
18394 }
18395 
18396 bool MarkReferencedDecls::TraverseTemplateArgument(
18397     const TemplateArgument &Arg) {
18398   {
18399     // A non-type template argument is a constant-evaluated context.
18400     EnterExpressionEvaluationContext Evaluated(
18401         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18402     if (Arg.getKind() == TemplateArgument::Declaration) {
18403       if (Decl *D = Arg.getAsDecl())
18404         S.MarkAnyDeclReferenced(Loc, D, true);
18405     } else if (Arg.getKind() == TemplateArgument::Expression) {
18406       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18407     }
18408   }
18409 
18410   return Inherited::TraverseTemplateArgument(Arg);
18411 }
18412 
18413 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18414   MarkReferencedDecls Marker(*this, Loc);
18415   Marker.TraverseType(T);
18416 }
18417 
18418 namespace {
18419 /// Helper class that marks all of the declarations referenced by
18420 /// potentially-evaluated subexpressions as "referenced".
18421 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18422 public:
18423   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18424   bool SkipLocalVariables;
18425 
18426   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18427       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18428 
18429   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18430     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18431   }
18432 
18433   void VisitDeclRefExpr(DeclRefExpr *E) {
18434     // If we were asked not to visit local variables, don't.
18435     if (SkipLocalVariables) {
18436       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18437         if (VD->hasLocalStorage())
18438           return;
18439     }
18440 
18441     // FIXME: This can trigger the instantiation of the initializer of a
18442     // variable, which can cause the expression to become value-dependent
18443     // or error-dependent. Do we need to propagate the new dependence bits?
18444     S.MarkDeclRefReferenced(E);
18445   }
18446 
18447   void VisitMemberExpr(MemberExpr *E) {
18448     S.MarkMemberReferenced(E);
18449     Visit(E->getBase());
18450   }
18451 };
18452 } // namespace
18453 
18454 /// Mark any declarations that appear within this expression or any
18455 /// potentially-evaluated subexpressions as "referenced".
18456 ///
18457 /// \param SkipLocalVariables If true, don't mark local variables as
18458 /// 'referenced'.
18459 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18460                                             bool SkipLocalVariables) {
18461   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18462 }
18463 
18464 /// Emit a diagnostic that describes an effect on the run-time behavior
18465 /// of the program being compiled.
18466 ///
18467 /// This routine emits the given diagnostic when the code currently being
18468 /// type-checked is "potentially evaluated", meaning that there is a
18469 /// possibility that the code will actually be executable. Code in sizeof()
18470 /// expressions, code used only during overload resolution, etc., are not
18471 /// potentially evaluated. This routine will suppress such diagnostics or,
18472 /// in the absolutely nutty case of potentially potentially evaluated
18473 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18474 /// later.
18475 ///
18476 /// This routine should be used for all diagnostics that describe the run-time
18477 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18478 /// Failure to do so will likely result in spurious diagnostics or failures
18479 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18480 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18481                                const PartialDiagnostic &PD) {
18482   switch (ExprEvalContexts.back().Context) {
18483   case ExpressionEvaluationContext::Unevaluated:
18484   case ExpressionEvaluationContext::UnevaluatedList:
18485   case ExpressionEvaluationContext::UnevaluatedAbstract:
18486   case ExpressionEvaluationContext::DiscardedStatement:
18487     // The argument will never be evaluated, so don't complain.
18488     break;
18489 
18490   case ExpressionEvaluationContext::ConstantEvaluated:
18491     // Relevant diagnostics should be produced by constant evaluation.
18492     break;
18493 
18494   case ExpressionEvaluationContext::PotentiallyEvaluated:
18495   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18496     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18497       FunctionScopes.back()->PossiblyUnreachableDiags.
18498         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18499       return true;
18500     }
18501 
18502     // The initializer of a constexpr variable or of the first declaration of a
18503     // static data member is not syntactically a constant evaluated constant,
18504     // but nonetheless is always required to be a constant expression, so we
18505     // can skip diagnosing.
18506     // FIXME: Using the mangling context here is a hack.
18507     if (auto *VD = dyn_cast_or_null<VarDecl>(
18508             ExprEvalContexts.back().ManglingContextDecl)) {
18509       if (VD->isConstexpr() ||
18510           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18511         break;
18512       // FIXME: For any other kind of variable, we should build a CFG for its
18513       // initializer and check whether the context in question is reachable.
18514     }
18515 
18516     Diag(Loc, PD);
18517     return true;
18518   }
18519 
18520   return false;
18521 }
18522 
18523 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18524                                const PartialDiagnostic &PD) {
18525   return DiagRuntimeBehavior(
18526       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18527 }
18528 
18529 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18530                                CallExpr *CE, FunctionDecl *FD) {
18531   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18532     return false;
18533 
18534   // If we're inside a decltype's expression, don't check for a valid return
18535   // type or construct temporaries until we know whether this is the last call.
18536   if (ExprEvalContexts.back().ExprContext ==
18537       ExpressionEvaluationContextRecord::EK_Decltype) {
18538     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18539     return false;
18540   }
18541 
18542   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18543     FunctionDecl *FD;
18544     CallExpr *CE;
18545 
18546   public:
18547     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18548       : FD(FD), CE(CE) { }
18549 
18550     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18551       if (!FD) {
18552         S.Diag(Loc, diag::err_call_incomplete_return)
18553           << T << CE->getSourceRange();
18554         return;
18555       }
18556 
18557       S.Diag(Loc, diag::err_call_function_incomplete_return)
18558           << CE->getSourceRange() << FD << T;
18559       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18560           << FD->getDeclName();
18561     }
18562   } Diagnoser(FD, CE);
18563 
18564   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18565     return true;
18566 
18567   return false;
18568 }
18569 
18570 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18571 // will prevent this condition from triggering, which is what we want.
18572 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18573   SourceLocation Loc;
18574 
18575   unsigned diagnostic = diag::warn_condition_is_assignment;
18576   bool IsOrAssign = false;
18577 
18578   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18579     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18580       return;
18581 
18582     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18583 
18584     // Greylist some idioms by putting them into a warning subcategory.
18585     if (ObjCMessageExpr *ME
18586           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18587       Selector Sel = ME->getSelector();
18588 
18589       // self = [<foo> init...]
18590       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18591         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18592 
18593       // <foo> = [<bar> nextObject]
18594       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18595         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18596     }
18597 
18598     Loc = Op->getOperatorLoc();
18599   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18600     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18601       return;
18602 
18603     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18604     Loc = Op->getOperatorLoc();
18605   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18606     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18607   else {
18608     // Not an assignment.
18609     return;
18610   }
18611 
18612   Diag(Loc, diagnostic) << E->getSourceRange();
18613 
18614   SourceLocation Open = E->getBeginLoc();
18615   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18616   Diag(Loc, diag::note_condition_assign_silence)
18617         << FixItHint::CreateInsertion(Open, "(")
18618         << FixItHint::CreateInsertion(Close, ")");
18619 
18620   if (IsOrAssign)
18621     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18622       << FixItHint::CreateReplacement(Loc, "!=");
18623   else
18624     Diag(Loc, diag::note_condition_assign_to_comparison)
18625       << FixItHint::CreateReplacement(Loc, "==");
18626 }
18627 
18628 /// Redundant parentheses over an equality comparison can indicate
18629 /// that the user intended an assignment used as condition.
18630 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18631   // Don't warn if the parens came from a macro.
18632   SourceLocation parenLoc = ParenE->getBeginLoc();
18633   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18634     return;
18635   // Don't warn for dependent expressions.
18636   if (ParenE->isTypeDependent())
18637     return;
18638 
18639   Expr *E = ParenE->IgnoreParens();
18640 
18641   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18642     if (opE->getOpcode() == BO_EQ &&
18643         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18644                                                            == Expr::MLV_Valid) {
18645       SourceLocation Loc = opE->getOperatorLoc();
18646 
18647       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18648       SourceRange ParenERange = ParenE->getSourceRange();
18649       Diag(Loc, diag::note_equality_comparison_silence)
18650         << FixItHint::CreateRemoval(ParenERange.getBegin())
18651         << FixItHint::CreateRemoval(ParenERange.getEnd());
18652       Diag(Loc, diag::note_equality_comparison_to_assign)
18653         << FixItHint::CreateReplacement(Loc, "=");
18654     }
18655 }
18656 
18657 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18658                                        bool IsConstexpr) {
18659   DiagnoseAssignmentAsCondition(E);
18660   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18661     DiagnoseEqualityWithExtraParens(parenE);
18662 
18663   ExprResult result = CheckPlaceholderExpr(E);
18664   if (result.isInvalid()) return ExprError();
18665   E = result.get();
18666 
18667   if (!E->isTypeDependent()) {
18668     if (getLangOpts().CPlusPlus)
18669       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18670 
18671     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18672     if (ERes.isInvalid())
18673       return ExprError();
18674     E = ERes.get();
18675 
18676     QualType T = E->getType();
18677     if (!T->isScalarType()) { // C99 6.8.4.1p1
18678       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18679         << T << E->getSourceRange();
18680       return ExprError();
18681     }
18682     CheckBoolLikeConversion(E, Loc);
18683   }
18684 
18685   return E;
18686 }
18687 
18688 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18689                                            Expr *SubExpr, ConditionKind CK) {
18690   // Empty conditions are valid in for-statements.
18691   if (!SubExpr)
18692     return ConditionResult();
18693 
18694   ExprResult Cond;
18695   switch (CK) {
18696   case ConditionKind::Boolean:
18697     Cond = CheckBooleanCondition(Loc, SubExpr);
18698     break;
18699 
18700   case ConditionKind::ConstexprIf:
18701     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18702     break;
18703 
18704   case ConditionKind::Switch:
18705     Cond = CheckSwitchCondition(Loc, SubExpr);
18706     break;
18707   }
18708   if (Cond.isInvalid()) {
18709     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18710                               {SubExpr});
18711     if (!Cond.get())
18712       return ConditionError();
18713   }
18714   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18715   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18716   if (!FullExpr.get())
18717     return ConditionError();
18718 
18719   return ConditionResult(*this, nullptr, FullExpr,
18720                          CK == ConditionKind::ConstexprIf);
18721 }
18722 
18723 namespace {
18724   /// A visitor for rebuilding a call to an __unknown_any expression
18725   /// to have an appropriate type.
18726   struct RebuildUnknownAnyFunction
18727     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18728 
18729     Sema &S;
18730 
18731     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18732 
18733     ExprResult VisitStmt(Stmt *S) {
18734       llvm_unreachable("unexpected statement!");
18735     }
18736 
18737     ExprResult VisitExpr(Expr *E) {
18738       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18739         << E->getSourceRange();
18740       return ExprError();
18741     }
18742 
18743     /// Rebuild an expression which simply semantically wraps another
18744     /// expression which it shares the type and value kind of.
18745     template <class T> ExprResult rebuildSugarExpr(T *E) {
18746       ExprResult SubResult = Visit(E->getSubExpr());
18747       if (SubResult.isInvalid()) return ExprError();
18748 
18749       Expr *SubExpr = SubResult.get();
18750       E->setSubExpr(SubExpr);
18751       E->setType(SubExpr->getType());
18752       E->setValueKind(SubExpr->getValueKind());
18753       assert(E->getObjectKind() == OK_Ordinary);
18754       return E;
18755     }
18756 
18757     ExprResult VisitParenExpr(ParenExpr *E) {
18758       return rebuildSugarExpr(E);
18759     }
18760 
18761     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18762       return rebuildSugarExpr(E);
18763     }
18764 
18765     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18766       ExprResult SubResult = Visit(E->getSubExpr());
18767       if (SubResult.isInvalid()) return ExprError();
18768 
18769       Expr *SubExpr = SubResult.get();
18770       E->setSubExpr(SubExpr);
18771       E->setType(S.Context.getPointerType(SubExpr->getType()));
18772       assert(E->getValueKind() == VK_RValue);
18773       assert(E->getObjectKind() == OK_Ordinary);
18774       return E;
18775     }
18776 
18777     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18778       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18779 
18780       E->setType(VD->getType());
18781 
18782       assert(E->getValueKind() == VK_RValue);
18783       if (S.getLangOpts().CPlusPlus &&
18784           !(isa<CXXMethodDecl>(VD) &&
18785             cast<CXXMethodDecl>(VD)->isInstance()))
18786         E->setValueKind(VK_LValue);
18787 
18788       return E;
18789     }
18790 
18791     ExprResult VisitMemberExpr(MemberExpr *E) {
18792       return resolveDecl(E, E->getMemberDecl());
18793     }
18794 
18795     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18796       return resolveDecl(E, E->getDecl());
18797     }
18798   };
18799 }
18800 
18801 /// Given a function expression of unknown-any type, try to rebuild it
18802 /// to have a function type.
18803 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18804   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18805   if (Result.isInvalid()) return ExprError();
18806   return S.DefaultFunctionArrayConversion(Result.get());
18807 }
18808 
18809 namespace {
18810   /// A visitor for rebuilding an expression of type __unknown_anytype
18811   /// into one which resolves the type directly on the referring
18812   /// expression.  Strict preservation of the original source
18813   /// structure is not a goal.
18814   struct RebuildUnknownAnyExpr
18815     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18816 
18817     Sema &S;
18818 
18819     /// The current destination type.
18820     QualType DestType;
18821 
18822     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18823       : S(S), DestType(CastType) {}
18824 
18825     ExprResult VisitStmt(Stmt *S) {
18826       llvm_unreachable("unexpected statement!");
18827     }
18828 
18829     ExprResult VisitExpr(Expr *E) {
18830       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18831         << E->getSourceRange();
18832       return ExprError();
18833     }
18834 
18835     ExprResult VisitCallExpr(CallExpr *E);
18836     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18837 
18838     /// Rebuild an expression which simply semantically wraps another
18839     /// expression which it shares the type and value kind of.
18840     template <class T> ExprResult rebuildSugarExpr(T *E) {
18841       ExprResult SubResult = Visit(E->getSubExpr());
18842       if (SubResult.isInvalid()) return ExprError();
18843       Expr *SubExpr = SubResult.get();
18844       E->setSubExpr(SubExpr);
18845       E->setType(SubExpr->getType());
18846       E->setValueKind(SubExpr->getValueKind());
18847       assert(E->getObjectKind() == OK_Ordinary);
18848       return E;
18849     }
18850 
18851     ExprResult VisitParenExpr(ParenExpr *E) {
18852       return rebuildSugarExpr(E);
18853     }
18854 
18855     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18856       return rebuildSugarExpr(E);
18857     }
18858 
18859     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18860       const PointerType *Ptr = DestType->getAs<PointerType>();
18861       if (!Ptr) {
18862         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18863           << E->getSourceRange();
18864         return ExprError();
18865       }
18866 
18867       if (isa<CallExpr>(E->getSubExpr())) {
18868         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18869           << E->getSourceRange();
18870         return ExprError();
18871       }
18872 
18873       assert(E->getValueKind() == VK_RValue);
18874       assert(E->getObjectKind() == OK_Ordinary);
18875       E->setType(DestType);
18876 
18877       // Build the sub-expression as if it were an object of the pointee type.
18878       DestType = Ptr->getPointeeType();
18879       ExprResult SubResult = Visit(E->getSubExpr());
18880       if (SubResult.isInvalid()) return ExprError();
18881       E->setSubExpr(SubResult.get());
18882       return E;
18883     }
18884 
18885     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18886 
18887     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18888 
18889     ExprResult VisitMemberExpr(MemberExpr *E) {
18890       return resolveDecl(E, E->getMemberDecl());
18891     }
18892 
18893     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18894       return resolveDecl(E, E->getDecl());
18895     }
18896   };
18897 }
18898 
18899 /// Rebuilds a call expression which yielded __unknown_anytype.
18900 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18901   Expr *CalleeExpr = E->getCallee();
18902 
18903   enum FnKind {
18904     FK_MemberFunction,
18905     FK_FunctionPointer,
18906     FK_BlockPointer
18907   };
18908 
18909   FnKind Kind;
18910   QualType CalleeType = CalleeExpr->getType();
18911   if (CalleeType == S.Context.BoundMemberTy) {
18912     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18913     Kind = FK_MemberFunction;
18914     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18915   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18916     CalleeType = Ptr->getPointeeType();
18917     Kind = FK_FunctionPointer;
18918   } else {
18919     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18920     Kind = FK_BlockPointer;
18921   }
18922   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18923 
18924   // Verify that this is a legal result type of a function.
18925   if (DestType->isArrayType() || DestType->isFunctionType()) {
18926     unsigned diagID = diag::err_func_returning_array_function;
18927     if (Kind == FK_BlockPointer)
18928       diagID = diag::err_block_returning_array_function;
18929 
18930     S.Diag(E->getExprLoc(), diagID)
18931       << DestType->isFunctionType() << DestType;
18932     return ExprError();
18933   }
18934 
18935   // Otherwise, go ahead and set DestType as the call's result.
18936   E->setType(DestType.getNonLValueExprType(S.Context));
18937   E->setValueKind(Expr::getValueKindForType(DestType));
18938   assert(E->getObjectKind() == OK_Ordinary);
18939 
18940   // Rebuild the function type, replacing the result type with DestType.
18941   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18942   if (Proto) {
18943     // __unknown_anytype(...) is a special case used by the debugger when
18944     // it has no idea what a function's signature is.
18945     //
18946     // We want to build this call essentially under the K&R
18947     // unprototyped rules, but making a FunctionNoProtoType in C++
18948     // would foul up all sorts of assumptions.  However, we cannot
18949     // simply pass all arguments as variadic arguments, nor can we
18950     // portably just call the function under a non-variadic type; see
18951     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18952     // However, it turns out that in practice it is generally safe to
18953     // call a function declared as "A foo(B,C,D);" under the prototype
18954     // "A foo(B,C,D,...);".  The only known exception is with the
18955     // Windows ABI, where any variadic function is implicitly cdecl
18956     // regardless of its normal CC.  Therefore we change the parameter
18957     // types to match the types of the arguments.
18958     //
18959     // This is a hack, but it is far superior to moving the
18960     // corresponding target-specific code from IR-gen to Sema/AST.
18961 
18962     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18963     SmallVector<QualType, 8> ArgTypes;
18964     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18965       ArgTypes.reserve(E->getNumArgs());
18966       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18967         Expr *Arg = E->getArg(i);
18968         QualType ArgType = Arg->getType();
18969         if (E->isLValue()) {
18970           ArgType = S.Context.getLValueReferenceType(ArgType);
18971         } else if (E->isXValue()) {
18972           ArgType = S.Context.getRValueReferenceType(ArgType);
18973         }
18974         ArgTypes.push_back(ArgType);
18975       }
18976       ParamTypes = ArgTypes;
18977     }
18978     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18979                                          Proto->getExtProtoInfo());
18980   } else {
18981     DestType = S.Context.getFunctionNoProtoType(DestType,
18982                                                 FnType->getExtInfo());
18983   }
18984 
18985   // Rebuild the appropriate pointer-to-function type.
18986   switch (Kind) {
18987   case FK_MemberFunction:
18988     // Nothing to do.
18989     break;
18990 
18991   case FK_FunctionPointer:
18992     DestType = S.Context.getPointerType(DestType);
18993     break;
18994 
18995   case FK_BlockPointer:
18996     DestType = S.Context.getBlockPointerType(DestType);
18997     break;
18998   }
18999 
19000   // Finally, we can recurse.
19001   ExprResult CalleeResult = Visit(CalleeExpr);
19002   if (!CalleeResult.isUsable()) return ExprError();
19003   E->setCallee(CalleeResult.get());
19004 
19005   // Bind a temporary if necessary.
19006   return S.MaybeBindToTemporary(E);
19007 }
19008 
19009 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19010   // Verify that this is a legal result type of a call.
19011   if (DestType->isArrayType() || DestType->isFunctionType()) {
19012     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19013       << DestType->isFunctionType() << DestType;
19014     return ExprError();
19015   }
19016 
19017   // Rewrite the method result type if available.
19018   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19019     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19020     Method->setReturnType(DestType);
19021   }
19022 
19023   // Change the type of the message.
19024   E->setType(DestType.getNonReferenceType());
19025   E->setValueKind(Expr::getValueKindForType(DestType));
19026 
19027   return S.MaybeBindToTemporary(E);
19028 }
19029 
19030 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19031   // The only case we should ever see here is a function-to-pointer decay.
19032   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19033     assert(E->getValueKind() == VK_RValue);
19034     assert(E->getObjectKind() == OK_Ordinary);
19035 
19036     E->setType(DestType);
19037 
19038     // Rebuild the sub-expression as the pointee (function) type.
19039     DestType = DestType->castAs<PointerType>()->getPointeeType();
19040 
19041     ExprResult Result = Visit(E->getSubExpr());
19042     if (!Result.isUsable()) return ExprError();
19043 
19044     E->setSubExpr(Result.get());
19045     return E;
19046   } else if (E->getCastKind() == CK_LValueToRValue) {
19047     assert(E->getValueKind() == VK_RValue);
19048     assert(E->getObjectKind() == OK_Ordinary);
19049 
19050     assert(isa<BlockPointerType>(E->getType()));
19051 
19052     E->setType(DestType);
19053 
19054     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19055     DestType = S.Context.getLValueReferenceType(DestType);
19056 
19057     ExprResult Result = Visit(E->getSubExpr());
19058     if (!Result.isUsable()) return ExprError();
19059 
19060     E->setSubExpr(Result.get());
19061     return E;
19062   } else {
19063     llvm_unreachable("Unhandled cast type!");
19064   }
19065 }
19066 
19067 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19068   ExprValueKind ValueKind = VK_LValue;
19069   QualType Type = DestType;
19070 
19071   // We know how to make this work for certain kinds of decls:
19072 
19073   //  - functions
19074   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19075     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19076       DestType = Ptr->getPointeeType();
19077       ExprResult Result = resolveDecl(E, VD);
19078       if (Result.isInvalid()) return ExprError();
19079       return S.ImpCastExprToType(Result.get(), Type,
19080                                  CK_FunctionToPointerDecay, VK_RValue);
19081     }
19082 
19083     if (!Type->isFunctionType()) {
19084       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19085         << VD << E->getSourceRange();
19086       return ExprError();
19087     }
19088     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19089       // We must match the FunctionDecl's type to the hack introduced in
19090       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19091       // type. See the lengthy commentary in that routine.
19092       QualType FDT = FD->getType();
19093       const FunctionType *FnType = FDT->castAs<FunctionType>();
19094       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19095       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19096       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19097         SourceLocation Loc = FD->getLocation();
19098         FunctionDecl *NewFD = FunctionDecl::Create(
19099             S.Context, FD->getDeclContext(), Loc, Loc,
19100             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19101             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19102             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19103 
19104         if (FD->getQualifier())
19105           NewFD->setQualifierInfo(FD->getQualifierLoc());
19106 
19107         SmallVector<ParmVarDecl*, 16> Params;
19108         for (const auto &AI : FT->param_types()) {
19109           ParmVarDecl *Param =
19110             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19111           Param->setScopeInfo(0, Params.size());
19112           Params.push_back(Param);
19113         }
19114         NewFD->setParams(Params);
19115         DRE->setDecl(NewFD);
19116         VD = DRE->getDecl();
19117       }
19118     }
19119 
19120     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19121       if (MD->isInstance()) {
19122         ValueKind = VK_RValue;
19123         Type = S.Context.BoundMemberTy;
19124       }
19125 
19126     // Function references aren't l-values in C.
19127     if (!S.getLangOpts().CPlusPlus)
19128       ValueKind = VK_RValue;
19129 
19130   //  - variables
19131   } else if (isa<VarDecl>(VD)) {
19132     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19133       Type = RefTy->getPointeeType();
19134     } else if (Type->isFunctionType()) {
19135       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19136         << VD << E->getSourceRange();
19137       return ExprError();
19138     }
19139 
19140   //  - nothing else
19141   } else {
19142     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19143       << VD << E->getSourceRange();
19144     return ExprError();
19145   }
19146 
19147   // Modifying the declaration like this is friendly to IR-gen but
19148   // also really dangerous.
19149   VD->setType(DestType);
19150   E->setType(Type);
19151   E->setValueKind(ValueKind);
19152   return E;
19153 }
19154 
19155 /// Check a cast of an unknown-any type.  We intentionally only
19156 /// trigger this for C-style casts.
19157 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19158                                      Expr *CastExpr, CastKind &CastKind,
19159                                      ExprValueKind &VK, CXXCastPath &Path) {
19160   // The type we're casting to must be either void or complete.
19161   if (!CastType->isVoidType() &&
19162       RequireCompleteType(TypeRange.getBegin(), CastType,
19163                           diag::err_typecheck_cast_to_incomplete))
19164     return ExprError();
19165 
19166   // Rewrite the casted expression from scratch.
19167   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19168   if (!result.isUsable()) return ExprError();
19169 
19170   CastExpr = result.get();
19171   VK = CastExpr->getValueKind();
19172   CastKind = CK_NoOp;
19173 
19174   return CastExpr;
19175 }
19176 
19177 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19178   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19179 }
19180 
19181 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19182                                     Expr *arg, QualType &paramType) {
19183   // If the syntactic form of the argument is not an explicit cast of
19184   // any sort, just do default argument promotion.
19185   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19186   if (!castArg) {
19187     ExprResult result = DefaultArgumentPromotion(arg);
19188     if (result.isInvalid()) return ExprError();
19189     paramType = result.get()->getType();
19190     return result;
19191   }
19192 
19193   // Otherwise, use the type that was written in the explicit cast.
19194   assert(!arg->hasPlaceholderType());
19195   paramType = castArg->getTypeAsWritten();
19196 
19197   // Copy-initialize a parameter of that type.
19198   InitializedEntity entity =
19199     InitializedEntity::InitializeParameter(Context, paramType,
19200                                            /*consumed*/ false);
19201   return PerformCopyInitialization(entity, callLoc, arg);
19202 }
19203 
19204 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19205   Expr *orig = E;
19206   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19207   while (true) {
19208     E = E->IgnoreParenImpCasts();
19209     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19210       E = call->getCallee();
19211       diagID = diag::err_uncasted_call_of_unknown_any;
19212     } else {
19213       break;
19214     }
19215   }
19216 
19217   SourceLocation loc;
19218   NamedDecl *d;
19219   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19220     loc = ref->getLocation();
19221     d = ref->getDecl();
19222   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19223     loc = mem->getMemberLoc();
19224     d = mem->getMemberDecl();
19225   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19226     diagID = diag::err_uncasted_call_of_unknown_any;
19227     loc = msg->getSelectorStartLoc();
19228     d = msg->getMethodDecl();
19229     if (!d) {
19230       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19231         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19232         << orig->getSourceRange();
19233       return ExprError();
19234     }
19235   } else {
19236     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19237       << E->getSourceRange();
19238     return ExprError();
19239   }
19240 
19241   S.Diag(loc, diagID) << d << orig->getSourceRange();
19242 
19243   // Never recoverable.
19244   return ExprError();
19245 }
19246 
19247 /// Check for operands with placeholder types and complain if found.
19248 /// Returns ExprError() if there was an error and no recovery was possible.
19249 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19250   if (!Context.isDependenceAllowed()) {
19251     // C cannot handle TypoExpr nodes on either side of a binop because it
19252     // doesn't handle dependent types properly, so make sure any TypoExprs have
19253     // been dealt with before checking the operands.
19254     ExprResult Result = CorrectDelayedTyposInExpr(E);
19255     if (!Result.isUsable()) return ExprError();
19256     E = Result.get();
19257   }
19258 
19259   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19260   if (!placeholderType) return E;
19261 
19262   switch (placeholderType->getKind()) {
19263 
19264   // Overloaded expressions.
19265   case BuiltinType::Overload: {
19266     // Try to resolve a single function template specialization.
19267     // This is obligatory.
19268     ExprResult Result = E;
19269     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19270       return Result;
19271 
19272     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19273     // leaves Result unchanged on failure.
19274     Result = E;
19275     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19276       return Result;
19277 
19278     // If that failed, try to recover with a call.
19279     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19280                          /*complain*/ true);
19281     return Result;
19282   }
19283 
19284   // Bound member functions.
19285   case BuiltinType::BoundMember: {
19286     ExprResult result = E;
19287     const Expr *BME = E->IgnoreParens();
19288     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19289     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19290     if (isa<CXXPseudoDestructorExpr>(BME)) {
19291       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19292     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19293       if (ME->getMemberNameInfo().getName().getNameKind() ==
19294           DeclarationName::CXXDestructorName)
19295         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19296     }
19297     tryToRecoverWithCall(result, PD,
19298                          /*complain*/ true);
19299     return result;
19300   }
19301 
19302   // ARC unbridged casts.
19303   case BuiltinType::ARCUnbridgedCast: {
19304     Expr *realCast = stripARCUnbridgedCast(E);
19305     diagnoseARCUnbridgedCast(realCast);
19306     return realCast;
19307   }
19308 
19309   // Expressions of unknown type.
19310   case BuiltinType::UnknownAny:
19311     return diagnoseUnknownAnyExpr(*this, E);
19312 
19313   // Pseudo-objects.
19314   case BuiltinType::PseudoObject:
19315     return checkPseudoObjectRValue(E);
19316 
19317   case BuiltinType::BuiltinFn: {
19318     // Accept __noop without parens by implicitly converting it to a call expr.
19319     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19320     if (DRE) {
19321       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19322       if (FD->getBuiltinID() == Builtin::BI__noop) {
19323         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19324                               CK_BuiltinFnToFnPtr)
19325                 .get();
19326         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19327                                 VK_RValue, SourceLocation(),
19328                                 FPOptionsOverride());
19329       }
19330     }
19331 
19332     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19333     return ExprError();
19334   }
19335 
19336   case BuiltinType::IncompleteMatrixIdx:
19337     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19338              ->getRowIdx()
19339              ->getBeginLoc(),
19340          diag::err_matrix_incomplete_index);
19341     return ExprError();
19342 
19343   // Expressions of unknown type.
19344   case BuiltinType::OMPArraySection:
19345     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19346     return ExprError();
19347 
19348   // Expressions of unknown type.
19349   case BuiltinType::OMPArrayShaping:
19350     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19351 
19352   case BuiltinType::OMPIterator:
19353     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19354 
19355   // Everything else should be impossible.
19356 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19357   case BuiltinType::Id:
19358 #include "clang/Basic/OpenCLImageTypes.def"
19359 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19360   case BuiltinType::Id:
19361 #include "clang/Basic/OpenCLExtensionTypes.def"
19362 #define SVE_TYPE(Name, Id, SingletonId) \
19363   case BuiltinType::Id:
19364 #include "clang/Basic/AArch64SVEACLETypes.def"
19365 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19366   case BuiltinType::Id:
19367 #include "clang/Basic/PPCTypes.def"
19368 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19369 #define PLACEHOLDER_TYPE(Id, SingletonId)
19370 #include "clang/AST/BuiltinTypes.def"
19371     break;
19372   }
19373 
19374   llvm_unreachable("invalid placeholder type!");
19375 }
19376 
19377 bool Sema::CheckCaseExpression(Expr *E) {
19378   if (E->isTypeDependent())
19379     return true;
19380   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19381     return E->getType()->isIntegralOrEnumerationType();
19382   return false;
19383 }
19384 
19385 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19386 ExprResult
19387 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19388   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19389          "Unknown Objective-C Boolean value!");
19390   QualType BoolT = Context.ObjCBuiltinBoolTy;
19391   if (!Context.getBOOLDecl()) {
19392     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19393                         Sema::LookupOrdinaryName);
19394     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19395       NamedDecl *ND = Result.getFoundDecl();
19396       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19397         Context.setBOOLDecl(TD);
19398     }
19399   }
19400   if (Context.getBOOLDecl())
19401     BoolT = Context.getBOOLType();
19402   return new (Context)
19403       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19404 }
19405 
19406 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19407     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19408     SourceLocation RParen) {
19409 
19410   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19411 
19412   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19413     return Spec.getPlatform() == Platform;
19414   });
19415 
19416   VersionTuple Version;
19417   if (Spec != AvailSpecs.end())
19418     Version = Spec->getVersion();
19419 
19420   // The use of `@available` in the enclosing function should be analyzed to
19421   // warn when it's used inappropriately (i.e. not if(@available)).
19422   if (getCurFunctionOrMethodDecl())
19423     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19424   else if (getCurBlock() || getCurLambda())
19425     getCurFunction()->HasPotentialAvailabilityViolations = true;
19426 
19427   return new (Context)
19428       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19429 }
19430 
19431 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19432                                     ArrayRef<Expr *> SubExprs, QualType T) {
19433   if (!Context.getLangOpts().RecoveryAST)
19434     return ExprError();
19435 
19436   if (isSFINAEContext())
19437     return ExprError();
19438 
19439   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19440     // We don't know the concrete type, fallback to dependent type.
19441     T = Context.DependentTy;
19442   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19443 }
19444